gpt4 book ai didi

java - 最大化窗口时多次调用 PaintComponent 方法

转载 作者:行者123 更新时间:2023-12-02 04:29:44 25 4
gpt4 key购买 nike

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

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

源代码:

GUI 类

   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();
}

}

事件处理类

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();
}
}

}

绘图面板类

 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 时,它应该只使用当前的颜色。

关于java - 最大化窗口时多次调用 PaintComponent 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31629001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com