向 JFrame 添加背景

Add a background to a JFrame

我想为我的 JFrame 添加背景,但无法完成。 我在互联网上搜索了一些关于它的教程。 我还是一个新手,我想学习这些东西。 这是我目前所拥有的。

package gui;

import java.awt.Desktop;

public class Gui extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel contentPane;
    private JLabel BackgroundLabel;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Gui frame = new Gui();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Gui() {
        setTitle("Exile Launcher");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 1000, 563);
        contentPane = new JPanel();
        contentPane.setBorder(null);
        setContentPane(contentPane);
        contentPane.setLayout(null);

        BufferedImage BackgroundImage = null;
        try {
            BackgroundImage = ImageIO.read(this.getClass().getResource("/Images/Background.jpg"));
        } catch (IOException ex) {
        }

        JLabel BackgroundLabel = new JLabel(new ImageIcon(BackgroundImage));

        add(BackgroundLabel);

        JButton HomeButton = new JButton("Home");
        HomeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    Desktop.getDesktop().browse(new URL("http://www.google.nl").toURI());
                } catch (MalformedURLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (URISyntaxException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });

        HomeButton.setBounds(10, 9, 50, 50);
        contentPane.add(HomeButton);

        JButton ForumButton = new JButton("Vote");
        ForumButton.setBounds(10, 70, 50, 50);
        contentPane.add(ForumButton);

        JButton VoteButton = new JButton("New button");
        VoteButton.setBounds(10, 131, 50, 50);
        contentPane.add(VoteButton);
    }
}

但是我得到这个错误:

java.lang.IllegalArgumentException: input == null!
    at javax.imageio.ImageIO.read(ImageIO.java:1388)
    at gui.Gui.<init>(Gui.java:59)
    at gui.Gui.run(Gui.java:36)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:312)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:733)
    at java.awt.EventQueue.access0(EventQueue.java:103)
    at java.awt.EventQueue.run(EventQueue.java:694)
    at java.awt.EventQueue.run(EventQueue.java:692)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:703)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

异常不言自明

 BackgroundImage = ImageIO.read(this.getClass().getResource("/Images/Background.jpg"));

您正在将 illegalArgument 传递给 ImageIO class

read() 方法

作为JavaDoc syas

public static BufferedImage read(File input)
                          throws IOException

Returns a BufferedImage as the result of decoding a supplied File with an ImageReader chosen automatically from among those currently registered. The File is wrapped in an ImageInputStream. If no registered ImageReader claims to be able to read the resulting stream, null is returned.

您需要像这样传递文件 Class 对象 :

 BackgroundImage = ImageIO.read(new File("C:\Users\Ruud\workspace\ExileLauncher\Images\Background.jpg"));

注意:需要传递所在文件的绝对路径

建议:如果您正在捕获 Exception 尝试将其打印出来,以便您了解根本原因。

 try {
 BackgroundImage = ImageIO.read(this.getClass().getResource("/Images/Background.jpg"));
  } catch (IOException ex) {
      ex.printStackTrace();// Here printing the stackTrace of Exception
        }

更新

我知道了 运行宁。首先使用空布局但不指定您需要关注的方面。当你只是做 "add(backgroundLabel);" 你需要 运行 backgroundLabel.setBounds(new Rectangle(int x, int y, width, hight); 我要去给你完整的代码。确保你的文件路径重置为你需要的。

只要把它放进去,设置你的路径,它就应该 运行。您需要确保 class 名称与您期望的任何名称相匹配,但在这里:

import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Gui extends JFrame {

private static final long serialVersionUID = 1L;
private final JPanel contentPane;
private JLabel BackgroundLabel;
Image background;


/**
 * Launch the application.
 */
public static void main(final String[] args) {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                final Gui frame = new Gui();
                frame.setVisible(true);
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }
    });
}


/**
 * Create the frame.
 */
public Gui() {
    this.setTitle("Exile Launcher");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setBounds(100, 100, 1000, 563);
    this.contentPane = new JPanel();
    this.contentPane.setBorder(null);
    this.setContentPane(this.contentPane);
    this.contentPane.setLayout(null);

    try {
        this.background = ImageIO.read(new File("src/Images/Background.jpg"));
    } catch (final IOException e) {
        e.printStackTrace();
    }

    final JLabel backgroundLabel = new JLabel(new ImageIcon(this.background));
    backgroundLabel.setBounds(new Rectangle(0, 0, 1000, 563));
    this.add(backgroundLabel);

    final JButton HomeButton = new JButton("Home");
    HomeButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            try {
                Desktop.getDesktop().browse(new URL("http://www.google.nl").toURI());
            } catch (final MalformedURLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (final IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (final URISyntaxException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    });

    HomeButton.setBounds(10, 9, 50, 50);
    this.contentPane.add(HomeButton);

    final JButton ForumButton = new JButton("Vote");
    ForumButton.setBounds(10, 70, 50, 50);
    this.contentPane.add(ForumButton);

    final JButton VoteButton = new JButton("New button");
    VoteButton.setBounds(10, 131, 50, 50);
    this.contentPane.add(VoteButton);
}


// Final Piece to add an image to the jpanel
public void paintComponent(final Graphics pic) {
    this.paintComponent(pic);
    pic.drawImage(this.background, 0, 0, null);
}
}