简体   繁体   English

未使用JPanel调用PaintComponent

[英]PaintComponent not being called with JPanel

when I run this code PaintComponent is never called because the "painted" message is never printed and I do not know why? 当我运行此代码时,永远不会调用PaintComponent,因为永远不会打印“已绘制”消息,而且我也不知道为什么? can anyone help? 有人可以帮忙吗?

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");
}
}

There are a couple of problems with the basic code: 基本代码有两个问题:

  1. as already mentioned you need to add an instance of your DisplayManager class to a frame or panel. 如前所述,您需要将DisplayManager类的实例添加到框架或面板中。

  2. When you do custom painting you need to override the getPreferredSize() method of the component to return your desired size. 自定义绘画时,您需要重写组件的getPreferredSize()方法以返回所需的大小。 Currently the preferred size of your component is (0, 0). 当前,组件的首选大小为(0,0)。

The suggestion to add the DisplayManager to the frame only works because the default layout manager is a BorderLayout and by default is added to the CENTER of the layout which means it get all the available space in the frame. 将DisplayManager添加到框架的建议仅能起作用,因为默认的布局管理器是BorderLayout并且默认情况下会添加到布局的CENTER ,这意味着它将获得框架中的所有可用空间。

However if you use: 但是,如果您使用:

frame.add(this, BorderLayout.PAGE_START);

you won't see the component size it has a size of (0, 0); 您不会看到组件大小为(0,0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM