Reputation: 1234
I have a big JLabel with a picture, where I'd like as soon as the user enters the mouse on it, to lose its image and others small pictures to appear in it, close to each other. Like a family tree, where the main image is a tree, and when mouse is entered, small pics of plebs appear next to each other, like the pic below. I use:
JLabel c = new JLabel();
c.setBorder(new EtchedBorder(EtchedBorder.RAISED));
c.setIcon(new ImageIcon("C:\\Users\\Lud\\Desktop\\family\\tree.png"));
c.setBackground(new Color(192, 192, 192));
c.setOpaque(true);
c.setBounds(5, 5, 256, 256);
c.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
c.setIcon(null);
JLabel c1 = new JLabel();
c1.setIcon(new ImageIcon("C:\\Users\\Lud\\Desktop\\family\\george.png"));
c1.setBounds(10, 10, 32, 32);
add(c1);
}
public void mouseExited(MouseEvent me) {
}
});
add(c);
The main JLabel/tree image appears just fine but when I enter the mouse on it, it just loses its picutes without displaying the new one above it. What do I do wrong? Thanks
Upvotes: 0
Views: 45
Reputation: 285403
Don't create a new JLabel, but rather simply set the Icon on the existing JLabel.
As a side recommendation, please understand that while null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
Upvotes: 2