rectangleButton.addActionListener(new ActionListener(){
       public void actionPerformed(ActionEvent event){ 
            repaint();
            System.out.println(1);
           
           add(new JPanel(){public void paintComponent(Graphics g){  
           super.paintComponents(g);
           Graphics2D g2 = (Graphics2D) g;
           Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
               g2.draw(rect);       }});代码如上  点了按钮反映只输出1  是表示我的repaint()放错位置了 为什么他不调用paintComponent() 呢  求解

解决方案 »

  1.   

    代码太乱!rectangleButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            repaint();
            System.out.println(1);
            add(new JPanel() {
                public void paintComponent(Graphics g) {
                    super.paintComponents(g);
                    Graphics2D g2 = (Graphics2D) g;
                    Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
                    g2.draw(rect);
                }
            });
        }
    });
      

  2.   

    rectangleButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            System.out.println(1);
            add(new JPanel() {  //用的什么布局管理器?
                public void paintComponent(Graphics g) {
                    super.paintComponents(g);
                    Graphics2D g2 = (Graphics2D) g;
                    Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
                    g2.draw(rect);
                }
            });
            repaint();  //换个位置试下
        }
    });
      

  3.   


     
    基本代码如下,楼主自己改改
    mPanel tmpmPanel=new mPanel();
     rectangleButton.getParent().add(tmpmPanel);rectangleButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
             tmpmPanel.repaint();
        }
    });  class mPanel extends JPanel{              public void paintComponent(Graphics g) {
                    super.paintComponents(g);
                    Graphics2D g2 = (Graphics2D) g;
                    Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
                    g2.draw(rect);
             }
     }