Try this. The judgement has not been done yet though.import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DrawRect extends JFrame {
   private MyPanel jPanel1 = new MyPanel();   public DrawRect() throws HeadlessException {
      try {
         jbInit();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
   public static void main(String[] args) throws HeadlessException {
      DrawRect dr = new DrawRect();
      dr.setSize(200,200);
      dr.setVisible(true);
   }
   private void jbInit() throws Exception {
      this.getContentPane().add(jPanel1, BorderLayout.CENTER);
   }
}class MyPanel extends JPanel {
   Color cOrg = null;
   Color cChg = Color.red;
   boolean isChg = false;
   public MyPanel() {
      addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
            int x = e.getX();
            int y = e.getY();
   // if x in y in
            isChg = !isChg;
            repaint();
         }
      });
   }
   int w ,h ;
   public void paint(Graphics g) {
      w = (int) getSize().getWidth()-100;
      h = (int) getSize().getHeight()-100;
      if(cOrg == null)
        cOrg = g.getColor();
      g.setColor(isChg?cOrg:cChg);
      g.fillRect(50,50,w,h);   }}

解决方案 »

  1.   

    这下全好了.
    class MyPanel extends JPanel {
       static final int W = 50, H = 50;   int w ,h ;
       Color cOrg = null;
       boolean isChg = false;   public MyPanel() {
          addMouseListener(new MouseAdapter() {
             public void mouseClicked(MouseEvent e) {
                if(chkIn(e)){
                   isChg = !isChg;
                }
                repaint();
            }
          });
          addMouseMotionListener(new MouseMotionListener() {
             public void mouseMoved(MouseEvent e) {
                setCursor(chkIn(e)?new Cursor(Cursor.CROSSHAIR_CURSOR):new Cursor(Cursor.HAND_CURSOR));
             }
             public void mouseDragged(MouseEvent e){}
          });
       }
       boolean chkIn(MouseEvent e) {
          int x = e.getX();
          int y = e.getY();
          return (x >W && x < w+W &&
             y > H && y < h+H);
       }   public void paint(Graphics g) {
          w = (int) getSize().getWidth()-2*W;
          h = (int) getSize().getHeight()-2*H;
          if(cOrg == null)
            cOrg = g.getColor();
          g.setColor(isChg?cOrg:Color.red);
          g.fillRect(50,50,w,h);   }
    }
      

  2.   

    在g.fillRect(50,50,w,h);的下面再写上:
      g.setColor(Color.white);
      g.drawString("Hello World",60,70);
      

  3.   

    还有为什么编译时出现以下错误:
    cannot resolve symbol
    symbol:class DrawRect
    public DrawRect() throws HeadlessException{