2016-05-30 95 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); 

    } 
});