Skip to content
Advertisement

Is there a faster way to create 12 buttons?

I am doing a task where I need to create a 3×4 GridLayout with 12 buttons. The task is when I click any of the buttons, all other buttons change the value to 1. Now, this is how I did it:

JFrame frame=new JFrame();
    frame.setSize(300,200);
    frame.setLayout(new GridLayout(3,4));
    
    JButton b1=new JButton("1");
    JButton b2=new JButton("2");
    JButton b3=new JButton("3");
    JButton b4=new JButton("4");
    JButton b5=new JButton("5");
    JButton b6=new JButton("6");
    JButton b7=new JButton("7");
    JButton b8=new JButton("8");
    JButton b9=new JButton("9");
    JButton b10=new JButton("10");
    JButton b11=new JButton("11");
    JButton b12=new JButton("12");

    b1.addActionListener(lambdaExpression -> {
        b2.setText("1");
        b3.setText("1");
        b4.setText("1");
        b5.setText("1");
        b6.setText("1");
        b7.setText("1");
        b8.setText("1");
        b9.setText("1");
        b10.setText("1");
        b11.setText("1");
        b12.setText("1");

    });

    b2.addActionListener(lambdaExpression -> {
        b1.setText("1");
        b3.setText("1");
        b4.setText("1");
        b5.setText("1");
        b6.setText("1");
        b7.setText("1");
        b8.setText("1");
        b9.setText("1");
        b10.setText("1");
        b11.setText("1");
        b12.setText("1");

    });
    
    b3.addActionListener(lambdaExpression -> {
        b1.setText("1");
        b2.setText("1");
        b4.setText("1");
        b5.setText("1");
        b6.setText("1");
        b7.setText("1");
        b8.setText("1");
        b9.setText("1");
        b10.setText("1");
        b11.setText("1");
        b12.setText("1");

    });
    .
    .
    .
    frame.add(b1);
    frame.add(b2);
    frame.add(b3);
    .
    .
    .
    frame.pack();
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    

My question is – is there a faster way to do this than just copying the same lines 12 times? I am fairly new at programming in Java, so any insight would be helpful, thank you!

Advertisement

Answer

Putting your buttons in an array can help a lot

final JButton[] buttons = new JButton[12];
final ActionListener myListener = new ActionListener() {
  public void actionPerformed(ActionEvent ae) {
    for (int i = 0; i < buttons.length; i++) {
      if (buttons[i] != ae.getSource()) {
        buttons[i].setText("1");
      }
    }
  }
}
for (int i = 0; i < 12; i++) {
  buttons[i] = new JButton();
  buttons[i].setName("Button " + (i + 1));
  buttons[i].addActionListener(myListener);
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement