我正在嘗試JPanel在我已經在另一個面板中執行過的應用程式中顯示影像。所以我做的第一件事就是使用相同的代碼,但它不起作用!
我收到了這條訊息:
javax.imageio.IIOException: Can't read input file!
一些谷歌搜索也是如此,我從 Youtube 獲得了以下示例:
package MainFrame
import all as required
public class ExImage {
ExImage()
{
try
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JPanel Example");
JPanel panel = new JPanel();
panel.setBounds(50, 50, 250, 250);
BufferedImage image = ImageIO.read(new File("about.png"));
JLabel label = new JLabel(new ImageIcon(image));
panel.add(label);
// main window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add the Jpanel to the main window
frame.add(panel);
frame.setSize(400, 400);
frame.setLayout(null);
frame.pack();
frame.setVisible(true);
}
catch (IOException e) {
e.printStackTrace();
}
}
我復制了它,因為在視頻中效果很好。但令人驚訝的是,當我測驗它時,我得到了同樣的錯誤!當然,路徑是對的,所以我不明白為什么代碼找不到影像。
uj5u.com熱心網友回復:
我使用這樣的代碼 - 請注意我從類路徑加載影像:
public class App extends javax.swing.JFrame {
private final javax.swing.ImageIcon iiFound = new javax.swing.ImageIcon(getClass().getResource("/images/done_outline_FILL0_wght400_GRAD0_opsz48.png"));
...
JLabel myLabel = new JLabel();
myLabel.setIcon(iiFound);
...
有了這個,我可以用一個特定的圖示初始化 UI,但我也可以在運行時替換影像,例如從附加到 JButton 的 ActionListener。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/482343.html
