swing设置背景图片和按钮

来源:互联网 发布:托福培训费用知乎 编辑:程序博客网 时间:2024/05/21 14:43
public class ImageFrame extends JFrame{    Dimension frameSize = new Dimension(1000, 600);    ImageIcon imageIcon = new ImageIcon(this.getClass().getResource("/game/img/startGame.jpg"));    public ImageFrame(String title) {        // 设置窗体属性        setSize(frameSize);        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        setIconImage(imageIcon.getImage());    }    public void addImageByJLable() {        setLayout(null);        // 设置背景        JLabel lbBg = new JLabel(imageIcon);        lbBg.setBounds(0, 0, frameSize.width, frameSize.height);        getContentPane().add(lbBg);        addComponents();        setVisible(true);    }        public void addImageByRepaint() {        ImagePanel imagePanel = new ImagePanel(frameSize, imageIcon.getImage());        setContentPane(imagePanel);        addComponents();        setVisible(true);    }        class ImagePanel extends JPanel {        Dimension dimension;        Image image;        public ImagePanel(Dimension dimension, Image image) {            super();            this.dimension = dimension;            this.image = image;        }        @Override        public void paintComponent(Graphics g) {            super.paintComponent(g);            g.drawImage(image, 0, 0, dimension.width, dimension.height, this);            repaint();        }    }    private void addComponents() {        JButton btn1 = new JButton("新游戏");        JButton btn2 = new JButton("排行榜");        JButton btn3 = new JButton("退出游戏");        btn1.setBounds(500, 500, 100, 50);        btn2.setBounds(400, 300, 100, 50);        btn3.setBounds(400, 400, 100, 50);        this.getContentPane().add(btn1);        this.getContentPane().add(btn2);        this.getContentPane().add(btn3);    }    public static void main(String[] args) {        ImageFrame imageFrame = new ImageFrame("AAA");         imageFrame.addImageByJLable();//        imageFrame.addImageByRepaint();    }}

原创粉丝点击