Java为JFrame添加背景图片

知识预备:

jframe的组成:
jrootpane中包含glasspane和layeredpane两个面板。而layeredpane面板包含contentpane(内容面板)和jmenubar(菜单面板)                         
在jframe上添加组件,往往是添加在contentpane中,但是在contentpane的下面还有两层面板,那就是layeredpane和jrootpane

我的实现:

//将背景图绘在JFrame的倒数第二底层的Layeredpane上

  JLabel   picLabel   =   new   JLabel();
  picLabel.setIcon(new   ImageIcon( "img//主界面.jpg"));
  this.getLayeredPane().add(picLabel, new Integer(Integer.MIN_VALUE));
  picLabel.setBounds(0,0,1024,768);

 

//再在JFrame的最上层contentpane上添加按钮并且设置contentpane为透明。

  JPanel content = new JPanel();
  content=(JPanel)getContentPane(); 
  content.setOpaque(false);
  content.add(monthOrWeekPlanBtn);

 

这样就可以显示背景图片和按钮了。。。。。

 

欢迎转载,请注明出处:http://writeblog.csdn.net/PostEdit.aspx

 

要在Java JFrame窗口中添加背景图片,可以使用以下步骤: 1. 将图片文件保存在项目文件夹中。 2. 在JFrame类中创建一个JPanel对象来包含所有的组件。 3. 创建一个ImageIcon对象,将其设置为JPanel的背景。 4. 将JPanel对象添加JFrame中。 5. 调用JFrame的pack()方法来自动调整大小。 以下是一个简单的示例代码: ```java import javax.swing.*; import java.awt.*; public class JFrameWithBackground extends JFrame { public JFrameWithBackground() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 500, 500); // Create a JPanel to contain all components JPanel contentPane = new JPanel(); setContentPane(contentPane); contentPane.setLayout(null); // Load the background image ImageIcon backgroundImage = new ImageIcon("background.jpg"); // Set the background image as the JPanel's background JLabel backgroundLabel = new JLabel(backgroundImage); backgroundLabel.setBounds(0, 0, backgroundImage.getIconWidth(), backgroundImage.getIconHeight()); contentPane.add(backgroundLabel); // Add other components to the JPanel // ... // Pack and display the JFrame pack(); setVisible(true); } public static void main(String[] args) { new JFrameWithBackground(); } } ``` 在这个示例中,我们创建了一个JFrameWithBackground类,继承自JFrame。在构造函数中,我们首先设置了JFrame的默认关闭操作和大小。然后,我们创建了一个JPanel对象,并将其设置为JFrame的内容面板。我们使用null布局,以便我们可以自由地定位组件。 接下来,我们载了背景图片,并将其设置为JPanel的背景。我们创建了一个JLabel对象来显示该图像,并将其添加到JPanel中。我们还可以添加其他组件到JPanel中。 最后,我们调用JFrame的pack()方法来自动调整大小,使所有组件都可以适应窗口大小,并使JFrame可见。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值