I Have one JButton variable which i used to create different buttons with different number on it
JButton numb;
numb = new JButton("7");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipadx = 30;
c.ipady = 30;
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 1;
displayPanel.add(numb, c);
numb.setFont(new Font("arial",Font.BOLD,20));
numb.addActionListener(this);
numb = new JButton("8");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipadx = 30;
c.ipady = 30;
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 1;
displayPanel.add(numb, c);
numb.setFont(new Font("arial",Font.BOLD,20));
numb.addActionListener(this);
numb = new JButton("9");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipadx = 30;
c.ipady = 30;
c.gridx = 2;
c.gridy = 3;
c.gridwidth = 1;
displayPanel.add(numb, c);
numb.setFont(new Font("arial",Font.BOLD,20));
numb.addActionListener(this);
Like So
when my buttons get clicked i wane read the text from the button thats got pressed
My actionPerformed looks like this
public void actionPerformed(ActionEvent e) {
// add your event handling code here
if (e.getSource()==numb){
String button = (String)e.getActionCommand();
display.setText(button);
System.out.println(button);
}else if (e.getSource()==opButton){
System.out.println(button);
}
}
Well you can print the text of whatever button was clicked on like this:
… but it’s not really clear what you’re trying to do. In particular, you’ve reassigned the value of
numbseveral different times – it can’t refer to all of those buttons. You might want to give all of the buttons a common action command, e.g. “digit”. Then you can use: