myeclipse 用Swing可视化编程,怎么添加背景图片?

背景图片大小怎么确定?

import java.awt.*;

import javax.swing.*;

public class TestBackgroundColor extends JFrame  {

public static void main(String[] args)  {

TestBackgroundColor tbc = new TestBackgroundColor();

tbc.setVisible(true);

}

private JPanel imagePanel;

private ImageIcon background;

public TestBackgroundColor()  {

background = new ImageIcon("C:\\Users\\Administrator\\Documents\\

My FTPRush Downloads\\项目\\Photoes\\007.jpg");//背景图片

JLabel label = new JLabel(background);//把背景图片显示在一个标签里面

//把标签的大小位置设置为图片刚好填充整个面板

label.setBounds(0,0,background.getIconWidth(),background.getIconHeight());

//把内容窗格转化为JPanel,否则不能用方法setOpaque()来使内容窗格透明

imagePanel = (JPanel)this.getContentPane();

imagePanel.setOpaque(false);

//内容窗格默认的布局管理器为BorderLayout

imagePanel.setLayout(new FlowLayout());

imagePanel.add(new JButton("测试按钮"));

this.getLayeredPane().setLayout(null);

//把背景图片添加到分层窗格的最底层作为背景

this.getLayeredPane().add(label,new Integer(Integer.MIN_VALUE));

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setSize(background.getIconWidth(),background.getIconHeight());

this.setVisible(true);

}

}

实现效果:

温馨提示:内容为网友见解,仅供参考
第1个回答  推荐于2017-11-26

代码的核心是组件全放一个JPanel里面,然后覆盖paintComponent()、同时绘背景图片。


import java.awt.Image;
import java.awt.Graphics;

import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;

public class JFrameBackground2 extends JFrame {
    private Image bgImage = new ImageIcon("IMAG0693_resize.jpg").getImage();
    public JFrameBackground2(){
        super("JFrameBackground2");
        this.setSize(500, 400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel pnl = new JPanel(){
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawImage(bgImage, 0, 0, null);
            }
        };
        pnl.add(new JLabel("Graphics Demo"));
        pnl.add(new JTextField("请输入文字"));
        pnl.add(new JButton("ClickMe"));
        this.add(pnl);
        this.setVisible(true);
    }
    
    public static void main(String args[]) {
        new JFrameBackground2();
    }
}

追问

用MyEclipse能不能像拖拽的组件设置属性一样快速设置背景图片呢?

追答

日前 没有,自己重写一个JFrame 或 JPanel,就方便了。

本回答被提问者采纳
相似回答