JFrame上传背景不了怎么办啊

源码如下

import javax.swing.*;
import java.awt.*;

public class MyPanel extends JPanel {
    @Override//重写画笔工具
    public void paintComponent(Graphics g) {
        super.paintComponents(g);
        Image img = new ImageIcon("/img/bg/mbg.png").getImage();//定义一个背景图片对象

        g.drawImage(img,0,0,this.getWidth(),this.getHeight(),this);
    }
}

 

 

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*
    登录窗口
* */
public class LoginFrame extends JFrame {

    private JLabel uNameJLabel;
    private JTextField uNameJTextField;
    private JButton btnJButton;
    private JButton cancelJButton;

    public LoginFrame(){
        //创建组件
        this.uNameJLabel = new JLabel("用户名");
        this.uNameJTextField = new JTextField();//创建文本框对象
        this.btnJButton = new JButton("登录");//创建按钮对象
        this.cancelJButton = new JButton("取消");
        //设置窗体属性
        this.setSize(400,300);//设置登录界面大小
        this.setLocationRelativeTo(null);//设置窗体居中
        this.setDefaultCloseOperation(3);//设置退出游戏时关闭程序
        this.setLayout(new GridLayout(2,2));//设置布局是GridLayout类型的2行2列
        //给窗口添加组件
        this.add(uNameJLabel);
        this.add(uNameJTextField);
        this.add(btnJButton);
        this.add(cancelJButton);
        this.setVisible(true);//设置窗体可见


        MyEvent myEvent = new MyEvent();//创建监听器对象
        this.btnJButton.addActionListener(myEvent);//将监听器对象绑定到指定按钮上
    }

    class MyEvent implements ActionListener{
        //创建一个内部类,继承监听类,实现监听,也可以创建一个外部类
        @Override//监听类ActionListener接口需要实现的方法
        public void actionPerformed(ActionEvent e) {
            //1.获取用户名
            String uName = uNameJTextField.getText();

            //2.创建一个socket链接服务器端

            //3.跳转到主窗口去 (服务器判断用户名和密码准确后,跳转。本游戏不考虑先)
            new MainFrame(uName);
        }
    }
}

 

 

import javax.swing.*;

/*
    主窗口
* */
public class MainFrame extends JFrame {
    public MyPanel myPanel;
    public String uNameStr;

    public MainFrame(String uName){
        uNameStr = uName;

        //设置窗体属性
        this.setSize(1200,666);
        this.setVisible(true);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        myPanel = new MyPanel();
        myPanel.setBounds(0,0,1200,666);//从原点开始,宽1200 高666的画布面板
        //将面板myPanel添加到窗体
        this.add(myPanel);

    }
}

 

 

 

public class Main {
    public static void main(String[] args) {

        new LoginFrame();//创建登录对象,登录类继承JFrame,所以也会调用JFrame中的一些方法

    }
}

 

 

 

背景图存放路径

 

登录窗口是正常的!!

 

 

但是主界面背景图加载不了!!有大神能帮忙解答吗?!!!

你肯定是图片路径不对,或者图片组件使用问题。

还学这个,没啥用,直接bs学起来

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps: 问答会员年卡【8折】购 ,限时加赠IT实体书,即可 享受50次 有问必答服务,了解详情>>>https://t.csdnimg.cn/RW5m