java 如何在GroupLayout Java中设置Jframe背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15493219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:47:23  来源:igfitidea点击:

How to set Jframe Background Image in GroupLayout Java

javaswingjframegrouplayout

提问by Ms_Joe

Am trying to set a background image for my frame but it does not work. I tried this link:

我正在尝试为我的框架设置背景图像,但它不起作用。我试过这个链接:

Setting background images in JFrame

在 JFrame 中设置背景图像

The code:

代码:

setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("/Images/about.png")))));

I tried adding the above code to my Contentpane but it does not work.

我尝试将上述代码添加到我的 Contentpane,但它不起作用。

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                MainMenu frame = new MainMenu();
                frame.setVisible(true);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public MainMenu() {
    setIconImage(Toolkit.getDefaultToolkit().getImage(MainMenu.class.getResource("/Images/bug-red.png")));
    setTitle("Automated Bug Fixing");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 712, 458);

            contentPane = new JPanel();

    //contentPane.setBackground(new Color(220, 220, 220));
    contentPane.setForeground(new Color(32, 178, 170));
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
            *setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("/Images/about.png")))));*

采纳答案by MadProgrammer

The basic concept looks fine.

基本概念看起来不错。

The only possible reason you might be getting problems is if the image doesn't exist.

您遇到问题的唯一可能原因是图像不存在。

It looks look you are trying to reference an image that should exist within the context of the Jar

看起来您正在尝试引用应该存在于 Jar 上下文中的图像

Instead of

代替

ImageIO.read(new File("/Images/about.png"))

Try

尝试

ImageIO.read(getClass().getResource("/Images/about.png"))

Instead.

反而。

Also, don't swallow exceptions, make sure all exceptions are been logged at the very least

另外,不要吞下异常,确保至少记录所有异常

enter image description here

enter image description here

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class BackgroundFrameImage {

    public static void main(String[] args) {
        new BackgroundFrameImage();
    }

    public BackgroundFrameImage() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                try {
                    JLabel label = new JLabel(new ImageIcon(ImageIO.read(...))));

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setContentPane(label);
                    frame.setLayout(new BorderLayout());
                    JLabel text = new JLabel("Hello from the foreground");
                    text.setForeground(Color.WHITE);
                    text.setHorizontalAlignment(JLabel.CENTER);
                    frame.add(text);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException | HeadlessException exp) {
                    exp.printStackTrace();
                }
            }
        });
    }

}

回答by Sinkingpoint

I've an inkling the problem may lie with

我知道问题可能出在

setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("/Images/about.png")))));

Try removing the leading slash in the file path, as this may be interpreted differently based on the OS:

尝试删除文件路径中的前导斜杠,因为这可能会因操作系统而异:

setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("Images/about.png")))));

回答by Java42

Put everything on an IPanel and put the IPanel on the JFrame. Tweak as necessary to suit your needs.

把所有东西放在一个IPanel 上,然后把IPanel 放在JFrame 上。根据需要进行调整以满足您的需求。

public class IPanel extends JPanel {
private static final long serialVersionUID = 1L;
private Image             imageOrg         = null;
private Image             image            = null;
{
    addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(final ComponentEvent e) {
            final int w = IPanel.this.getWidth();
            final int h = IPanel.this.getHeight();
            image = w > 0 && h > 0 ? imageOrg.getScaledInstance(w, h, Image.SCALE_SMOOTH) : imageOrg;
            IPanel.this.repaint();
        }
    });
}

public IPanel(final Image i) {
    imageOrg = i;
    image = i;
}

@Override
public void paintComponent(final Graphics g) {
    super.paintComponent(g);
    if (image != null)
        g.drawImage(image, 0, 0, null);
}
}

Example:

例子:

    final JPanel j = new IPanel(image);
    j.setLayout(new FlowLayout());
    j.add(new JButton("YoYo"));
    j.add(new JButton("MaMa"));
    j.add(new JLabel(icon));

Produces:

产生:

enter image description here

enter image description here