PVB*_*PVB 1 java swing toolbar imagebutton
swing几天以来,我一直在研究开发gui应用程序.
以下代码旨在创建一个带退出按钮的工具栏(包括图像 "exit.png").问题是虽然工具栏显示,但我无法看到图像.该工具栏的位置使用的borderlayout经理在java中.NORTH
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
menubar.add(file);
setJMenuBar(menubar);
JToolBar toolbar = new JToolBar();
toolbar.setFloatable(false);
ImageIcon exit = new ImageIcon("exit.png");
JButton bexit = new JButton(exit);
bexit.setBorder(new EmptyBorder(0, 0, 0, 0));
toolbar.add(bexit);
//Default layout manager for JFrame is BorderLayout Manager
add(toolbar, BorderLayout.NORTH);
Run Code Online (Sandbox Code Playgroud)
代码写在类构造函数中,类扩展了JFrameswing类.
请注意我已导入所需的课程.也没有编译错误.图像保存在创建.class的目录中.显示gui的其他元素没有错误.
请帮我确定问题所在.提前致谢.
小智 5
首先创建您的ImageIcon.
ImageIcon myIcon = createImageIcon("exit.png", "");
Run Code Online (Sandbox Code Playgroud)
以及Oracle网站上的createImageIcon()方法代码:
private ImageIcon createImageIcon(String path, String description) {
URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
然后设置按钮的图标:
bexit.setIcon(myIcon);
Run Code Online (Sandbox Code Playgroud)