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);
}
}
答案 0 :(得分:1)
如果在帖子中包含堆栈跟踪,对我们来说会更容易。但我想这个问题很清楚。
在go
- 方法中,将JFrame
存储在本地变量中:
JFrame frame = new JFrame();
只需将此行更改为:
frame = new JFrame();
这实际上会以您想要的方式存储变量 - 作为类GUI
的成员变量