import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class CustomJFileChooser extends JFrame
{
private JButton jb;
private JFileChooser jf;
private JPanel jp;
private JLabel jl;
public CustomJFileChooser()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
// Set frame properties
setTitle("Custom JFileChooser");
setSize(400,400);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
// Create JButton
jb=new JButton("Open JFileChooser");
// Add ActionListener to JButton
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
// Create JFileChooser
jf=new JFileChooser();
// Create JPanel
jp=new JPanel();
// Create JLabel
jl=new JLabel("I am a label on custom JFileChooser");
// Add JLabel to the JPanel
jp.add(jl);
// This is that method, do it before showOpenDialog!
jf.setAccessory(jp);
// Show Open Dialog
jf.showOpenDialog(null);
}
});
// Add JButton to the JFrame
add(jb);
}
public static void main(String args[])
{
new CustomJFileChooser();
}
}
Output of the CustomJFileChooser
Custom JFileChooser Screenshot |
This is not a hack, it is just a feature provided. This is the way you can add your own custom components to JFileChooser. You don't actually need the JPanel, I just added it, you can directly add JLabel to it. But in order to have a layout of the components we added i added JPanel. Good to know if we can add components in a certain layout to the JFileChooser without JPanel and without disturbing the layout of the JFileChooser's by-birth components.