代码编译但不运行

时间:2014-05-18 10:19:47

标签: java swing

这是一个简单的计算器;我的代码编译但无法正常工作。我的意思是它不执行或运行:

   import java.awt.*;
   import javax.swing.*;
   import java.awt.event.*;
   public class Calc implements ActionListener{

JFrame frame;
JButton plus,mul;
JTextField op1,op2,ans;
JLabel firstOperand, secondOperand,answer;
// setting layout

public void initGUI(){

frame = new JFrame();////set top level container
Container con = frame.getContentPane();         
con.setLayout(new FlowLayout());

firstOperand = new JLabel("First Operand");g their constructor
secondOperand = new JLabel("Second Operand");
answer = new JLabel("Answer");

plus = new JButton("+");
plus.setPreferredSize(new Dimension(70,25));
mul = new JButton("*");
mul.setPreferredSize(new Dimension(70,25));

con.add(firstOperand); 
con.add(op1);r

con.add(secondOperand);
con.add(op2);

con.add(plus);
con.add(mul);

con.add(answer);
con.add(ans);


plus.addActionListener(this);
mul.addActionListener(this);

// set size of frame and make it visible
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,220);
 frame.setVisible(true);

 }//end of initilization GUI

//constructor 
public Calc(){

initGUI();// jab obj create ho ga to call ho ga


}
// actionperformed() method of ActionListener

   public void actionPerformed(ActionEvent event){

      String oper, result;
    int num1,num2,res;
    //System.out.println(event.getSource);
    if(event.getSource() == plus){
    oper = op1.getText();
    oper = op2.getText();
    num2 = Integer.parseInt(oper);
    res = num1 + num2;//add operands
    result = res+"";
    ans.setText(result);
    }
    else if (event.getSource() == mul){
    oper = op1.getText();
    num1 = Integer.parseInt(oper);
    oper = op2.getText();
    num2 = Integer.parseInt(oper);
    res = num1 * num2;//add operands 
    result = res+"";
    ans.setText(result);

    }


}// end of actionPerformed method

public static void main(String args[]){

Calc cl = new Calc();// making object for Cals class

}
}

3 个答案:

答案 0 :(得分:1)

您的JTextField未初始化。用

初始化它们
op1 = new JTextField();
....

答案 1 :(得分:0)

您收到NullPointerException因为JTextFields未初始化。因此,当您尝试将它们添加到ControlPanel时,它会抛出NullPointerException。正确初始化

答案 2 :(得分:0)

添加你的构造函数:

  op1 = new JTextField();
  op2 = new JTextField();
  ans = new JTextField();