PaintComponent not being called with JPanel

≯℡__Kan透↙ 提交于 2020-01-30 12:25:05

问题


when I run this code PaintComponent is never called because the "painted" message is never printed and I do not know why? 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");
}
}

回答1:


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.

  2. When you do custom painting you need to override the getPreferredSize() method of the component to return your desired size. Currently the preferred size of your component is (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.

However if you use:

frame.add(this, BorderLayout.PAGE_START);

you won't see the component size it has a size of (0, 0);



来源:https://stackoverflow.com/questions/40685729/paintcomponent-not-being-called-with-jpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!