谁知道如果我要在一个panel上画东西,除了写个类去继承他,然后覆盖paint方法,还有什么方法么?

解决方案 »

  1.   

    public class DrawPanel extends javax.swing.JPanel {
          private Image image; 
        /**
         * Creates new form DrawPanel
         */
        public DrawPanel() {
            initComponents();
        }
           //定义setImage方法    
            public void setImage(URL imagePath){
             image=Toolkit.getDefaultToolkit().getImage(imagePath);
             MediaTracker tracker=new MediaTracker(this);
             tracker.addImage(image,0);
             try{
                 tracker.waitForID(0);
             }catch(InterruptedException exception){
                 exception.printStackTrace();
             }        
         } 
    //下面是重载!!!!
    public void paintComponent(Graphics g){
             super.paintComponent(g);
             
             if(image == null) return;
             //int imageWidth = image.getWidth(this);
             //int imageHeight = image.getHeight(this);
             g.drawImage(image,0,0,null);
         }
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        // <editor-fold defaultstate="collapsed" desc=" 生成的代码 ">                          
        private void initComponents() {        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(0, 400, Short.MAX_VALUE)
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(0, 300, Short.MAX_VALUE)
            );
        }
    }
      

  2.   

    使用 Canvas 这个组件,专门用来画图的,把它放入panel,然后在Canvas里面画图。