[英]Swing - paintComponent method not being called
我只是實現了繼承JPanel的類,如下所示
public class Orpanel extends JPanel {
....
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(tpaint);
g2d.fill(rect);
}
....
}
Orpanel類正在加載圖像並調整其自身大小。
這是問題。
調用JFrame的setContentpane(Orpanel的實例)使其工作正常,但是當我將Orpanel附加到JFrame時,調用add()方法而不是setContentpane(我知道setcontentpane並不意味着attach ..反正),它就無法正常工作。
最終弄清楚了當我使用add()方法時,添加到JFrame的Component不會調用paintComponent()方法。 即使我手動調用repaint()方法,仍然不會調用paintComponent()方法。
我錯過了什么? 任何幫助將不勝感激!
提前。 海永信
我添加了額外的代碼。
public Test(OwPanel op)
{
super();
Dimension monitor = Toolkit.getDefaultToolkit().getScreenSize();
op.setBackground(Color.white);
this.setBackground(Color.white);
this.setBounds(monitor.width / 2 - 200 , monitor.height / 2 - 200, 400, 400);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setTitle("test");
this.setLayout(null);
this.getContentPane().add(op);
//this.setContentPane(op);
this.setVisible(true);
this.validate();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
OwPanel op = new OwPanel("d:\\java_workplace\\img\\img1.jpg", 100, 100);
OwLabel ol = new OwLabel("d:\\java_workplace\\img\\img2.jpg", 300, 50);
Test tst = new Test(op);
tst.add(ol);
}
});
如果將setContentpane()方法替換為getContentpane()。add(),仍然無法正常工作。 不要困惑。 Owpanel和Orpanel相同:)
在您的示例代碼中,我看到您選擇不使用LayoutManager,這是一個非常糟糕的主意,但是無論如何,按照這種方式,我看到您的Orpanel.paintComponent()
不被調用的一個原因:可能不是在框架內可見!
如果沒有LayoutManager
,則必須(通過setBounds()
)顯式設置添加到框架的所有組件的大小和位置。
您可能沒有這樣做,因此Orpanel
實例的大小可能為0,因此它永遠不會被繪制。
聽起來您使用的方法錯誤。 將面板添加到框架時,您應該這樣做:
frame.getContentPane().add(panel) ;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.