Search code examples
javaarraysdrop-down-menuscrollbarjoptionpane

JOptionPane component seems differ


When I use the following code the look of the JOptionPane seems to differ depending on how many items of data are held within the array. Sometimes a drop down scrolling list (similar to a JComboBox). At other times, when the array holds more items, a component similar to a JList.

Object wid = JOptionPane.showInputDialog(null,
                    "Choose Width",
                    "Select a Width", JOptionPane.QUESTION_MESSAGE,
                    null, width, "9");

Any suggestions would be appreciated as to how to control which type of component is displayed, and its look in terms of size and colours?


Solution

  • If you use the method showInputDialog you have no control how the dialog is constructed or designed. This method exists to have a quick way to construct an input dialog that works when you don't care how it looks or behaves. It all depends on the look an feel of the environment.
    Mostly that means in this case 19 elements or lower result in a JComboBox and 20 or more result in a JList.

    If you want to have full control of the GUI components you need to design them for yourself. It is not as hard as it sounds. Have a look at this code. It will always result in a combo box no matter how much items it has.

    final int items = 100;
    
    // create items
    String[] width = new String[items];
    for(int i = 0; i < items; i++) width[i] = Integer.toString(i);
    
    // create the panel
    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(2,1));
    JLabel label = new JLabel("Choose Width");
    JComboBox<String> cmbBox = new JComboBox<>(width);
    cmbBox.setSelectedIndex(8);
    panel.add(label);
    panel.add(cmbBox);
    
    // show dialog
    int res = JOptionPane.showConfirmDialog(null, panel,
                "Select a Width", JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.QUESTION_MESSAGE, null);
    
    // get selection
    if(res == JOptionPane.OK_OPTION){
        String sel = String.valueOf(cmbBox.getSelectedItem());
        System.out.println("you selected: " + sel);
    }