JFileChooser embedded in a JPanel
Asked Answered
A

4

8

I am writing a java program that needs a file open dialog. The file open dialog isn't difficult, I'm hoping to use a JFileChooser. My problem is that I would like to have a dual pane JFrame (consisting of 2 JPanels). The left panel would have a JList, and the right panel would have a file open dialog.

When I use JFileChooser.showOpenDialog() this opens the dialog box above all other windows, which isn't what I want. Is there any way to have the JFileChooser (or maybe another file selection dialog) display inside a JPanel and not pop-up above it?

Here is the code that I've tried, at this point it's very simplified. I'm only trying to get the JFileChooser to be embedded in the JPanel at this point.

public class JFC extends JFrame{
    public JFC()
    {
        setSize(800,600);

        JPanel panel= new JPanel();

        JFileChooser chooser = new JFileChooser();
        panel.add(chooser);

        setVisible(true);

        chooser.showOpenDialog(null);
    }

    public static void main(String[] args)
    {
        JFC blah = new JFC();
    }
}

I have also tried calling chooser.showOpenDialog with this and panel, but to no avail. Also, I have tried adding the JFileChooser directly to the frame. Both of the attempts listed above still have the JFileChooser pop up in front of the frame or panel (depending on which I add the JFileChooser to).

Archives answered 3/11, 2008 at 18:51 Comment(0)
D
11

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

JFileChooser fc = ...
JPanel panel ...
panel.add(fc);
Downtown answered 3/11, 2008 at 18:58 Comment(0)
G
5

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();
    }
}
Grus answered 5/11, 2008 at 9:41 Comment(0)
S
3

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.

Stichometry answered 3/11, 2008 at 19:18 Comment(0)
I
2

To Johannes: thanks for your useful snippet.

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

Impervious answered 10/9, 2009 at 16:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.