簡體   English   中英

未使用JPanel調用PaintComponent

[英]PaintComponent not being called with JPanel

當我運行此代碼時,永遠不會調用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");
}
}

基本代碼有兩個問題:

  1. 如前所述,您需要將DisplayManager類的實例添加到框架或面板中。

  2. 自定義繪畫時,您需要重寫組件的getPreferredSize()方法以返回所需的大小。 當前,組件的首選大小為(0,0)。

將DisplayManager添加到框架的建議僅能起作用,因為默認的布局管理器是BorderLayout並且默認情況下會添加到布局的CENTER ,這意味着它將獲得框架中的所有可用空間。

但是,如果您使用:

frame.add(this, BorderLayout.PAGE_START);

您不會看到組件大小為(0,0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM