0

these are four buttons, i wanna just select one or two button! how do i do that?

public class Game {
  private JButton button1,button2,button3,button4;
  public Game(){

buttonMethod();

private void buttonMethod() {
    JButton button1 = new JButton("?");
    button1.setFont(new Font("Tahoma",Font.BOLD,20));
    button1.setBackground(Color.yellow);
    panel2.add(button1);

    JButton button2 = new JButton("?");
    button2.setFont(new Font("Tahoma",Font.BOLD,20));
    button2.setBackground(Color.yellow);
    button2.addActionListener(e->{
    button2.setText("2");
    });
    panel2.add(button2);

    JButton button3 = new JButton("?");
    button3.setFont(new Font("Tahoma",Font.BOLD,20));
    button3.setBackground(Color.yellow);
    button3.addActionListener(e->{
    button3.setText("3");
    });
    panel2.add(button3);

    JButton button4 = new JButton("?");
    button4.setFont(new Font("Tahoma",Font.BOLD,20));
    button4.setBackground(Color.yellow);
    button4.addActionListener(e->{
    button4.setText("4");
    });
    panel2.add(button4);
    }

}
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    Use a `JToggleButton`, or more likely `JCheckBox`. – camickr Sep 21 '21 at 17:25
  • Is your problem solved? You should respond to all suggestions so people know if the suggestion have helped or not. – camickr Sep 22 '21 at 13:57
  • @camickr thanks, i solved my problem then i used only one ActionListener after use if&else to add ActionListener for any Buttons and finally call any buttons separate : explain more: https://www.youtube.com/watch?v=OI-TFbHQhtA – ehsan_pc Sep 23 '21 at 07:05
  • 1) That has nothing to do with the question you asked. 2) That is not a good solution. Yes you can share an ActionListener for multiple button, if the Action for each button is generic, but you should NOT have if/else statements in an ActionListener. If the Action is not generic then you should use a separate ActionListener for each button. See: https://stackoverflow.com/questions/33739623/how-to-add-a-shortcut-key-for-a-jbutton-in-java/33739732#33739732 for a better example of how to create a generic ActionListener without using if/else statements. – camickr Sep 23 '21 at 13:40
  • @camickr thanks a lot, yeah you're right, but I'm beginner in java and I'm not experienced in GUI Generally. – ehsan_pc Sep 24 '21 at 16:17

0 Answers0