问题描述
因此,我创建了一个GUI,在该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);
}
}
1楼
有一种特定的方法可以更改从ActionListener
调用的颜色,而不是更改重绘时的颜色。
调用paintComponent
,应仅使用当前颜色是什么。