【问题标题】:Program to 'Change color of a circle on click doesn't Compile“单击时更改圆圈颜色的程序无法编译”
【发布时间】:2014-09-14 11:18:17
【问题描述】:

我正在从“Head First Java”学习 Java 中的 GUI 当我编写以下程序时,即使在之后我也无法弄清楚我哪里出错了 调试了20多分钟。

import javax.swing.*;//for the frame etc
import java.awt.*;//for  paintComponent(),Grapics Object etc
import java.awt.event.*;//for listeners


//display a circle and chang eits color when a button is clicked

class MyDrawPanel extends JPanel//this class will contain code for the circle
{

    public void paintComponent(Graphics g)
    {
    int r=(int)(Math.random()*255);//generate random float between 0 & 255
    int b=(int)(Math.random()*255);//generate random float between 0 & 255
    int gr=(int)(Math.random()*255);//generate random float between 0 & 255
    Color randcolor=new Color(r,gr,b);//name clashed with Graphics g
    g.setColor(randcolor);
    g.fillOval(90,90,120,120);//default background color is used,oval is filled with Color (randcolor);
    }
}

public class changecolor implements ActionListener
{

JButton button;//ie this class's objects have a button as an instance field
MyDrawPanel p;//similar except this isuser defined

    public static void main(String args[])
    {
    changecolor c=new changecolor();
    c.go();
    }

    public void go()
    {
    button=new JButton("Change Color ");
    button.addActionListener(this);//this class ie object of this class listens to                       the action
    p=new MyDrawPanel();
    JFrame frame=new JFrame();
    frame.setSize(700,700);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(BorderLayout.SOUTH,button);
    frame.getContentPane().add(BorderLayout.CENTRE,p);
    frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e)
    {
    frame.repaint();//repaint or referesh the frame;

    }


}

我收到这些错误

  changecolor.java:49: error: cannot find symbol
    frame.repaint();//repaint or referesh the frame;
    ^
  symbol:   variable frame
  location: class changecolor
1 error

我知道我错过了一些琐碎的事情,有人可以告诉我我错过了什么吗?谢谢!

【问题讨论】:

    标签: java swing user-interface compiler-errors event-handling


    【解决方案1】:

    在 java 中,必须将公共类写入与此类命名的文件中。在这种情况下,您需要两个文件:MyDrawPanel.javachangecolor.java

    【讨论】:

    • 哦,谢谢我改了,现在只是说 repaint() 找不到,我已经编辑了我的问题,请立即查看。
    • 我想通了,JFrame 框架在 main() 中被声明为本地变量,并且执行的操作无法访问它,我会更改它
    • 在您的函数 actionPerformed 中,您使用的是 go 方法中声明的变量 frame。定义框架 aß 类变量,就在 MyDrawPanel p 下方;
    猜你喜欢
    • 2013-04-25
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 2012-06-27
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    相关资源
    最近更新 更多