2016-05-30 74 views
1

上午试图调用paint在我的听众,但绘制矩形不应该叫Java的油漆不起作用

也许我的代码是错误的帮助我,请我在java的新手

btnNewButton_5.addActionListener(new ActionListener() { 

     public void actionPerformed(ActionEvent e) { 
      class MyCanvas extends JComponent { 

        public void paint(Graphics g) { 
        g.drawRect (10, 10, 200, 200); 
        } 
      } 

      JFrame window = new JFrame(); 
      window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      window.setBounds(30, 30, 300, 300); 
      window.getContentPane().add(new MyCanvas()); 
      window.setVisible(true); 

     } 
    }); 
+0

它只显示帧但看不到矩形 –

回答

0

希望它会帮助你:)

btnNewButton_5.addActionListener(new ActionListener() { 

    public void actionPerformed(ActionEvent e) { 
     class MyCanvas extends JComponent { 

       //You didnt set size 

       public MyCanvas(){ 
        setSize(size, width); 
       } 

       //public void paint(Graphics g) { better use paintComponent 
       public void paintComponent(Graphics g){ 
       //always use it: 
       super.paintComponent(g); 
       g.setColor(Color.RED); // You didnt set color 
       g.drawRect (10, 10, 200, 200); 
       } 
     } 

     JFrame window = new JFrame(); 
     window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     //window.setBounds(30, 30, 300, 300); Never saw the same statement 
     window.setSize(width, height); 
     //window.getContentPane().add(new MyCanvas()); 
     window.add(new MyCanvas()); // dont use getContentPane dont need it in newest java versions 
     window.setVisible(true); 

    } 
});