当我运行此代码时,PaintComponent 永远不会被调用,因为“painted”消息永远不会被打印,我不知道为什么?有人可以帮忙吗?
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
类的实例添加到框架或面板。当您进行自定义绘制时,您需要重写组件的
getPreferredSize()
方法以返回所需的尺寸。目前组件的首选大小是 (0, 0)。
将 DisplayManager 添加到框架的建议仅有效,因为默认布局管理器是 BorderLayout
并且默认情况下添加到布局的 CENTER
这意味着它获取框架中的所有可用空间。
但是如果您使用:
frame.add(this, BorderLayout.PAGE_START);
您不会看到组件大小,它的大小为 (0, 0);
关于java - PaintComponent 没有被 JPanel 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40685729/