2015-05-08 40 views
-1

我在使用此代碼時遇到問題。出於某種原因,paintComponent(Graphics g)根本不起作用,似乎沒有答案如何強制它。這是我的代碼:爲什麼paintComponent不起作用?

import javax.swing.JFrame; 

public class Robotron extends JFrame 
{ 

    public Robotron() 
    { 
     //add(this); This one gave me an error 
     setSize(800, 600); 
     new TestFrame(); 
     setVisible(true); 
    } 


    public static void main(String [ ] args) 
    { 

     new Robotron(); 

    } 

,這是我TestFrame類具有的paintComponent功能:

import java.awt.Color; 
import java.awt.Graphics; 

import javax.swing.JPanel; 


public class TestFrame extends JPanel 
{ 
    public void paintComponent(Graphics g) 
    { 
     g.setColor(Color.BLACK); 
     g.fillRect(0, 0, getWidth(), getHeight()); 
     g.setColor(Color.YELLOW); 
     g.fillRect(100, 100, 10, 30); 
     System.out.println("Abdullah Paint"); 

    } 


    public TestFrame() 
    { 
     setFocusable(true);   
     repaint();   

    } 


} 

我能以使實際的paintComponent玩做。我最終得到的只是一個空的JFrame,沒有運行System.out.println thingy。

非常感謝,長期以來一直在解決這個問題。

回答

0

你不添加任何內容到JFrame,因爲這個

//add(this); 

在這裏,你試圖添加的組件自己,這是不會飛。

相反,您需要將TestFrame實例添加到框架。

add(new TestFrame()); 
    setSize(800, 600); 
    setVisible(true); 
+0

沒關係啊,它被添加到Frame啄本身...這有很大幫助,謝謝! – TheForgot3n1

0

您需要將面板添加到幀:

public Robotron() 
{ 
    //add(this); This one gave me an error 
    setSize(800, 600); 
    add(new TestFrame()); 
    setVisible(true); 
} 
+0

感謝很多答案隊友:) – TheForgot3n1

0

正如其他人所提到的,您需要將面板添加到幀:

public Robotron() { 

    add(new TestFrame()); 
    setSize(800, 600); 
    setVisible(true); 
} 

由於不被別人提及,你需要調用super.paintComponent(g)的第一件事就是在你的重寫方法:

@Override 
public void paintComponent(Graphics g) { 

    super.paintComponent(g); 
    g.setColor(Color.BLACK); 
    g.fillRect(0, 0, getWidth(), getHeight()); 
    g.setColor(Color.YELLOW); 
    g.fillRect(100, 100, 10, 30); 
    System.out.println("Abdullah Paint"); 
} 

注:

  • 不要在構造函數中調用repaint()。最好它什麼都不做。
  • 請不要致電setSize(...),而應致電pack()。您需要覆蓋面板中的getPreferredSize方法。
+0

在paintComponent方法之前編寫「super」似乎沒有必要。也不是最重要的東西。目前,只使用套標,因爲它似乎沒有任何問題。 – TheForgot3n1

+0

@ TheForgot3n1如果您在第一次調用paintComponent之前不使用'super.',您將獲得無限遞歸。 '@ Override'只是一個註釋,但強烈建議使用它。 'setSize'將適用於你的屏幕和分辨率,但不適用於我和我的朋友。 – user1803551

相關問題