繁体   English   中英

在 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,如果在图像抽屉顶部添加任何 JPanel,它们需要是透明的 (setOpaque(false)`) 所以背景图像显示通过。


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

您的 window 似乎是登录 window,如果是这样,如果这是我的程序,我什至不会使用 JFrame,而是更容易以这种方式显示的模态JDialog 程序流控制.


使用 GridBagLayout 和太多“幻数”的概念证明程序:

在此处输入图像描述

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()));
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM