How to stop the auto-repaint() when I resize the Jframe

前端 未结 2 1590
日久生厌
日久生厌 2021-01-24 21:16

I am still learning Java, if someone can help me I will be very happy!

Sorry for bad english, I am spanish! I am making a tile game, the game uses the classic \"game loo

相关标签:
2条回答
  • 2021-01-24 21:24

    so when the JFrame isn't maximized

    I don't know why this would cause a problem since only one repaint request should be generated.

    or (resizing)

    I can see this being a problem since repaint will be invoked for every pixel you resize the frame by. In this case maybe you can use:

    Toolkit.getDefaultToolkit().setDynamicLayout(false); 
    

    Now the components will validated after resizing is complete.

    this.setBackground(new Color(210,247,255));

    Don't use code like the above since changing the background causes repaint() to be invoked which will invoke the paintComponent() method again. Painting methods are for painting only.

    0 讨论(0)
  • 2021-01-24 21:35

    "How to stop the auto-repaint() when I resize the Jframe"

    Short answer, you don't control it. Longer answer, you need to make sure you aren't doing any thing that changes the state (you are using to paint), in the paintComponent method. For example:

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Random random = new Random();
        int x = random.nextInt(100);
        int y = random.nextInt(100);
        int size = random.nextInt(100);
        g.drawRect(x, y, size, size);
    }
    

    What happens here is that every times the GUI repaints, which is not under your control, the rectangle will resize, without you wanting it to. So if you want the rectangle to only repaint when you tell it to, you need to make sure you only manipulate the state (i.e. x, y, size) from outside the paintComponent method, and only use that state to paint. Something like

    Random random = new Random();
    int x, y, size;
    ...
    void reset() {
        x = random.nextInt(100);
        y = random.nextInt(100);
        size = random.nextInt(100);
    }
    ...
    Timer timer = new Timer(25, new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            reset();
            repaint();
        }
    }).start();
    ...
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
    
        g.drawRect(x, y, size, size);
    }
    
    0 讨论(0)
提交回复
热议问题