gpt4 book ai didi

JAVA 改变图形颜色

转载 作者:行者123 更新时间:2023-12-01 11:31:41 27 4
gpt4 key购买 nike

每个人我都有一个创建圆圈和按钮的代码。圆圈在开头有一个颜色,按钮必须在每次单击它时更改该圆圈的颜色,但每当我单击它时控制台都会出现错误。由于我是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);

}
}

最佳答案

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

go 方法中,将 JFrame 存储在局部变量中:

JFrame frame = new JFrame();

只需将此行更改为:

frame = new JFrame();

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

的成员变量

关于JAVA 改变图形颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30330019/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com