不能使用JPanel调用PaintComponent [英] PaintComponent not being called with JPanel

查看:68
本文介绍了不能使用JPanel调用PaintComponent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行此代码时,永远不会调用PaintComponent,因为永远不会打印"painted"消息,而且我也不知道为什么?有人可以帮忙吗?

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. 如上所述,您需要将 DisplayManager 类的实例添加到框架或面板.

  1. as already mentioned you need to add an instance of your DisplayManager class to a frame or panel.

自定义绘画时,您需要重写组件的 getPreferredSize()方法以返回所需的尺寸.当前,组件的首选大小为(0,0).

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).

仅在默认布局管理器是 BorderLayout 且默认情况下将其添加到布局的 CENTER 时,才建议将DisplayManager添加到框架中获取框架中的所有可用空间.

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.

但是,如果您使用:

frame.add(this, BorderLayout.PAGE_START);

您不会看到组件大小为(0,0);

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

这篇关于不能使用JPanel调用PaintComponent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆