gpt4 book ai didi

java - Swing - 没有调用 paintComponent 方法

转载 作者:搜寻专家 更新时间:2023-10-31 20:05:49 25 4
gpt4 key购买 nike

我简单地实现了继承 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 并不意味着附加......无论如何),它不起作用。

终于弄明白当我使用 add() 方法时,添加到 JFrame 的组件不会调用 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 的大小instance 可能为 0,因此它永远不会被绘制。

关于java - Swing - 没有调用 paintComponent 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7398335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com