Reputation: 1
I need to make a drop down box with two choices in java and when either option or word is clicked it runs the program that I have created with else if statements. Can anyone help?? Right now my program opens each option by inputing 1 or 2. Want a drop box of some sort instead. Thanks.
Upvotes: 0
Views: 253
Reputation: 1819
This code will update the label when you use the combobox.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ComboTest extends JFrame {
public static void main(String[] args) {
new ComboTest();
}
public ComboTest() {
final JLabel label = new JLabel("Select something in the ComboBox");
String[] options = {"1", "2"};
JComboBox combo = new JComboBox(options);
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
String selected = (String) cb.getSelectedItem();
label.setText("You selected: " + selected);
}
});
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel main = new JPanel(new BorderLayout());
main.add(combo, BorderLayout.CENTER);
main.add(label, BorderLayout.SOUTH);
getContentPane().add(main);
pack();
setVisible(true);
}
}
Upvotes: 1