Search code examples
javaswingjoptionpane

JOptionPane.showConfirmDialog with a JScrollPane and a maximum size


I was trying to make a JFrame with a JScrollPane containing hundreds of JRadioButtons and two JButtons below (OK and Cancel). Finally I discovered the JOptionPane.showConfirmDialog(...) method.

It seems to be perfect for what I want : From a first JFrame, open a "window" with a Scroll containing my radio buttons and get the selected one in my first JFrame when I click on "OK". However, when the showConfirmDialog appears, there is no JScrollPane, and we cannot see the bottom of the window (there are hundreds of radio buttons). So :

  • I tried to call JOptionPane.showConfirmDialog(myScrollPane) instead of adding the JScrollPane to a JPanel and call the method with a JPanel... it didn't work

  • I tried to initialize a JOptionPane object, then set its maximum size, then call the method showConfirmDialog with the initialized object but it doesn't work because "the method must be called in a static way".

So I need your help, here is my code, and I don't understand what is wrong and why I don't have a scroll with my radio buttons in the confirm dialog.

public void buildMambaJobPathWindow(ArrayList<String> list) {
    ButtonGroup buttonGroup = new ButtonGroup();
    JPanel radioPanel = new JPanel(new GridLayout(0,1));
    for(int i=0; i<list.size(); i++) {
        JRadioButton radioButton = new JRadioButton(list.get(i));
        buttonGroup.add(radioButton);
        radioButton.addActionListener(this);
        radioButton.setActionCommand(list.get(i));
        radioPanel.add(radioButton);
    }

    JScrollPane myScrollPane = new JScrollPane(radioPanel);         
    myScrollPane.setMaximumSize(new Dimension(600,600));

    JOptionPane.showConfirmDialog(null, myScrollPane);
}

// Listens to the radio buttons
public void actionPerformed(ActionEvent e) {
    String result = e.getActionCommand();
}

Thank you for your time.


Solution

  • As shown here, you can override the scroll pane's getPreferredSize() method to establish the desired size. If the content is larger in either dimension, the corresponding scroll bar will appear as needed.

    JScrollPane myScrollPane = new JScrollPane(radioPanel){
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(600, 600);
        }
    };
    JOptionPane.showConfirmDialog(null, myScrollPane);