TheJustikar1996
TheJustikar1996

Reputation: 3

Java JOptionPane woth scrollable checkbutton list

I have a little Problem here. I'm currently working at a GUI to organise my series, that im watching/have watched. In this part I wanted a frame to open with all the different genres in JCheckBox'es, that should return a boolean-array, where each index represents the genre of this index and the value if it JCheckBox was clicked.

I decied to do this woth a JOptionPane, because the JOptioPane.showInputPane()-funktion offers to give an Object-array as parameter, that will be displayed in the JOptionPane. To this point, my code is working perfectly:

    String[] genres = IO.getGenres();
    JCheckBox[] check = new JCheckBox[genres.length];

    for(int i = 0; i < genres.length; i++)
        check[i] = new JCheckBox(genres[i]);    

    boolean[] ret = new boolean[genres.length];     

    int answer = JOptionPane.showConfirmDialog(null, new Object[]{"Choose gernes:", check}, "Genres" , JOptionPane.OK_CANCEL_OPTION);

    if(answer == JOptionPane.OK_OPTION)
    {
        for(int i = 0; ; i++)
            ret[i] = check[i].isSelected();

    }else if(answer == JOptionPane.CANCEL_OPTION || answer == JOptionPane.ERROR_MESSAGE)
    {
        for(int i = 0; i < genres.length; i++)
            ret[i] = false;
    }

    return ret;

The problem is that the JOptionPane grows to large, with to many genres. So how can I make a scrollable list of JCheckBox'es, that is displayed in the JOptionPane? Or is there a better way to work around?

Upvotes: 0

Views: 419

Answers (1)

Sergiy Medvynskyy
Sergiy Medvynskyy

Reputation: 11327

You can simply layout your check boxes in a panel and transfer a wrapping scroll pane to your JOptionPane. Something like this:

JPanel layoutPanel = new JPanel(new GridLayout(genres.length, 1));
for (JCheckBox c : check) {
  layoutPanel.add(c);
}
JScrollPane scroller = new JScrollPane(layoutPanel);
scroller.setPreferredSize(new Dimension(300, 500));
int answer = JOptionPane.showConfirmDialog(null, scroller, "Genres" , JOptionPane.OK_CANCEL_OPTION);

Upvotes: 2

Related Questions