我编写了一个代码,在框架中生成一个简单的矩形,并更改框架上已存在的圆的颜色。
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class DrawRect extends JPanel{
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.draw(new Rectangle(200,200,200,200));
}
}
class FillOval extends JPanel{
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;
int red = (int)(Math.random()*255);
int green = (int)(Math.random()*255);
int blue = (int)(Math.random()*255);
Color startColor = new Color(red,green,blue);
red = (int)(Math.random()*255);
green = (int)(Math.random()*255);
blue = (int)(Math.random()*255);
Color endColor = new Color(red,green , blue);
GradientPaint gradient = new GradientPaint(70,70,startColor,150,150,endColor);
g2.setPaint(gradient);
g2.fillOval(70,70,100,100);
}
}
class MainGui {
public static void main(String[] args){
MainGui gui = new MainGui();
gui.go();
}
JFrame frame;
FillOval ov = new FillOval();
void go(){
frame = new JFrame();
JButton colorButton = new JButton("change color");
JButton rectButton = new JButton("draw rectangle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
colorButton.addActionListener(new colorListener());
rectButton.addActionListener(new rectListener());
frame.getContentPane().add(BorderLayout.SOUTH, colorButton);
frame.getContentPane().add(BorderLayout.WEST, rectButton);
frame.getContentPane().add(BorderLayout.CENTER, ov);
frame.setSize(500,500);
frame.setVisible(true);
}
class colorListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
frame.repaint();
}
}
class rectListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
DrawRect rect = new DrawRect();
frame.add(rect);
frame.revalidate();
frame.repaint();
}
}
}
现在,问题是rectButton
按钮正在改变框架中圆圈的颜色,同时在框架中生成一个矩形。
它与colorButton
按钮的事件无关。为什么它会以这种方式表现?我该如何解决?
答案 0 :(得分:1)
调用repaint
会触发paintComponent
的调用,其中颜色将始终随机选择。您需要将endColor
定义为class
的成员,并使用null
进行初始化。在paintComponent
方法中,针对null
进行检查,如果是null
,请对其进行初始化。您还需要在colorListener
初始化它。在paintComponent
中,使用endColor
成员。这样,只要调用endColor
,您就不会重新定义paintComponent
。由于您需要在多个位置初始化endColor
,因此最好为它实现一个方法,并在需要初始化颜色时调用该方法以避免代码重复。