Java ComboBox in JOptionPane


 

Java ComboBox in JOptionPane

In this section, you will learn how to create combobox in JOptionPane dialog box.

In this section, you will learn how to create combobox in JOptionPane dialog box.

Java ComboBox in JOptionPane

In this section, you will learn how to create combo box in JOptionPane dialog box. We have created a button to perform an action.On clicking the button, you will get the dialog box with combo box in it. 

Here is the code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ComboBoxInJOptionPane extends JFrame{
  static final String Select = "Sports";
   String input = "";
  public ComboBoxInJOptionPane() {
    super(Select);
    JButton button=new JButton("Add");
  
  ActionListener lst = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    String[] sport = new String[] {"Cricket""FootBall""Tennis""Hockey" };
     input = (StringJOptionPane.showInputDialog(ComboBoxInJOptionPane.this,
"Please select your favorite sport"
,Select, JOptionPane.INFORMATION_MESSAGE, 
null, sport,
"Tennis");
     JOptionPane.showMessageDialog(null,"You have selected: "+input);
    }
    };
  System.out.println(input);
  button.addActionListener(lst);
  add(button);
  pack();
    setVisible(true);

  }
  public static void main(String argv[]) {
    new ComboBoxInJOptionPane();
  }
}

Ads