我正在尝试使用标准的Java实用程序将图像叠加在背景图像上。见下面的图片...

我有似乎可以创建背景图像的代码(您可以验证它是否确实有效吗?)
我创建了JPanel扩展,用于显示图像(该类称为ImagePanel)

但是,在程序启动时,JFrame仅显示第二个图像,然后在调整窗口大小时移动第二个图像。

我想首先打开窗口,背景图像占据整个窗口空间。然后,我想在我指定的位置将第二张图像显示在顶部。

import javax.swing.*;
import java.awt.*;

public class ImageTest {




public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.getContentPane().setLayout(null);

    JPanel backgroundPanel = new JPanel();
    ImageIcon backgroundImage = new ImageIcon("C:\\Documents and Settings\\Robert\\Desktop\\ClientServer\\Poker Table Art\\TableAndChairs.png");
    JLabel background = new JLabel(backgroundImage);
    background.setBounds(0, 0, backgroundImage.getIconWidth(), backgroundImage.getIconHeight());
    frame.getLayeredPane().add(background, new Integer(Integer.MIN_VALUE));
    backgroundPanel.setOpaque(false);
    frame.setContentPane(backgroundPanel);

    ImagePanel button = new ImagePanel("C:\\Documents and Settings\\Robert\\Desktop\\ClientServer\\Poker Table Art\\button.png");
    JPanel cardContainer = new JPanel(new FlowLayout());


    frame.getContentPane().add(cardContainer);

    cardContainer.add(button);
    cardContainer.setBounds(100, 600, 200, 200);

    frame.pack();
    frame.setVisible(true);
  }
}


alt text http://img189.imageshack.us/img189/9739/image1qi.jpg

alt text http://img186.imageshack.us/img186/1082/image2ll.jpg

最佳答案

您可以将背景面板的首选大小设置为图像大小:

backgroundPanel.setPreferredSize(new Dimension(
    backgroundImage.getIconWidth(), backgroundImage.getIconHeight()));


我主张遵循@camickr的方法。这是我自己以前没有尝试过setBounds()的示例,下面是一个简单的示例来查看效果:

import javax.swing.*;
import java.awt.*;

public class ImageTest {

    public static void main(String[] args) {

        JFrame frame = new JFrame();
        JLabel label = new JLabel(new ElliptIcon(380, 260, Color.red));
        label.setLayout(new GridLayout(2, 2));
        frame.setContentPane(label);

        for (int i = 0; i < 4; i++) {
            label.add(new JLabel(new ElliptIcon(100, 60, Color.blue)));
        }

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    private static class ElliptIcon implements Icon {

        private int w, h;
        private Color color;

        public ElliptIcon(int w, int h, Color color) {
            this.w = w;
            this.h = h;
            this.color = color;
        }

        @Override
        public void paintIcon(Component c, Graphics g, int x, int y) {
            g.setColor(color);
            g.fillOval(x, y, w, h);
        }

        @Override
        public int getIconWidth() { return w; }

        @Override
        public int getIconHeight() { return h; }
    }
}

10-07 23:49