JFileChooser embedded in a JPanel

情到浓时终转凉″ 提交于 2019-11-29 10:04:36

JFileChooser extends JComponent and Component so you should be able to add it directly to your frame.

JFileChooser fc = ...
JPanel panel ...
panel.add(fc);

To access the "buttons" in the file chooser, you will have to add an ActionListener to it:

fileChooser.addActionListener(this);
[...]

public void actionPerformed(ActionEvent action)
{
    if (action.getActionCommand().equals("CancelSelection"))
    {
        System.out.printf("CancelSelection\n");
        this.setVisible(false);
        this.dispose();
    }
    if (action.getActionCommand().equals("ApproveSelection"))
    {
        System.out.printf("ApproveSelection\n");
        this.setVisible(false);
        this.dispose();
    }
}

If you are adding the JFileChooser on the fly, you will need to call revalidate().

Steve's answer is correct. You can add a JFileChooser to other containers.

To Johannes: thanks for your useful snippet.

Instead of "ApproveSelection" and "CancelSelection" I used the defined constants JFileChooser.APPROVE_SELECTION and JFileChooser.CANCEL_SELECTION

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!