日期:2014-05-19  浏览次数:20824 次

关于jcombobox的问题,无法实现,求大师,
/*jcombobox中包含加减乘除。选中不同的符号具有不同功能,就大神补全,初学。*/



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Arith extends JFrame implements ItemListener,ActionListener {
JTextField t,t1,t2;
JButton deng;
JComboBox j;

 
Arith(){

super ("a simple calculator");
this.setDefaultCloseOperation (3);
clickInit();
Container cc = this.getContentPane();
cc.setLayout(new FlowLayout ());
cc.add(t);
cc.add(j);
cc.add(t1);
cc.add(deng);
deng.addActionListener(this);
cc.add(t2);
pack();
setBounds(300,200,220,120);
this.setVisible(true);
}


void clickInit() {
t = new JTextField ( " ");
deng = new JButton (" = ");
deng.addItemListener(this);
t1= new JTextField ( " ");
j = new JComboBox(new String[] {"+","-","*","/"});
t2 = new JTextField ( " ");
}
public void itemStateChanged(ItemEvent e){

  if( j.getSelectedItem()=="+"){
   
   
  }

}
public void actionPerformed (ActionEvent o) {
int tint=Integer.parseInt(t.getText());
  int t1int=Integer.parseInt(t1.getText());
   
   
  int resultint=tint+t1int;
   
  t2.setText(String.valueOf(resultint));
   
}

public static void main (String [] args) {
new Arith();
}
}

------解决方案--------------------
给组件增加一个itemStateChanged的事件,然后通过
String select = modeComboBox.getSelectedItem().toString();
if("平均分发".equals(select)){
mode = 1;
}else{
mode = 2;
}
这样的语句来设置一个变量,通过变量来判断使用什么计算方法。