import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test implements ActionListener{
static JFrame frm = new JFrame("Calculator");
static JPanel jp1 = new JPanel(new FlowLayout());
static JPanel jp2 = new JPanel(new GridLayout(3, 3));
static JButton []btn = new JButton[9];
static JTextField txtOut = new JTextField(15);
static Container cp = frm.getContentPane();
public static void main(String args[]){
cp.setLayout(new BorderLayout(0, 10));
jp1.add(txtOut);
cp.add(jp1, BorderLayout.NORTH);
for (int i = 0; i < 9; ++i){
btn[i].setText("" + (i + 1));
btn[i].addActionListener((ActionListener)frm);
jp2.add(btn[i]);
}
cp.add(jp2, BorderLayout.CENTER);
frm.setSize(200, 200);
frm.setVisible(true);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
JButton tmp_btn = (JButton) e.getSource();
// check which button
for (int i = 0; i < 9; ++i){
if (tmp_btn == btn[i]){
txtOut.setText("" + (i + 1));
break;
}
}
}
}
Hello, I am studying in Java Swing course.
I tried to make a calculator,
but when I handle Event Listener, I face a problem!
It's java.lang.NullPointerException.
I guess the problem is in main method's for loop's three statements,
because I tried to comment them respectively,
and the IDE compiler talk me "NullPointerException" is in there...
But I still don't know what's wrong in this code.
So, I want to ask, ho to fix it, thanks!!
(Sorry I'm poor at English :(...