我有一個JPanel名稱「imagePanel」和一個按鈕名稱「browseBtn」。全部包含在JFrame類中。當按下browseBtn時,文件選擇器將打開,選擇一個PNG圖像文件後,圖像將直接出現在imagePanel中。圖像未加載JPanel
這是browseBtn
private void browseBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon image = new ImageIcon(file.getPath());
JLabel l = new JLabel(image);
imagePanel.add(l);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error reading file !");
}
}
else {
JOptionPane.showMessageDialog(this, "Choose png file only !");
}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
我必須選擇正確的PNG文件的操作事件,但我不明白爲什麼圖像沒有在imagePanel露面。你能解釋一下嗎? 乾杯。
1)對於初學者來說,'新的ImageIcon(file.getPath());'應該最好是'新的ImageIcon(文件);'2)Dynamicall添加成分是棘手。我建議在啓動時添加'JLabel',然後簡單地調用'l.setIcon(..)'。 –
,但它會拋出一個錯誤:「使用ImageIcon(文件) –
D'Oh時發現沒有適合ImageIcon(File)的構造函數」!我的(和甲骨文的)不好。當某些東西應該代表一個'File'路徑時,他們***應該提供'File'的構造函數(該死!)。 –