JFrame嵌套背景另外一种实现方式

实现背景图片的第二种方式,重写JPanel,再重写JPanel的paintComponent(Graphics g)方法,JPanel会调用paintComponent画出自身,在这之后我们再将自己需要的背景画出来就实现了添加背景图片的方法

MyFrame.java:

package Back;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class MyFrame extends JFrame{

    private MyPanel contentPanel;

    private JButton button;

    private JTextField text;



    public MyFrame() {
        contentPanel = new MyPanel();

        contentPanel.setLayout(new BorderLayout());
        button = new JButton("button");
        contentPanel.add(button, BorderLayout.NORTH);

        text = new JTextField();
        contentPanel.add(text, BorderLayout.SOUTH);

        addListener();
        this.setContentPane(contentPanel);
        this.setSize(contentPanel.getWidth(), contentPanel.getHeight());
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setVisible(true);
    }


    public void addListener() {
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("hello, world!" + text.getText());
            }

        });
    }

    public static void main(String[] args) {
        new MyFrame();
    }
}

MyPanel.java

package Back;

import java.awt.Graphics;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class MyPanel extends JPanel{

    private ImageIcon imageIcon;

    private int width;

    private int height;


    public MyPanel() {
        imageIcon = new ImageIcon("resource\\冬天3.jpg");
        width = imageIcon.getIconWidth();
        height = imageIcon.getIconHeight();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        //这个只能出现在super.paintComponent(g)方法之后,否则将不会画出背景图片
        g.drawImage(imageIcon.getImage(), 0, 0, width, height, null);
    }
    /**
     * 返回面板的宽度
     */
    public int getWidth() {
        return width;
    }
    /**
     * 返回面板的高度
     */
    public int getHeight() {
        return height;
    }

}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值