3

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

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

但是,当我尝试此操作时,内容会被放入背景中并且不可见。另外,如果调整框架大小,我不知道如何调整图像大小。

是否有一个简单的解决方法,或者我是否需要重新编写大部分代码?

4

3 回答 3

4
  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涵盖了所有可用RectangleJFrame,然后Background Image(从我的第一点开始)永远不会被显示,因为这些JComponents是 on_topJFrame并且也可以隐藏它Image

  3. 添加JPanel with Background Image(从我的第一点开始),然后放另一个JPanel(s)with JPanel#setOpaque(false);,那么这JPanel将是透明JPanel的,默认情况下已实现通知FlowLayout

于 2012-03-22T03:58:28.613 回答
1
frame.getContentPane().add(new JPanel() {

      public void paintComponent(Graphics g) {
            g.drawImage(img, 0, 0, this.getWidth(), this.getHeight());
      }
});
于 2012-03-22T05:21:54.833 回答
0

这个例子会让你开始。像使用任何 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);
于 2012-03-22T05:24:49.380 回答