日期:2014-05-20  浏览次数:20749 次

这么简单的程序哪里错了?
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);