问题
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:
as already mentioned you need to add an instance of your
DisplayManager
class to a frame or panel.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