当前位置: 代码迷 >> J2SE >> 这么简单的程序错哪了
  详细解决方案

这么简单的程序错哪了

热度:67   发布时间:2016-04-23 21:15:17.0
这么简单的程序哪里错了?
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);         
  相关解决方案