package javaapplication2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calc extends JFrame implements ActionListener {
private JButton b1, b2, b3, b4,b5,b6,b7,b8,b9,b0;
JButton[] label = {b1, b2, b3, b4, b5,b6,b7,b8,b9,b0};
String[] numKeys = {"1","2","3","4","5","6","7","8","9","0"};
JPanel numPad;
JPanel opPad;
JTextField displayPanel;
public Calc() {
super("Calculator");
setSize(250,200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
displayPanel = new JTextField(20);
numPad = new JPanel();
numPad.setLayout(new GridLayout(4, 3));
opPad = new JPanel();
opPad.setLayout(new GridLayout(4, 1));
getContentPane().setLayout(new BorderLayout());
getContentPane().add(numPad,BorderLayout.LINE_START);
getContentPane().add(displayPanel, BorderLayout.PAGE_START);
for (int i = 0; i <label.length;i++) {
label[i] = new JButton(numKeys[i]);
numPad.add(label[i]);
label[i].addActionListener(this);
}
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent a) {
if (a.getSource() == b1)
displayPanel.setText("1");
}
public static void main(String args[]) {
Calc c = new Calc();
}
}
Hi, I've attempted to add numbered Jbuttons and add the action listener within a single loop in my attempt to make a calculator, The buttons are created and added to the panel however pressing "1" has no effect when it should display a 1 on the text field