我只是实现了一个继承JPanel的类,如下所示:
如果将setContentpane()方法替换为getContentpane().add(),仍然无法正常工作。不要混淆,Owpanel和Orpanel是相同的 :)
我只是实现了一个继承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的实例)可以正常工作,但是当我使用add()方法而不是setContentpane将Orpanel附加到JFrame时(我知道setcontentpane并不意味着附加..无论如何),它不起作用。
最终发现当我使用add()方法时,被添加到JFrame中的组件不会调用paintComponent()方法。即使我手动调用repaint()方法,仍然不会调用paintComponent()方法。
我错过了什么吗? 任何帮助将不胜感激!
提前致谢。 Jaeyong shin。
我添加了额外的代码。
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是相同的 :)
OrPanel
添加到JFrame
的代码吗? - Mohayemin