我已經經歷了每一篇文章,我可以找到這個網站和Java教程,我仍然無法弄清楚爲什麼我的代碼不工作。即使我複製/粘貼其他人的代碼,它仍然不起作用。圖片將不會顯示在JLabel
我做了一個假的程序只是爲了測試這一點,並且代碼看起來像這樣:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
public class gui extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
gui frame = new gui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public gui() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 900, 700);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel(new ImageIcon("bg.png"));
contentPane.add(lblNewLabel);
}
}
我試圖顯示,bg.png背景圖像,位於項目的根夾。我嘗試了多種格式的路徑字符串,但沒有成功。我究竟做錯了什麼?
請勿使用空佈局管理器。 – mre
@mre那是唯一的原因?所有其他佈局看起來很不直觀。絕對佈局更容易將事情放在gui中。有沒有辦法使這個絕對佈局的工作? – MattL922
@ MattL922:這不是原因。使用空佈局管理器只是一個非常糟糕的做法。您的GUI在另一臺具有不同設置的機器上看起來很糟糕。學習使用佈局管理器。這是設計外觀良好的GUI的唯一方法。 –