About ComboBox in JOptionPane using dialog

Ajay Victor picture Ajay Victor · Oct 23, 2016 · Viewed 11k times · Source

I would like to get a dialog box using joptionpane as a Combobox where I want to accept the values of day, month and year. I want all these in a single dialog box. What I've is this:

 String[] date= {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"};
    String[] month= {"1","2","3","4","5","6","7","8","9","10","11","12"};
    String[] year={"2016","2017","2018","2019","2020"};
    JComboBox jcd = new JComboBox(date);
    JComboBox jcm = new JComboBox(date);
    JComboBox jcy = new JComboBox(date);
      jcd.setEditable(true);
      jcm.setEditable(true);
      jcy.setEditable(true);
    JOptionPane.showMessageDialog( null, jcd, "Date", JOptionPane.QUESTION_MESSAGE);
    JOptionPane.showMessageDialog( null, jcm, "Month", JOptionPane.QUESTION_MESSAGE);
    JOptionPane.showMessageDialog( null, jcy, "Year", JOptionPane.QUESTION_MESSAGE);

    int resd=(int) jcd.getSelectedItem();
    int resm=(int) jcd.getSelectedItem();
    int resy=(int) jcd.getSelectedItem();

Here the issue is that I'm getting 3 dialog boxes one after another for entering values where I want to make it as a single dialog box which have multiple comboboxes.

Answer

c0der picture c0der · Oct 23, 2016

Here is something to get you started. The idea is:
create a JOptionPane
add to it and configure it as you need,
use a JDialog to display the JOptionPane content:

import java.io.IOException;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JOptionPane;

class Test {


    public static void  main(String args[]) throws IOException  {


        String[] date= {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"};
        String[] month= {"1","2","3","4","5","6","7","8","9","10","11","12"};
        String[] year={"2016","2017","2018","2019","2020"};
        JComboBox jcd = new JComboBox(date);
        JComboBox jcm = new JComboBox(month);
        JComboBox jcy = new JComboBox(year);

        jcd.setEditable(true);
        jcm.setEditable(true);
        jcy.setEditable(true);

        //create a JOptionPane
        Object[] options = new Object[] {};
        JOptionPane jop = new JOptionPane("Please Select",
                                        JOptionPane.QUESTION_MESSAGE,
                                        JOptionPane.DEFAULT_OPTION,
                                        null,options, null);

        //add combos to JOptionPane
        jop.add(jcd);
        jop.add(jcm);
        jop.add(jcy);

        //create a JDialog and add JOptionPane to it 
        JDialog diag = new JDialog();
        diag.getContentPane().add(jop);
        diag.pack();
        diag.setVisible(true);
    }
}

enter image description here