我编写了一段代码,可以在框架中生成一个简单的矩形,并更改框架上已经存在的圆的颜色。
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
按钮的事件无关。为什么它的行为方式如此?我应该如何解决它?
repaint
会触发paintComponent
的调用,其中颜色将始终随机选择。你需要将endColor
定义为class
的成员,用null
初始化。在您的paintComponent
方法中,根据null
检查它,如果null
,则对其进行初始化。您还需要在colorListener
初始化它。在paintComponent
中,使用endColor
成员。这样,无论何时调用paintComponent
,您都不会重新定义endColor
。由于您需要在多个位置初始化endColor
,因此最好为其实现一个方法,并在需要初始化颜色时调用该方法以避免代码重复。