当我运行程序时我正在设置框架的背景图像我的其他组件是不可见的只有图像在框架中可见
class ImagePanel extends JComponent {
private Image image;
public ImagePanel(Image image) {
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
在主课程中,我调用上面的类,如下所示:
BufferedImage myImage = ImageIO.read(new File("cal.jpg"));
frame.setContentPane(new ImagePanel(myImage));
答案 0 :(得分:2)
您有以下代码:
BufferedImage myImage = ImageIO.read(new File("cal.jpg"));
frame.setContentPane(new ImagePanel(myImage));
但您似乎正在创建ImagePanel实例 inline ,并且似乎没有向此ImagePanel实例添加任何组件,因此我不会对您没有看到任何组件感到惊讶。您似乎也没有在ImagePanel构造函数中向其添加任何组件。
考虑在构造函数中或在使用它的类中向ImagePanel类添加组件,创建ImagePanel实例,将其分配给变量,向其添加组件,然后然后将其放入JFrame的contentPane。
侧面建议:
null
布局,这是你不想使用的。例如,这对我有用:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class TestImagePanel {
private static void createAndShowGui() {
String resource = "/imgFolder/PlanetEarth.jpg";
Image image = null;
try {
image = ImageIO.read(TestImagePanel.class.getResource(resource));
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
ImagePanel mainPanel = new ImagePanel(image);
mainPanel.setLayout(new FlowLayout());
mainPanel.add(new JButton("Fubars Rule!"));
JFrame frame = new JFrame("TestImagePanel");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
@SuppressWarnings("serial")
class ImagePanel extends JComponent {
private Image image;
public ImagePanel(Image image) {
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
@Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
int w = image == null ? superSize.width : Math.max(superSize.width, image.getWidth(null));
int h = image == null ? superSize.height : Math.max(superSize.height, image.getHeight(null));
Dimension d = new Dimension(w, h);
return d;
}
}
并展示了这个GUI: