2012-11-08 83 views
0

我想知道如何設置JComboBox與Jbutton一起使用。在按下按鈕時,在JcomboBox中選擇某個對象將更改計算。這是我迄今爲止,但似乎並沒有工作,我不知道它有什麼問題。jcombobox使用它與jbutton

//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); 
      } 

     } 

回答

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