最大化时多次调用 Paintcomponent 方法 window

Paint component method called multiple times whilst maximising window

所以我创建了一个 GUI,用户可以在其中单击 JButton 来更改圆圈的颜色...我使用了 paintComponent 方法,我知道该方法将在显示 GUI 时以及当 GUI 出现时调用window 被最小化然后重新打开。

然而,当我在 mac 上最大化我的 window 时,paintComponent 方法被多次调用并且圆圈循环显示许多不同的颜色,为什么会发生这种情况,就像为什么调用 paintComponent 方法一样多次。

源代码:

图形界面 Class

   import javax.swing.*;
   import java.awt.event.*;
   import java.awt.*;

public class Gui extends JFrame {

JPanel row1 = new JPanel();
JPanel drawingSpace = new MyDrawPanel();
JButton colourChange = new JButton("Click here to change colors");

public Gui(){
    setTitle("Circle Colors");
    setSize(400,650);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    BorderLayout layoutMaster = new BorderLayout();
    colourChange.addActionListener(new EventHandler(this));
    setLayout(layoutMaster);


    setLayout(layoutMaster);
    row1.add(colourChange);
    add(drawingSpace, BorderLayout.CENTER);
    add(row1, BorderLayout.SOUTH);

    setVisible(true);
}

public static void main(String[] args){
    Gui createPage = new Gui();
}

}

事件处理Class

import java.awt.event.*;
import java.awt.*;

public class EventHandler implements ActionListener {

Gui refRemote;

public EventHandler(Gui obj){
    refRemote = obj;
}

public void actionPerformed(ActionEvent e1){
    String buttonTitle = e1.getActionCommand();

    if(buttonTitle.equals("Click here to change colors"))
    {
        refRemote.repaint();
    }
}

}

绘图面板Class

 import javax.swing.*;
 import java.awt.*;

  public class MyDrawPanel extends JPanel {

   public void paintComponent(Graphics g1){

    Graphics2D g2D = (Graphics2D) g1;

    int red = (int) (Math.random()*256);
    int green = (int) (Math.random()*256);
    int blue = (int) (Math.random()*256);

    Color initialColor = new Color(red, green, blue);

    red = (int) (Math.random()*256);
    green = (int) (Math.random()*256);
    blue = (int) (Math.random()*256);

    Color finalColor = new Color(red, green, blue);

    ///GradientPaint gradient = new GradientPaint(50, 50, initialColor, 100, 100, finalColor);

    g2D.setPaint(initialColor);
    g2D.fillOval(100, 150, 200, 200);

}

}

不是在重绘时更改颜色,而是使用一种特定的方法来更改将从 ActionListener 调用的颜色。当调用 paintComponent 时,它应该只使用当前颜色。