JAVA Changin一款图形色

时间:2015-05-19 15:33:03

标签: java actionlistener graphics2d

每个人都有一个创建圆圈和按钮的代码。圆圈在开始时有颜色,按钮必须在每次点击它时改变这个圆圈的颜色,但是每当我点击它时控制台都没有错误。由于我是JAVA的新手,我找不到解决方案。这是代码:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class GUI extends JPanel implements ActionListener {

JFrame frame;
public static void main(String[] args) {

    GUI gui = new GUI();
    gui.go();

}

public void go() {

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JButton button = new JButton("change colors");
    button.addActionListener(this);

    MyDrawPanel drawPanel = new MyDrawPanel();

    frame.getContentPane().add(BorderLayout.SOUTH, button);
    frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
    frame.setSize(300, 300);
    frame.setVisible(true);



}


 public void actionPerformed(ActionEvent event) {

    frame.repaint();
}


}

我的重绘功能:

 import java.awt.*;
import javax.swing.*;

  public class MyDrawPanel extends JPanel {




public void paintComponent(Graphics g) {


    Graphics2D g2d = (Graphics2D) g;

    int red = (int) (Math.random()*256);
    int green = (int) (Math.random()*256);
    int blue = (int) (Math.random()*256);

    Color starColor = new Color(red, green, blue);      ;


    red = (int) (Math.random() * 256);
    green = (int) (Math.random() * 256);
    blue  = (int) (Math.random() * 256);
    Color endColor = new Color(red, green, blue);

    GradientPaint gradient = new GradientPaint(70, 70,starColor, 150, 150,endColor);
    g2d.setPaint(gradient);
    g2d.fillOval(70, 70, 100, 100);

}
}

1 个答案:

答案 0 :(得分:1)

如果在帖子中包含堆栈跟踪,对我们来说会更容易。但我想这个问题很清楚。

go - 方法中,将JFrame存储在本地变量中:

JFrame frame = new JFrame();

只需将此行更改为:

frame = new JFrame();

这实际上会以您想要的方式存储变量 - 作为类GUI的成员变量