jcombobox使用它与jbutton

时间:2012-11-08 01:56:19

标签: java swing jbutton actionlistener jcombobox

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

        }

1 个答案:

答案 0 :(得分: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) {
          ...       
       }
    }
}