My question is about Image not appearing when jlabel is clicked from menu Why does the image does not appear when I click from menu? Please help. Newbie here
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
public class Lab05Part02 extends JFrame implements ActionListener{
JMenuItem b1,b2,b3;
JLabel bankImg;
ImageIcon img1 = new ImageIcon("aib.jpg");
ImageIcon img2 = new ImageIcon("BOI.jpg");
ImageIcon img3 = new ImageIcon("kbc.jpeg");
Lab05Part02(){
JMenuBar mb = new JMenuBar();
JMenu banks = new JMenu("Banks", false);
banks.add(b1 = new JMenuItem("AIB"));
b1.addActionListener(this);
banks.add(b2 = new JMenuItem("Bank of Ireland"));
b2.addActionListener(this);
banks.add(b3 = new JMenuItem("KBC"));
b3.addActionListener(this);
mb.add(banks);
setJMenuBar(mb);
JPanel p = new JPanel();
bankImg = new JLabel();
p.add(bankImg);
getContentPane().add(p);
setSize(500,500);
setVisible(true);
}//end of constructor
public static void main(String[] args){
Lab05Part02 myMenu = new Lab05Part02();
}//end of main method
public void actionPerformed(ActionEvent e){
Object source = new Object();
if(source == b1){
bankImg.setIcon(img1);
}
else if(source == b2){
bankImg.setIcon(img2);
}
else if(source == b3){
bankImg.setIcon(img3);
}
else{
bankImg.setText("Select Image from Menu");
}
}//end of listener method
}//end of class
Where did I go wrong? On else if statements? Can someone explain this to me? I did putting setVisible(true) on every condition but it did not work. Thank you in advance!
In the actionPerformed
method you forgot to get the source object from the ActionEvent e
and you just created a new object:
Object source = new Object();
As it's obvious, in this way source
is not equals to the reference of one of your buttons.
The ActionEvent
object contains the source of event. In order to resolve the issue get the source object from ActionEvent e
argument:
Object source = e.getSource();
If your images ("aib.jpg", "BOI.jpg" and "kbc.jpeg") are in a right path and your ImageIcon img1, img2, img3
objects populated successfully you are good to go with the above fix.
But I can advise that if you want no further inconvenience for showing images and icons in your project, it's better you put them under a package like resources.images
and also create a java class there and name it Resources.java
for example.
Then you can create images using the resource stream of Resources.java
which is in the same package with images and icons:
package resources.images;
import java.net.URL;
import javax.swing.ImageIcon;
public class Resources {
public static ImageIcon getImageIcon(String name) {
URL imagePath = Resources.class.getResource(name);
return new ImageIcon(imagePath);
}
}
Then in your code you can write
ImageIcon img1 = Resources.getImageIcon("aib.jpg");
instead of
ImageIcon img1 = new ImageIcon("aib.jpg");
This way it will work even if you package your application as a jar file.
Hope this helps.