Good day. Stupid question, but I can not solve. There is a small such code. When you click the rectangle should change the coordinates, but this does not happen. What should be done?

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Gui implements ActionListener { int x = 50; int y = 200; JButton button; MyDrawPanel myDrawPanel; JFrame frame; public static void main (String[] args) { Gui gui = new Gui(); gui.go(); } public void go() { frame = new JFrame(); myDrawPanel = new MyDrawPanel(); button = new JButton("Test"); frame.setSize(1500, 800); frame.setVisible(true); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(BorderLayout.CENTER, myDrawPanel); frame.getContentPane().add(BorderLayout.SOUTH, button); button.addActionListener(this); } public void actionPerformed(ActionEvent event) { x++; y++; } class MyDrawPanel extends JPanel { public void paintComponent(Graphics g) { g.setColor(Color.gray); g.fillRect(x, y, 50, 200); } } } 
  • должен менять координаты - why are you so bogged down? You only increase the values ​​of the variables. Are these variables related to this rectangle? - post_zeew
  • Yes, connected. In the g.fillRect(x, y, 50, 200); method g.fillRect(x, y, 50, 200); they set the position of the rectangle. - Kojer Defor
  • They only initially set the position of the rectangle. - post_zeew
  • Try adding the line MyDrawPanel.setLocation(x, y); to the actionPerformed(...) method after the increment of variables MyDrawPanel.setLocation(x, y); . - post_zeew
  • Cool, thanks a lot. - Kojer Defor

2 answers 2

You increment variables that are not essentially related to MyDrawPanel .

In order for MyDrawPanel redrawn by new coordinates, add the following line to the actionPerformed(...) method after the increment of variables:

 MyDrawPanel.setLocation(x, y); 

    Your paintComponent method, which uses x and y variables, is called only once when the program draws its window the first time. After you increase their value in the actionPerformed method, the window is not redrawn - there is no reason for it.

    Make the window redraw after increment of variables, and then the rectangle will be drawn in a new place. To do this, add one line:

     public void actionPerformed(ActionEvent event) { x++; y++; frame.update(frame.getGraphics()); // Не забываем обновить окно!!! }