在JPanel上添加图像和按钮

时间:2017-02-24 00:28:00

标签: java swing

我在下面有这个JFrame:

public class TestJFrame extends JFrame {
    public RecyclingMachinesGui(String title) {
        super (title);

        Container container = getContentPane();
        container.setLayout(new FlowLayout());

        Panel r = new Panel();
        Jbutton j = new JButton("Recycle Item");
        r.add(j);
        container.add(r);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);      
        setSize(500,500);
        setVisible(true);
    }

    private class Panel extends JPanel {
        private BufferedImage image;

        public Panel() {
            try {
                image = ImageIO.read(new File("./temp.png"));
            }catch (IOException e) {
                e.getMessage().toString();
            }
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, this);
        }
    }
}

在我的main方法中的上述代码中,当我因某种原因运行new TestJFrame()时,我只看到JButton j里面的Panel(我添加到我的容器中)并且看不到面板内的图像。我的Panel中的paintComponent方法是否未被调用?

我希望在顶部有一张照片,在面板底部有一个按钮。任何人都可以解释为什么没有发生这种情况吗?

2 个答案:

答案 0 :(得分:2)

Panel中的图片未显示, 因为Panel没有正确的首选尺寸。 因此,LayoutManager(FlowLayout)不知道大小 给小组,并给它一个非常小的正方形的大小。 因此,您实际调用了Panel paintComponent, 但它只在一个看不见的小区域上绘画,

您可以在Panel的构造函数中轻松修复它, 加载图片后立即致电setPreferredSize

image = ImageIO.read(new File("./temp.png"));
setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));

答案 1 :(得分:2)

  

我希望在顶部有一张照片,在面板底部有一个按钮。任何人都可以解释为什么没有发生这种情况吗?

好的,所以你真的不需要自己绘制图像,JLabel本身会做得非常好,然后你只需要使用BorderLayout将标签添加到中心和南边的按钮,例如......

public class TestJFrame extends JFrame {
    public RecyclingMachinesGui(String title) {
        super (title);

        Container container = getContentPane();
        container.setLayout(new FlowLayout());

        JPanel r = new JPanel(new BorderLayout());
        try {
            r.add(new JLabel(new ImageIcon(ImageIO.read(new File("./temp.png")))));
        }catch (IOException e) {
            e.getMessage().toString();
        }
        Jbutton j = new JButton("Recycle Item");
        r.add(j, BorderLayout.SOUTH);
        container.add(r);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);      
        setSize(500,500);
        setVisible(true);
    }
}

您当前的方法会将按钮放在图像上,如果您想将图像用作背景,那就太棒了

相关问题