【问题标题】:PaintComponent not being called with JPanel没有使用 JPanel 调用 PaintComponent
【发布时间】:2016-11-18 20:49:45
【问题描述】:

当我运行此代码时,永远不会调用 PaintComponent,因为永远不会打印“绘制”消息,我不知道为什么?谁能帮忙?

public class DisplayManager extends JPanel {

public static final int WIDTH = 700, HEIGHT = 900;

public Bottle bottle1 = new Bottle("res/bottleimage.png");
public Slider slider1 = new Slider();

public void initDisplay()
{
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(new Dimension(WIDTH, HEIGHT));

    frame.add(panel);

    frame.setVisible(true);
}

@Override
public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    bottle1.imageIcon.paintIcon(this, g, 50, 50);
    System.out.println("painted");
}
}

【问题讨论】:

  • 如果您的DisplayManager 应该是JPanel,您必须将DisplayManager 添加到您的Frame 而不是新的JPanelframe.add(this) 而不是 frame.add(panel)
  • 谢谢老兄这工作
  • @PDPIG,这只是解决方案的一半。

标签: java swing paintcomponent imageicon


【解决方案1】:

基本代码有几个问题:

  1. 如前所述,您需要将DisplayManager 类的实例添加到框架或面板。

  2. 当您进行自定义绘画时,您需要覆盖组件的getPreferredSize() 方法以返回您想要的大小。目前,您的组件的首选大小是 (0, 0)。

将 DisplayManager 添加到框架的建议仅适用,因为默认布局管理器是 BorderLayout,默认情况下添加到布局的 CENTER,这意味着它可以获取框架中的所有可用空间。

但是如果你使用:

frame.add(this, BorderLayout.PAGE_START);

你不会看到它大小为 (0, 0) 的组件大小;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多