I have been studying swing for developing gui applications since a few days.
The following code aims to create a toolbar with an exit button (including the image “exit.png”). The problem is I am unable to see the image, though the toolbar shows up. The toolbar is positioned NORTH using the borderlayout manager in java.
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);
The code is written inside a class constructor where the class extends the JFrame swing class.
please note that I have imported the required classes. There is no compile error either. the image is saved in the directory where the .class is created. Other elements of the gui are displayed without an error.
Please help me identify the problem. Thanks in advance.
First create your ImageIcon.
And the code for the createImageIcon() method as found on the Oracle website:
And then set the icon of the button with: