新人求救事件问题

墨竹丶蝉翼 2018-04-14 06:28:25
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class testitem{
public static void main(String args[]){
windows win=new windows();
win.setBounds(100,100,400,300);
win.setTitle("简单计算器");
}
}

class windows extends JFrame{
JTextField one=new JTextField(5);
JTextField two=new JTextField(5);
JComboBox<String>fuhao;
JTextArea show=new JTextArea(9,30);
JButton button=new JButton("计算");
Item a=new Item();
action b=new action();
windows(){
init();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init(){
setLayout(new FlowLayout());
fuhao=new JComboBox<String>();
String [ ] tim={"+","-","*","/"};
for(int i=0;i<tim.length;i++){
fuhao.addItem(tim[i]);
}
a.setJComeBox(fuhao);
a.setWorkTogether(b);
b.setone(one);
b.settwo(two);
b.setarea(show);
fuhao.addItemListener(a);
button.addActionListener(b);
add(one);
add(fuhao);
add(two);
add(button);
add(new JScrollPane(show));
}
}

class Item implements ItemListener{
JComboBox choise;
action together;
void setJComeBox(JComboBox choise){
this.choise=choise;
}
void setWorkTogether(action together){
this.together=together;
}
public void itemStateChanged(ItemEvent e){
String fuhao=choise.getSelectedItem().toString();
together.setfuhao(fuhao);
}
}

class action implements ActionListener{
JTextField one,two;
JTextArea show;
String fuhao;
void setone(JTextField one){
this.one=one;
}
void settwo(JTextField two){
this.two=two;
}
void setarea(JTextArea show){
this.show=show;
}
void setfuhao(String fuhao){
this.fuhao=fuhao;
}
public void actionPerformed(ActionEvent e){
try{
double num1=Double.parseDouble(one.getText() );
double num2=Double.parseDouble(two.getText() );
double result=0;
if(fuhao.equals("+")){
result=num1+num2;
}
else if(fuhao.equals("-")){
result=num1-num2;
}
else if(fuhao.equals("*")){
result=num1*num2;
}
else if(fuhao.equals("/")){
result=num1/num2;
}
show.append(num1+fuhao+num2+"="+result+"\n");
}
catch(Exception exp){
show.append("just math!\n");
}
}
}


为什么加法运算报错,求大神帮忙!
...全文
793 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_33326733 2018-04-15
  • 打赏
  • 举报
回复
JComboBox默认初始化为null,你可以在运算之前直接打印JComboBox的值,会发现是null
qq_33326733 2018-04-15
  • 打赏
  • 举报
回复
是由于JComboBox没有默认初始化导致的,你看到的是加号,但实际里面并不是加号,建议将fuhao在定义的时候写成 String fuhao="+";
墨竹丶蝉翼 2018-04-15
  • 打赏
  • 举报
回复
引用 1 楼 qq_33326733 的回复:
是由于JComboBox没有默认初始化导致的,你看到的是加号,但实际里面并不是加号,建议将fuhao在定义的时候写成 String fuhao="+";
感谢,问题已解决!

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧