У меня есть одна переменная JButton, которую я использовал для создания разных кнопок с разным номером
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);
Как и так
когда мои кнопки нажимаются, я читаю текст с кнопкивот нажали
Мое действие выполнено выглядит так
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);
}
}