我尝试在使用BoxLayout格式化的JPanel中放置一个简单的图标。
JPanel panel_4 = new JPanel();
contentPane.add(panel_4, BorderLayout.CENTER);
panel_4.setLayout(new BoxLayout(panel_4, BoxLayout.X_AXIS));
ImageIcon seven= new ImageIcon("C:\\Users\\alewe\\workspace\\SlotMachine\\Lucky_Seven-128.png");
JLabel lblNewLabel_1 = new JLabel(seven);
panel_4.add(lblNewLabel_1);
当我运行代码时,它给了我错误“Some characters cannot be mapped using "Cp1252" character encoding
”,我保存了UTF-8
,现在它启动但我看不到图标。
答案 0 :(得分:1)
也许如果你使用setIcon
会帮助你:
ImageIcon seven= new ImageIcon("C:\\Users\\alewe\\workspace\\SlotMachine\\Lucky_Seven-128.png");
JLabel lblNewLabel_1 = new JLabel();
//Set your icon to your label
lblNewLabel_1.setIcon(seven);
panel_4.add(lblNewLabel_1);
您可以阅读有关图标here
的更多信息答案 1 :(得分:0)
你需要一个输入流来读取图片。像这样使用它:
File f = new File("filepath");
InputStream in=new FileInputStream(f);
if (in != null) {
ImageIcon imageIcon = new ImageIcon(ImageIO.read(in));
label.setIcon(imageIcon);
} else {
LOG.debug("No icon found...");
}