這是一個簡單的計算器;我的代碼編譯但不工作。我的意思是它不執行或運行:代碼編譯但不運行
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
}
}
沒有給出什麼錯誤? – Leigh
這需要更多的診斷。 「不執行」是什麼意思?它可以運行嗎? (如果沒有,即使你認爲它沒有編譯,也可能不會編譯。)它運行但沒有任何反應?然後添加調試輸出以查看它的運行情況 - 在開始時添加一條打印語句。 – usr2564301
請務必首先查看日誌。它導致'java.lang.NullPointerException' – Braj