2017-10-17 81 views
-2

我回來了一個有關Java的圖形通過擺問題...我想在一個JFrame畫一些東西,這裏是代碼:重繪永遠不會到達paintComponent();

PaintUtil級:

public class PaintUtil extends JPanel{ 

public PaintUtil(){ 
    this.setFocusable(true); 
    this.requestFocus(); 
} 

    @Override 
    public void paintComponent(Graphics g){ 
     super.paintComponent(g); 
     System.out.println("Repainted"); 

     g.drawstuff... 
    } 
} 

Main-等級:

public static PaintUtil util = new PaintUtil(); 

JFrame frame = new JFrame(); 
frame.setSize(500,600); 
frame.setRezisable(false); 
frame.add(util); 
frame.setDefaultCloseOperation(3); 
frame.getContentPane().setColor(Color.BLACK); 
setup(); //This add some buttons 
frame.setVisible(true); 

util.repaint(); //not working 
util.paintComponent(frame.getGraphics()); //works 

你們能幫我嗎?

+0

什麼'PaintUtil'擴展? –

+0

PaintUtil擴展JPanel – Caipi

+0

您的組件實際上是否在屏幕上? – khelwood

回答

2

沒有錯誤,在控制檯沒有消息,只是沒有

frame.setLayout(null); 

不要使用空佈局。 Swing旨在與佈局經理一起使用。擺脫這種說法。

默認情況下,面板的大小是(0,0),所以沒有東西可以繪製。

您將需要覆蓋面板的getPreferredSize()方法,以便佈局管理器可以完成其工作。

閱讀Swing教程中有關Custom Painting的部分以獲取更多信息和工作示例。

+0

好吧,現在我已經消除了空佈局,但仍然有同樣的問題 – Caipi

+0

Shoukd我mabey打印你全班?但是,只有當你專注於我問的問題,而不是其他不好的事情時,我才知道;) – Caipi

+0

@Caipi,發佈一個證明問題的適當的[mcve]。 – camickr

相關問題