gpt4 book ai didi

java - jcombobox 与 jbutton 一起使用

转载 作者:行者123 更新时间:2023-12-02 00:08:53 24 4
gpt4 key购买 nike

我想知道如何设置与 Jbutton 一起使用的 JComboBox。在 JcomboBox 中选择某个对象会在按下按钮时更改计算。这是我到目前为止所拥有的,但它似乎不起作用,我不确定它出了什么问题。

    //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) {
...
}
}
}

关于java - jcombobox 与 jbutton 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13281358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com