我想在我的JFrame中添加背景图像,但是当我使用下面的代码执行此操作时,我无法添加其他元素,如JLabel或JTextField。
ImageIcon icon = new ImageIcon("src/images/back.jpg");
backImage = icon.getImage();
BackgroundImagePanel contentPane = new BackgroundImagePanel();
contentPane.setBackgroundImage(backImage);
this.setContentPane(contentPane);
如果有另一种方法可以将JTabbedPane添加到具有背景的JFrame中,您能告诉我吗?
谢谢。
答案 0 :(得分:4)
喜欢这个吗?
附录:“通常你会首先调用super.paintComponent(g)
,但由于图像将覆盖整个背景,因此无需执行此操作。” - camickr
附录:另见opacity property。
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Imager {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ImagePanel("image.jpg"));
frame.pack();
frame.setVisible(true);
}
});
}
private static class ImagePanel extends JPanel {
BufferedImage img;
ImagePanel(String name) {
this.setToolTipText(name);
this.add(new JLabel(name));
try {
img = ImageIO.read(new File(name));
this.setPreferredSize(new Dimension(
img.getWidth(), img.getHeight()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
// super.paintComponent(g);
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
}
}
}
答案 1 :(得分:2)
尝试添加此内容:
//4. Size the frame.
this.pack();
//5. Show it.
this.setVisible(true);