Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customizing javax.swing.JFileChooser to include an additional JTextField

I want to include an additional (optional) JTextField in the FileChooser, allowing the user to fill it in while choosing the file rather than giving them an additional prompt after they make their choice. Has anybody attempted something similar and found a working solution?

My target result would look something like this:

http://imgur.com/lVMd6

like image 447
sgtFloyd Avatar asked Jan 28 '10 16:01

sgtFloyd


1 Answers

The documented way to add controls to a JFileChooser is via the setAccessory(JComponent) method.

JTextField field = new JTextField("Hello, World");
JPanel accessory = new JPanel();
accessory.setLayout(new FlowLayout());
accessory.add(field);

JFileChooser chooser = new JFileChooser();
chooser.setAccessory(accessory);
int ret = chooser.showOpenDialog(frame);

However, this will layout the new control on the right of the dialog (exact positioning is probably locale-dependent).

To locate the component to the position you want it, you'll probably have to walk the component graph and manipulate it. This would be a very fragile approach and you may be better off just building your own dialog.

This could incorporate a file chooser:

JFileChooser chooser = new JFileChooser();
chooser.addActionListener(new ActionListener() {
  @Override
  public void actionPerformed(ActionEvent e) {
    // TODO - wire into something
    System.out.println(e);
  }
});

JTextField field = new JTextField("Hello, World");

JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(chooser, BorderLayout.CENTER);
panel.add(field, BorderLayout.SOUTH);
like image 198
McDowell Avatar answered Oct 16 '22 19:10

McDowell