你这样当然不会画出图来的,好像重画的时候是没有调用paint这个方法的。你仅仅在click的时候设置标志有什么用呢。你难道想让系统根据你的标志给你画图不成,你应该要自己调用一个画图的过程,而且可以不要通过标志的。使用面向对象的做法是,你可以定义好图形类,然后通过基类去调用画图的方法。

解决方案 »

  1.   

    你好,感谢你的帮助
    我还是“真想让系统根据我的标志给我画图”,我以为通过设置标志,就可以在paint中控制画出不同的图形来。
    对你的方法,能否详细介绍一下,学JAVA不久,还望你指点迷津。
    程序中private String names",应为
    private String names[]={"oval","arc","line"};
      

  2.   

    上述问题已解决package CustomPanel;import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;public class CustomPanelTest extends JFrame {
       private JPanel buttonPanel;
       private CustomPanel myPanel;
       private JButton oval,arc,line;   public CustomPanelTest()
       {
          super( "CustomPanel Test" );      myPanel = new CustomPanel();   // instantiate canvas
          myPanel.setBackground( Color.green );      oval = new JButton( "oval" );
          oval.addActionListener(
             new ActionListener() {
                public void actionPerformed( ActionEvent e )
                {
                   myPanel.draw( CustomPanel.OVAL );
                }
             }
          );      arc = new JButton( "arc" );
          arc.addActionListener(
             new ActionListener() {
                public void actionPerformed( ActionEvent e )
                {
                   myPanel.draw( CustomPanel.ARC );
                }
             }
          );      line = new JButton( "arc" );
          line.addActionListener(
              new ActionListener() {
                 public void actionPerformed( ActionEvent e )
                 {
                    myPanel.draw( CustomPanel.LINE );
                 }
              }
           );      buttonPanel = new JPanel();
          buttonPanel.setLayout( new GridLayout( 1, 2 ) );
          buttonPanel.add( oval );
          buttonPanel.add( line );
          buttonPanel.add( arc );      Container c = getContentPane();
          c.add( myPanel, BorderLayout.CENTER );
          c.add( buttonPanel, BorderLayout.SOUTH );      setSize( 300, 150 );
          show();
       }   public static void main( String args[] )
       {
          CustomPanelTest app = new CustomPanelTest();      app.addWindowListener(
             new WindowAdapter() {
                public void windowClosing( WindowEvent e )
                {
                   System.exit( 0 );
                }
             }
          );
       }
    }
    package CustomPanel;import java.awt.*;
    import javax.swing.*;public class CustomPanel extends JPanel {
       public final static int OVAL = 1, ARC = 2,LINE=3;
       private int shape;   public void paintComponent( Graphics g )
       {
          super.paintComponent( g );      if ( shape == OVAL )
             g.fillOval( 50, 10, 60, 60 );
          else if ( shape == LINE )
             g.fillRect( 10, 10, 160, 60 );
          else if (shape==ARC)
            g.drawArc(10,60,120,120,0,260);
       }   public void draw( int s )
       {
          shape = s;
          repaint();
       }
    }