在 JFrame 中将背景图像加载到 JPanel 时出错

Error loading background image into JPanel in a JFrame

我有一个 JFrame,我想用 JPanel 完全占据它,并在 JPanel.

中放置一个背景图像

代码:

public class InicioSesion extends javax.swing.JFrame{
private Image imagenFondo;
private URL fondo;

public InicioSesion(){
    initComponents();
    try{
        fondo = this.getClass().getResource("fondo.jpg");
        imagenFondo = ImageIO.read(fondo);
    }catch(IOException ex){
        ex.printStackTrace();
        System.out.print("Image dont load"); //Dont load the message.
    }

    Container c = getContentPane();
    c.add(PanelFondo);
}

public JPanel panelFondo = new JPanel(){
    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawImage(imagenFondo, 0, 0, getWidth(), getHeight(), this);
    }
};

为什么图片加载不出来?我的代码有什么解决方案吗?

您的问题在这里:

initComponents();

您可能使用此方法将所有组件添加到 GUI,很可能使用 GroupLayout 或其他用户不友好的布局管理器,然后在添加所有组件后添加 panelFondo JPanel。

如果你想让GUI显示背景图片,组件需要添加到图像绘制JPanel,如果任何JPanels被添加到图像绘制器的顶部,它们需要是透明的(setOpaque( false)`) 以便背景图片显示出来。


我猜您正在使用 GUI 构建器来创建 GUI 布局并帮助您向 GUI 添加组件。我自己避免使用它们,更喜欢使用布局管理器(绝不是空布局)手动创建我的 GUI。如果您绝对必须使用 GUI 构建器,那么让构建器为您创建一个 JPanel,而不是 JFrame,然后覆盖这个 JPanel 的 paintComponent,在其中绘制图像。否则,您最好像我一样学习 Swing 布局管理器并手动创建 GUI。

您的 window 似乎是登录 window,如果是这样,如果这是我的程序,我什至不会使用 JFrame,而是 modal JDialog 来显示这个,因为用这种方式控制程序流会容易得多。


使用 GridBagLayout 的概念验证程序太多了 "magic numbers":

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

@SuppressWarnings("serial")
public class LoginPanel extends JPanel {
    public static final String TITLE = "INICIO DE SESIÓN";
    public static final String IMG_PATH = "https://upload.wikimedia.org/wikipedia/"
            + "commons/thumb/6/69/MarsSunset.jpg/779px-MarsSunset.jpg";
    private JTextField usuarioField = new JTextField(20);
    private JPasswordField passwordField = new JPasswordField(20);
    private BufferedImage backgroundImg = null;

    public LoginPanel(BufferedImage img) {
        this.backgroundImg = img;
        JCheckBox showPasswordChkBx = new JCheckBox("Show Password");
        showPasswordChkBx.setOpaque(false);
        showPasswordChkBx.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    passwordField.setEchoChar((char) 0);
                } else {
                    passwordField.setEchoChar('*');
                }
            }
        });

        JButton accederBtn = new JButton("Acceder");
        accederBtn.addActionListener(e -> {
            Window win = SwingUtilities.getWindowAncestor(LoginPanel.this);
            win.dispose();
        });

        setForeground(Color.BLACK);

        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        int row = 0;

        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        int ins = 12;
        gbc.insets = new Insets(ins, ins, ins, ins);
        gbc.anchor = GridBagConstraints.CENTER;

        JLabel titleLabel = new JLabel(TITLE);
        titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 24f));
        add(titleLabel, gbc);

        row++;
        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.LINE_START;
        add(new JLabel("Usuario:"), gbc);

        gbc.gridx = 1;
        add(usuarioField, gbc);

        row++;
        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.insets = new Insets(ins, ins, 0, ins);
        add(new JLabel("Password:"), gbc);

        gbc.gridx = 1;
        add(passwordField, gbc);

        row++;
        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.insets = new Insets(0, ins, ins, ins);
        add(new JLabel(""), gbc);

        gbc.gridx = 1;
        add(showPasswordChkBx, gbc);

        row++;
        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.insets = new Insets(ins, ins, ins, ins);
        add(new JLabel(""), gbc);

        gbc.gridx = 1;
        add(accederBtn, gbc);

    }

    public String getUsuario() {
        return usuarioField.getText();
    }

    public char[] getPassword() {
        return passwordField.getPassword();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (backgroundImg != null) {
            g.drawImage(backgroundImg, 0, 0, getWidth(), getHeight(), this);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        Dimension superSize = super.getPreferredSize();
        int width = superSize.width;
        int height = superSize.height;
        if (backgroundImg != null) {
            width = Math.max(width, backgroundImg.getWidth());
            height = Math.max(height, backgroundImg.getHeight());
        }
        return new Dimension(width, height);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }

    private static void createAndShowGui() {
        BufferedImage img = null;
        try {
            URL imgUrl = new URL(IMG_PATH);
            img = ImageIO.read(imgUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }

        LoginPanel mainPanel = new LoginPanel(img);
        JDialog dialog = new JDialog((JFrame) null, LoginPanel.TITLE, ModalityType.APPLICATION_MODAL);
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.add(mainPanel);
        dialog.pack();
        dialog.setLocationByPlatform(true);
        dialog.setVisible(true);

        System.out.println("User Name: " + mainPanel.getUsuario());
        System.out.println("Password: " + new String(mainPanel.getPassword()));
    }
}