繁体   English   中英

背景图像JFrame与内容

[英]Background image JFrame with content

我有一个带有BorderLayoutJFrame ,四面都有面板(北,东,......)。 在面板中主要有标签和按钮。

现在我希望框架有一个背景图像,一些研究告诉我,我必须更改框架的内容窗格。

但是,当我尝试这样做时,内容将被放入后台并且不可见。 另外,如果调整帧大小,我不知道如何调整图像大小。

有没有一个简单的解决方案或我将不得不重做我的大部分代码?

  1. 将带有背景图像的JPanel (或JComponent )放到BorderLayout.CENTER ,然后这个JPanel填充整个JFrame区域,其余的JComponents放到这个JPanel

  2. there are Jpanels on all sides (North, East ,...). In the Jpanels there are Jlabels and Jbuttons mostly.

    这些JComponents覆盖了JFrame所有可用Rectangle ,然后Background Image (从我的第一点开始)永远不会被显示出来,因为这些JComponents是on_top JFrame并且可以隐藏这个Image

  3. 添加JPanel with Background Image (从我的第一点开始),然后将另一个JPanel(s)JPanel#setOpaque(false); ,那么这个JPanel将是透明的,请注意JPanel默认使用FlowLayout实现

frame.getContentPane().add(new JPanel() {

      public void paintComponent(Graphics g) {
            g.drawImage(img, 0, 0, this.getWidth(), this.getHeight());
      }
});

这个例子可以帮助你入门。 像任何JPanel一样使用它。

public class JPanelWithBackground extends JPanel {
Image imageOrg = null;
Image image = null;
{
    addComponentListener(new ComponentAdapter() {
        public void componentResized(ComponentEvent e) {
            int w = JPanelWithBackground.this.getWidth();
            int h = JPanelWithBackground.this.getHeight();
            image = w>0&&h>0?imageOrg.getScaledInstance(w,h, 
                    java.awt.Image.SCALE_SMOOTH):imageOrg;
            JPanelWithBackground.this.repaint();
        }
    });
}
public JPanelWithBackground(Image i) {
    imageOrg=i;
    image=i;
    setOpaque(false);
}
public void paint(Graphics g) {
    if (image!=null) g.drawImage(image, 0, 0, null);
    super.paint(g);
}
}

用法示例:

    Image image = your image
    JFrame f = new JFrame("");
    JPanel j = new JPanelWithBackground(image);
    j.setLayout(new FlowLayout());
    j.add(new JButton("YoYo"));
    j.add(new JButton("MaMa"));
    f.add(j);
    f.setVisible(true);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM