2011-01-09 35 views
2

我有一個jrame,我在其中添加了一些JComponent對象。 每個JComponent都有一個我使用JComponent.add(Component)添加的容器列表。將容器上的paint添加到jcomponent中

現在在我的主要JComponent類中,名爲MyComponent,我重寫受保護的方法paintComponent,在那裏我可以繪製的東西,它工作得很好。

但我不想畫在主JComponent上,我只想繪製我已添加到我的主JComponent的容器上。

所以在PaintComponent中的MyComponent中,我執行以下操作。

protected void paintComponent(Graphics g) { 
    super.paintComponent(g); 

    Graphics page_g = this.getPage("main").getGraphics(); 

    page_g.setColor(Color.RED); 
    page_g.drawRect(10, 10, this.getWidth() - 20, this.getHeight() - 20); 
    page_g.setColor(Color.BLUE); 
    page_g.drawString("HELLO WORLD", this.getWidth()/2, this.getHeight()/2); 
} 

該行this.getPage(「main」)。getGraphics();將我的一個容器中的Graphics對象添加到MyComponents容器列表中,當然還可以使用JComponents add方法將其添加到主要組件列表中。通過調用setVisible(true)將容器設置爲可見;方法。

但沒有任何反應。屏幕是空的。當我用g替換page_g時,然後繪畫工作,因爲它的繪製在我的JComponent(MyComponent)上,但是我想在這種情況下在MyComponent的一個子集上繪製容器。

我經常聽到「從不使用getGraphics()」。但是,如果父類paintComponent方法被調用,其他父組件的子組件如何才能使用父組件的子組件?

回答

1

真的最好的辦法是讓實際做自定義繪畫的類覆蓋自己的paintComponent()方法。讓AWT擔心圖形上下文。

+0

但這意味着我必須爲每個要添加到我的組件的容器定義一個類。但是我想在我的組件類中完成所有這些。我知道它是避開getGraphics的最好方法。但我只是問是否還有一個好的解決方案。 – NovumCoder 2011-01-10 00:09:38

相關問題