I'm trying to add an ActionListener to my ComboBox. I want to open a form when a item is selected from the box. I successfully implemented it on a JButton but I can't figure out how to do it in a combobox. Can someone please help me out?
我正在尝试将ActionListener添加到我的ComboBox中。我想从框中选择一个项目时打开一个表单。我在JButton上成功实现了它,但我无法弄清楚如何在组合框中实现它。有人可以帮帮我吗?
JComboBox<String> valBox = new JComboBox<>();
valBox.addItem("Apparat");
valBox.addItem("Smycke");
valBox.addItem("Aktie");
södra.add(valBox);
valBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (valBox.getSelectedIndex() == 0)
nyLyss.ApparatForm.form1();
}
});
The code that I wan't to execute when the first item is selected is this one:
选择第一个项目时我不想执行的代码是这个:
class nyLyss implements ActionListener{
public void actionPerformed(ActionEvent ae) {
try{
ApparatForm form1 = new ApparatForm();
int svar = JOptionPane.showConfirmDialog(Layout.this, form1);
if(svar != JOptionPane.OK_OPTION)
return;
String namn = form1.getNamn();
int inköpspris = form1.getPris();
int slitage = form1.getPris();
// saker ap = new saker(namn, inköpspris, slitage);
// alla.add(ap);
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(Layout.this, "Felaktig indata!");
}
}
}
Thanks! :)
谢谢! :)
1 个解决方案
#1
0
I would solve the problem with a ItemStateChanged listener on my combobox. Here a short example with a combobox called "mycombobox".
我会在我的组合框上用ItemStateChanged监听器解决问题。这是一个名为“mycombobox”的组合框的简短示例。
private void mycomboboxItemStateChanged(java.awt.event.ItemEvent evt) {
System.out.println(mycombobox.getSelectedItem());
}
The result is, that the application is printing out the selected item after every change of the selected item in the combobox "mycombobox".
结果是,应用程序在组合框“mycombobox”中每次更改所选项目后打印出所选项目。
#1
0
I would solve the problem with a ItemStateChanged listener on my combobox. Here a short example with a combobox called "mycombobox".
我会在我的组合框上用ItemStateChanged监听器解决问题。这是一个名为“mycombobox”的组合框的简短示例。
private void mycomboboxItemStateChanged(java.awt.event.ItemEvent evt) {
System.out.println(mycombobox.getSelectedItem());
}
The result is, that the application is printing out the selected item after every change of the selected item in the combobox "mycombobox".
结果是,应用程序在组合框“mycombobox”中每次更改所选项目后打印出所选项目。