javaswingjfilechooser

JFileChooser with additional JCheckBox for setting the file opening method


I am using JFileChooser as a component for selecting files in this code.

I need one additional input from the user to trigger the way how the file shall be opened. In my use case if it shall be read to the RAM entirely or not.

I know I can ask user elsewhere but the best would be if I can add JCheckBox to the JFileChooser dialog. I want to achieve something as on the picture.

enter image description here

How I can do that and how I read the status of user input?


Solution

  • I figured out the simplest is to utilize the mechanism that is intended for image thumbnails of selected files. By providing so called Accessory Component, which must be a child class of JComponent, through calling JFileChooser.setAccessory you can obtain a space to the right of file selecting rectangle.

    Including minimal example:

    JFileChooser fc = new JFileChooser();
    fc.setDialogTitle("Open DEN file...");
    fc.setAccessory(new CheckBoxAccessory());
    int returnVal = fc.showOpenDialog(frame);
    CheckBoxAccessory cba = (CheckBoxAccessory)fc.getAccessory();
    boolean useVirtualStack = cba.isBoxSelected();
    JOptionPane.showMessageDialog(null, String.format("selected=%b", useVirtualStack));
    

    where the class CheckBoxAccessory looks as follows

    public class CheckBoxAccessory extends JComponent {
        JCheckBox virtualCheckBox;
        boolean checkBoxInit = false;
        
        int preferredWidth = 150;
        int preferredHeight = 100;//Mostly ignored as it is  
        int checkBoxPosX = 5;
        int checkBoxPosY = 20;
        int checkBoxWidth = preferredWidth;
        int checkBoxHeight = 20;
        
        public CheckBoxAccessory()
        {
            setPreferredSize(new Dimension(preferredWidth, preferredHeight));
            virtualCheckBox = new JCheckBox("Virtual stack", checkBoxInit);
            virtualCheckBox.setBounds(checkBoxPosX, checkBoxPosY, checkBoxWidth, checkBoxHeight);
            this.add(virtualCheckBox);
        }
        
        public boolean isBoxSelected()
        {
            return virtualCheckBox.isSelected();
        }
    }
    

    The result looks as follows enter image description here

    Disadvantage is that you will not get the whole component to play with but just a relatively small box. Thus the visual look is not what I initially wanted, but when you are no Picasso, you won't care. Advantage of this solution is that you can even react on change of selected file, which is in more details described in https://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html#accessory