-1
我使用GUI設計器創建JPanel
類。我試圖給它添加背景圖片,但它什麼都沒顯示。如果我在JPanel
某處放置了JLabel
,它可以顯示JLabel
。JPanel背景圖像不顯示
我不認爲圖像路徑是一個問題,因爲我可以在另一個面板上顯示保存在此路徑中的其他圖像(使用JLabel
的setIcon()方法)。
背景圖片的尺寸爲1920x1080。
我在這裏搜索了很多帖子。有誰知道發生了什麼問題?
public class MenuPanel extends javax.swing.JPanel {
private final Image background;
public MenuPanel() {
initComponents();
background = new ImageIcon("/program/img/bg.jpg").getImage();
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(background, 0, 0, null);
}
@SuppressWarnings("unchecked")
private void initComponents() {
setPreferredSize(new java.awt.Dimension(800, 650));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 800, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 650, Short.MAX_VALUE)
);
}
}
public class GUI {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setSize(new Dimension(800, 650));
MenuPanel m = new MenuPanel();
frame.add(m);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
}
閱讀[文檔](http://docs.oracle.com/javase/8/docs/api/javax/swing/ImageIcon.html#ImageIcon-java.lang.String-)。 ImageIcon構造函數的參數是一個文件名。您的計算機是否在「/program/img/bg.jpg」上有文件? – VGR