这么简单的程序哪里错了?
import java.awt.*;import javax.swing.*;
import java.awt.event.*;
class DrawRectangle extends JFrame
{
public static void main(String[] args)
{
DrawRectangle dr=new DrawRectangle();
dr.setSize(RECT_WIDTH,RECT_HEIGHT);
Toolkit kit=Toolkit.getDefaultToolkit();
Dimension screenSize=kit.getScreenSize();
dr.setLocation((screenSize.width-RECT_WIDTH)/2,(screenSize.height-RECT_HEIGHT)/2);
dr.setDefaultCloseOperation(dr.EXIT_ON_CLOSE);
dr.add(new MyPanel());
dr.setVisible(true);
}
public static final int RECT_WIDTH=800;
public static final int RECT_HEIGHT=600;
}
class MyPanel extends Panel
{
Button button=new Button("刷新");
add(button);
button.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
repaint();
}
});
public void paint(Graphics g)
{
g.setColor(Color.RED);
g.drawRect(20,20,20+(int)(Math.Random()*100),20+(int)(Math.Random()*100));
}
} --------------------编程问答--------------------
import java.awt.*;--------------------编程问答--------------------
import javax.swing.*;
import java.awt.event.*;
public class Test extends JFrame {
public static void main(String[] args) {
Test dr = new Test();
dr.setSize(RECT_WIDTH,RECT_HEIGHT);
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
dr.setLocation((screenSize.width-RECT_WIDTH)/2, (screenSize.height-RECT_HEIGHT)/2);
dr.setDefaultCloseOperation(dr.EXIT_ON_CLOSE);
dr.add(new MyPanel());
dr.setVisible(true);
}
public static final int RECT_WIDTH = 800;
public static final int RECT_HEIGHT = 600;
}
class MyPanel extends JPanel {
public MyPanel(){
JButton button = new JButton("刷新");
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event){
repaint();
}
});
}
public void paint(Graphics g){
g.setColor(Color.RED);
g.drawRect(20,20,20+(int)(Math.random()*100),20+(int)(Math.random()*100));
}
}
+1
像 add(button); 这样的代码必须在方法里。 --------------------编程问答-------------------- 请问一楼的,是不是方法外只能包括成员?
补充:Java , Java SE