问题
I'm having a problem adding a JPanel
on top of an Image
. This is what I'm trying to do:
Image bgImage = loadImage(filename);
JPanel jp = new JPanel();
jp.setBounds(100,100,100,100);
jp.setOpaque(true);
jp.setBackgroudColor(Color.red);
bgImage.add(jp);
After doing this, I only see the bgImage
. I tried everything but I still can't show the panel. Can somebody help me?
回答1:
You cannot place a component inside an Image
. What you want to do is paint the Image
onto the background of a swing component (like JPanel
). All swing components have a paint()
method that calls these three methods (perhaps not quite this order): paintComponent()
, paintChildren()
, paintBorder()
. So, you want to override the paintComponent()
method to paint your background image over the panel. When this runs, your custom method will be called, and then the paintChildren()
method will be called, which will paint all "child" components over the top of your background image:
class BackgroundImagePanel extends JPanel {
public void setBackgroundImage(Image backgroundImage) {
this.backgroundImage = backgroundImage;
}
@Override
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
graphics.drawImage(backgroundImage, 0, 0, this);
}
private Image backgroundImage;
}
BackgroundImagePanel panel = new BackgroundImagePanel();
panel.setBackgroundImage(image);
panel.add(new JTextField("Enter text here..."));
panel.add(new JButton("Press Me"));
回答2:
The "BackgroundImagePanel" solution paints the image at its actual size. If this is a requirement, then you can just use a JLabel instead of creating a custom component.
The BackgroundPanel entry shows how you can do this. It also provides a background panel with more custom image painting solutions, that will allow you to scale and tile the image, if this is part of your requirement.
来源:https://stackoverflow.com/questions/1549346/images-and-panels