2014-05-18 151 views
0

這是一個簡單的計算器;我的代碼編譯但不工作。我的意思是它不執行或運行:代碼編譯但不運行

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 

} 
} 
+0

沒有給出什麼錯誤? – Leigh

+1

這需要更多的診斷。 「不執行」是什麼意思?它可以運行嗎? (如果沒有,即使你認爲它沒有編譯,也可能不會編譯。)它運行但沒有任何反應?然後添加調試輸出以查看它的運行情況 - 在開始時添加一條打印語句。 – usr2564301

+1

請務必首先查看日誌。它導致'java.lang.NullPointerException' – Braj

回答

1

您的JTextFields未初始化。與

op1 = new JTextField(); 
.... 
0

你得到NullPointerException因爲JTextFields沒有初始化初始化。所以當你試圖將它們添加到ControlPanel,其投擲NullPointerException。初始化它們正確

0

添加此構造函數:

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