LaPalme
LaPalme

Reputation: 339

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 :

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.

Upvotes: 2

Views: 791

Answers (1)

trashgod
trashgod

Reputation: 205785

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);

Upvotes: 1

Related Questions