更新时间:2022-04-25 07:23:47
BackgroundPanel
应该返回图像的尺寸作为最小首选尺寸 (@Override .. getPreferredSize()
代码>).如果有组件,可能会更大(超级尺寸更大).
BackgroundPanel
should return the size of the image as the minimum preferred size (@Override .. getPreferredSize()
). Possibly larger if it has components (the super size is larger).
带有图像的 JLabel
将不起作用,因为我将在背景面板顶部添加不同的标签.
A
JLabel
with an image won't work because I'm going to be adding different labels on top of the background panel.
有趣的是你应该提到这一点.可以(不一定推荐)设置 JLabel
的布局,然后向其中添加其他 JComponent
对象.在任何 JPanel
对象上调用 setOpaque(false)
很重要,否则 BG 图像将无法显示.
Funny you should mention that. It is possible (not necessarily recommended) to set the layout of a JLabel
, then add other JComponent
objects to it. It is important to call setOpaque(false)
on any JPanel
objects or the BG image won't show through.
这演示了两种方法.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class BackGroundImage {
private JComponent ui = null;
BackGroundImage() {
initUI();
}
public void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new GridLayout(0, 1));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
try {
BufferedImage bi1 = ImageIO.read(
new URL ("http://i.stack.imgur.com/OVOg3.jpg"));
BackgroundPanel bp = new BackgroundPanel(bi1);
ui.add(bp);
bp.setLayout(new GridBagLayout());
JLabel l1 = new JLabel("Using BackgroundPanel");
Font f = l1.getFont();
l1.setFont(f.deriveFont(32f));
l1.setForeground(Color.RED);
bp.add(l1);
BufferedImage bi2 = ImageIO.read(
new URL ("http://i.stack.imgur.com/lxthA.jpg"));
JLabel l = new JLabel(new ImageIcon(bi2));
ui.add(l);
l.setLayout(new GridBagLayout());
JLabel l2 = new JLabel("Using JLabel");
l2.setFont(f.deriveFont(32f));
l2.setForeground(Color.RED);
l.add(l2);
} catch (Exception e) {
e.printStackTrace();
}
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
BackGroundImage o = new BackGroundImage();
JFrame f = new JFrame("BackgroundPanel");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
class BackgroundPanel extends JPanel {
BufferedImage image;
public BackgroundPanel(BufferedImage image) {
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);
}
@Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
int w = d.width > image.getWidth() ? d.width : image.getWidth();
int h = d.height > image.getHeight() ? d.height : image.getHeight();
return new Dimension(w, h);
}
}