为窗体添加背景和为组件添加图片

为窗体添加背景

public class LoginPanel extends JPanel{
    private Image img;// 登录面板的背景图片
    public LoginPanel() {// 登录面板的构造方法
        super();// 调用父类JPanel的构造器
        URL url = getClass().getResource("login.png");// 获得登录面板背景图片的路径
        img = new ImageIcon(url).getImage();// 获得登录面板的背景图片
    }
    protected void paintComponent(Graphics g) {// 重写绘制组件方法
        super.paintComponent(g);// 绘制组件
        g.drawImage(img, 0, 0, this);// 绘制图片
    }
}

然后用  窗体对象.setContentPane(getLoginPanel());为窗体添加背景

为组件添加图片(以JButton为例)

button1.setIcon(new ImageIcon(getClass().getResource("button.png")));

button.png不用特意声明,直接添加到包内即可

猜你喜欢

转载自blog.csdn.net/liyuzhe1998/article/details/83539657