2

我需要在我的程序中设置背景图像。主GUI的结构是:

JFrame 包含 - 带有 BoxLayou 的 JPanel 包含...等

我需要在第一个 JPanel 后面放一张图片,但我不知道怎么做。

我写了这段代码:

JPanel background = new JPanel();
JLabel labl = new JLabel("This is a dummy label this is a dummy label");
background.add(labl);
// TODO insert an image in background.
Component VERT_RA = Box.createRigidArea(new Dimension(0, 10));
Component HORI_RA = Box.createRigidArea(new Dimension(10, 0));
JPanel main = new JPanel();
main.setLayout(new BoxLayout(main, BoxLayout.PAGE_AXIS));
add(background);
add(main);
main.setOpaque(false);
main.add(VERT_RA);
JPanel a = new JPanel();
a.setLayout(new BoxLayout(a, BoxLayout.LINE_AXIS));
main.add(a);
main.add(VERT_RA);
a.add(HORI_RA);
JPanel services = new JPanel();
services.setLayout(new BoxLayout(services, BoxLayout.PAGE_AXIS));
a.add(services);
a.add(HORI_RA);
JPanel right = new JPanel();
right.setLayout(new BoxLayout(right, BoxLayout.PAGE_AXIS));
a.add(right);
a.add(HORI_RA);     
JLabel lbl = new JLabel("SERVIZI");
lbl.setFont(new Font("SansSerif", Font.BOLD, 30));
lbl.setAlignmentX(Component.CENTER_ALIGNMENT);
lbl.setPreferredSize(new Dimension(100, 100));      
services.add(lbl);

但如果我运行它,我只能看到“主”JPanel(“SERVIZI”标签)。如果我指定 setSize(x,y) 方法,我只能看到背景 JPanel。

有什么方法可以在我的布局中添加背景图像,而无需指定尺寸?

我也尝试使用 setLayou(null) 但我必须手动指定所有组件的尺寸(没用)。

4

3 回答 3

4

您只需覆盖getPreferredSize()相应 JPanel 的方法,并使其返回一些有效的维度对象。我想这个例子可能会在这个方向上帮助你:

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

public class PaintingExample
{
    private CustomPanel contentPane;
    private JTextField userField;
    private JPasswordField passField;
    private JButton loginButton;

    private void displayGUI()
    {
        JFrame frame = new JFrame("Painting Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        contentPane = new CustomPanel();        

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new PaintingExample().displayGUI();
            }
        });
    }
}

class CustomPanel extends JPanel
{
    private BufferedImage image;

    public CustomPanel()
    {
        setOpaque(true);
        setBorder(BorderFactory.createLineBorder(Color.BLACK, 5));
        try
        {
            /*
             * Since Images are Application Resources,
             * it's always best to access them in the
             * form of a URL, instead of File, as you are doing.
             * Uncomment this below line and watch this answer
             * of mine, as to HOW TO ADD IMAGES TO THE PROJECT
             * https://stackoverflow.com/a/9866659/1057230
             * In order to access images with getClass().getResource(path)
             * here your Directory structure has to be like this
             *                 Project
             *                    |
             *         ------------------------
             *         |                      |
             *        bin                    src
             *         |                      |
             *     ---------             .java files             
             *     |       |                   
             *  package   image(folder)
             *  ( or              |
             *   .class        404error.jpg
             *   files, if
             *   no package
             *   exists.)
             */
            //image = ImageIO.read(
            //      getClass().getResource(
            //              "/image/404error.jpg"));
            image = ImageIO.read(new URL(
                        "http://gagandeepbali.uk.to/" + 
                                "gaganisonline/images/404error.jpg"));
        }
        catch(IOException ioe)
        {
            System.out.println("Unable to fetch image.");
            ioe.printStackTrace();
        }
    }

    /*
     * Make this one customary habbit,
     * of overriding this method, when
     * you extends a JPanel/JComponent,
     * to define it's Preferred Size.
     * Now in this case we want it to be 
     * as big as the Image itself.
     */
    @Override
    public Dimension getPreferredSize()
    {
        return (new Dimension(image.getWidth(), image.getHeight()));
    }

    /*
     * This is where the actual Painting
     * Code for the JPanel/JComponent
     * goes. Here we will draw the image.
     * Here the first line super.paintComponent(...),
     * means we want the JPanel to be drawn the usual 
     * Java way first, then later on we will
     * add our image to it, by writing the other line,
     * g.drawImage(...).
     */
    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
}

但是,如果您不想使用继承,那么您可以简单地将图像添加到 JLabel,然后通过设置 JLabel 的布局将组件添加到 JLabel,如本示例本示例所示

于 2012-10-03T14:08:38.670 回答
3

您可以使用OverlayLayout。它使您可以将组件彼此堆叠在一起。像这样添加图像作为最低的图像应该可以:

JPanel backgroundPanel = new JPanel();
backgroundPanel.setLayout(new OverlayLayout(backgroundPanel));

backgroundPanel.add(/* your panel with controls */);
backgroundPanel.add(/* image component */);

请注意,带有控件的面板应该是透明的,以免隐藏背景图像。您可以通过设置 panel.setOpaque(false);

于 2012-10-03T12:55:27.103 回答
0

你可以这样做:

Image image = new ImageIcon(path);     
JLabel label=new JLabel(image);

如果您想使用 JLabel 作为背景图像,我认为这可能会完成您想要的工作。

无论如何,您可能还想看看ImageIcon Javadoc。

于 2012-10-03T12:42:40.303 回答