程序设置为“点击”更改圆圈的颜色不会编译

时间:2014-09-14 11:18:18

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

我正在从“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

我知道我错过了一些微不足道的事情,有人可以告诉我我错过了什么吗?,谢谢你!。

1 个答案:

答案 0 :(得分:2)

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