0

我想知道如何设置与 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);
            }

        }
4

1 回答 1

3

在按钮的动作侦听器中,您应该检查在组合框中选择的项目,而不是使用在初始化期间设置的索引 ( 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) {
          ...       
       }
    }
}
于 2012-11-08T02:04:00.167 回答