我需要在java中创建一个带有两个选择的下拉框,当单击选项或单词时,它会运行我用else if语句创建的程序。有人可以帮忙吗?现在我的程序通过输入 1 或 2 打开每个选项。想要一个某种类型的投递箱。谢谢。
最佳答案
当您使用组合框时,此代码将更新标签。
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);
}
}
关于java - 我需要在java中制作一个有两个选择的下拉框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4419531/