Draw a grid to test the monitor. By clicking the mouse on the form, cyclically change the colors of the grid lines in order: red, blue, green. Provide the ability to change the pitch of the grid.

package dialogtest; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.*; import java.awt.event.*; import javax.swing.*; import java.awt.event.*; public class DialogTest extends JFrame{ JPanel panSouth; JPanel panCenter; JButton but; JTextField tf1; JTextField tf2; JLabel[] grid; private int colorIndex = 0; DialogTest(){ super(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 450); setLayout(new BorderLayout()); panSouth = new JPanel(); tf1 = new JTextField(5); tf2 = new JTextField(5); but = new JButton("Change"); panSouth.add(new JLabel("X: ")); panSouth.add(tf1); panSouth.add(new JLabel("Y: ")); panSouth.add(tf2); panSouth.add(but); add(panSouth, BorderLayout.SOUTH); but.addActionListener(new ActionListener() { int x; int y; @Override public void actionPerformed(ActionEvent e) { if (!tf1.getText().isEmpty() && !tf2.getText().isEmpty()){ x = Integer.parseInt(tf1.getText()); y = Integer.parseInt(tf2.getText()); panCenter = new JPanel(new GridLayout(y, x)); grid = new JLabel[x*y]; for (int i = 0; i<grid.length; i++){ grid[i] = new JLabel(); grid[i].setBorder(BorderFactory.createLineBorder(Color.RED)); panCenter.add(grid[i]); } add(panCenter, BorderLayout.CENTER); revalidate(); } } }); // repaint(); addMouseListener (new MouseAdapter() { // @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); // Клик int x=0; int y=0; x = Integer.parseInt(tf1.getText()); y = Integer.parseInt(tf2.getText()); Color color; colorIndex = colorIndex + 1; if (colorIndex > 2) { colorIndex = 0; } switch (colorIndex) { case 0:color = Color.RED;break; case 1:color = Color.BLUE;break; case 2:color = Color.GREEN;break; default:color = Color.RED;break; } // System.out.println("mouseClicked ->" + e.getX() + "->" + e.getY()); for (int i = 0; i<x*y; i++){ grid[i].setBorder(BorderFactory.createLineBorder(color)); } // revalidate(); repaint(); } }); } public static void main(String[] args) { new DialogTest().setVisible(true); } } 

At the initial size of the grid, the color changes normally, and when the grid step is changed, pressing the mouse over the form changes the color to the initial one. What could be the error?

    1 answer 1

    Add between these lines now

     y = Integer.parseInt(tf2.getText()); panCenter = new JPanel(new GridLayout(y, x)); 

    This

     if(panCenter != null) { remove(panCenter); } 

    And it will work

    Your mistake is that you are not replacing the old grid, but adding another one. And when you redraw, your old grid appears, and a new grid is drawn outside the visible area. If you stretch the window, you will see it.