cannot resolve symbol frame,为什么我的frame被idea标红了?

Foools 2021-02-23 11:27:35
目的是实现在一个面板上面放置一个按钮,一个圆形,点击按钮,圆形里的颜色就会变。
但是我加入了implement之后,在监听到点击之后调用的函数:actionPerformed()会显示frame被标红了,connot resolve symbol frame,请问怎么修改呢?


代码:

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

class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D graphics2D = (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 gradientPaint = new GradientPaint(70,70,startColor,150,150,endColor);
graphics2D.setPaint(gradientPaint); //将虚拟的笔刷画成渐层
graphics2D.fillOval(70,70,100,100); //用目前的笔刷来填满椭圆形区域
}
}

public class SimpleGUI implements ActionListener {
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
gui.go();
}

public void actionPerformed(ActionEvent event){
frame.repaint();
}

//重写JPanel,加入我们需要的样式

public void go(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置关闭即停止

JButton button = new JButton("do not click") ;
button.addActionListener(this);
MyDrawPanel mypanel = new MyDrawPanel(); //创建我们的myPanel对象

frame.add(BorderLayout.CENTER,mypanel); //add进frame框架中
frame.add(BorderLayout.SOUTH,button);

frame.setSize(300,300);
frame.setVisible(true); //设置框架为可见
}

}

不用接口的运行结果:


书上的实例

...全文
619 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
qybao 2021-02-24
  • 打赏
  • 举报
回复
把 public void go(){ JFrame frame = new JFrame(); 改成 JFrame frame = new JFrame(); //换个位置,变成成员变量,否则frame是go方法的局部变量,actionPerformed方法是看不到它的 public void go(){

51,397

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧