Quite new to Swing, maybe you don’t fully understand streams or anything. In general, this is a problem - the Field class is a window containing a panel of 4 by 4 buttons (field).

Field Class

The AI ​​class is its successor, but the buttons on the main diagonal are also programmed in the constructor in the constructor. The fact is that when this pressing is performed, the field of buttons itself is not displayed. Like that:

enter image description here

Source of the program:

Field class

import java.awt.*; import javax.swing.*; public class Field extends JFrame { JPanel field; //панель будет содержать кнопки 4x4 JButton[][] buttons; //собственно, кнопки public Field() { // TODO Auto-generated constructor stub setLayout(new FlowLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 400); setLocationRelativeTo(null); field = new JPanel(new GridLayout(4, 4)); //инициализируем панель field.setPreferredSize(new Dimension(300,300)); buttons = new JButton[4][4]; for(int i=0; i<4; i++) for(int j=0; j<4; j++) { buttons[i][j] = new JButton(); field.add(buttons[i][j]); } add(field); setVisible(true); } } 

AI class:

 public class AI extends Field { public AI() { // TODO Auto-generated constructor stub super(); for(int i=0; i<4; i++) { buttons[i][i].doClick(); } } } 

Calling AI asynchronously (SwingUtilities.invokeLater)

    1 answer 1

    If you want to click programmatically (not by the user) you can use this option:

     public AI() { // TODO Auto-generated constructor stub super(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 4; i++) { buttons[i][i].doClick(); } } }).start(); } 

    those. perform a push in a parallel thread