我编写了一个代码,该代码在框架中生成一个简单的矩形,并更改框架中已经存在的圆的颜色。

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成员。这样,只要调用endColor,就不会重新定义paintComponent。由于需要在多个位置初始化endColor,因此,最好为它实现一个方法,并在需要初始化颜色以避免任何代码重复时调用该方法。

10-07 12:27