Java jcombobox将其与jbutton一起使用
我想知道如何设置一个与Jbutton一起工作的JComboBox。在JcomboBox中选择某个对象会在按下按钮时更改计算。到目前为止,这就是我所拥有的,但它似乎不起作用,我也不确定它到底出了什么问题Java jcombobox将其与jbutton一起使用,java,swing,jbutton,actionlistener,jcombobox,Java,Swing,Jbutton,Actionlistener,Jcombobox,我想知道如何设置一个与Jbutton一起工作的JComboBox。在JcomboBox中选择某个对象会在按下按钮时更改计算。到目前为止,这就是我所拥有的,但它似乎不起作用,我也不确定它到底出了什么问题 //JComboBox objectList = new JComboBox(); String[] objectStrings = { "Triangle", "Box", "Done" }; JComboBox objectList = new JComboBox(ob
//JComboBox objectList = new JComboBox();
String[] objectStrings = { "Triangle", "Box", "Done" };
JComboBox objectList = new JComboBox(objectStrings);
//objectList.setModel(new DefaultComboBoxModel(new String[]{"Triangle", "Box", "Done"}));
objectList.setSelectedIndex(0);
final int object = objectList.getSelectedIndex();
objectList.setBounds(180, 7, 86, 20);
objectList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (object == 2) {
System.exit(0);
}
}
});
frmPrestonPalecekWeek.getContentPane().add(objectList);
JButton btnCalculate = new JButton("Calculate!");
btnCalculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String box;
String done;
Box a;
Triangle b;
b = new Triangle(Double.parseDouble(txtSidea.getText()), Double.parseDouble(txtSideb.getText()), Double.parseDouble(txtSidec.getText()));
a = new Box(Double.parseDouble(txtSidea.getText()), Double.parseDouble(txtSideb.getText()), Double.parseDouble(txtSidec.getText()));
if (object == 0) {
txtOutput.setText("this is the volume " + a.getVolume());
}
else if (object == 2) {
System.exit(0);
}
}
在按钮的操作侦听器中,您应该检查组合框中所选的项目,而不是使用初始化期间设置的索引(
final int object=objectList.getSelectedIndex()
),因为组合选择更改时它不会更改。此变量甚至被标记为final
例如,您可以执行类似的操作:
btnCalculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int selectedIndex = objectList.getSelectedIndex();
if (selectedIndex == 0) {
...
} else if selectedIndex == 2) {
...
}
}
}
在按钮的操作侦听器中,您应该检查组合框中所选的项目,而不是使用初始化期间设置的索引(
final int object=objectList.getSelectedIndex()
),因为组合选择更改时它不会更改。此变量甚至被标记为final
例如,您可以执行类似的操作:
btnCalculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int selectedIndex = objectList.getSelectedIndex();
if (selectedIndex == 0) {
...
} else if selectedIndex == 2) {
...
}
}
}