Wajih Ahmed
Wajih Ahmed

Reputation: 99

Need to display image when user click clickme button

I need to display image in label when the user click the button.I have written some code in ActionListener but its not working

        btnNewButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            ImageIcon one = new ImageIcon("E:\\image1.jpg");
            panel_1.setLocation(20, 100);
            panel_1.setSize(115, 115);
            mbutton.setIcon(one);
            panel_1.add(mbutton);
            // mbutton.setText("You changed me");
        }
    });

Upvotes: 2

Views: 698

Answers (1)

David Kroukamp
David Kroukamp

Reputation: 36423

Im a bit confused as to your code you talk of adding an image to a JLabel but the code shows you adding a variable mButton and setting its icon, which makes me think its JButton?

Either way is the JLabel/JButton already added to the container or is it being added dynamically too?

1) If JLabel/JButton is not already present on visible container:

After adding/removing or changing size/Layout of components on a visible container, you should call revalidate() and repaint() on containers instance as to reflect the changes:

//code which adds component to visible panel_1

//so changes can be reflected
panel_1.revalidate();
panel_1.repaint();

2) If JLabel/JButton is visible setIcon should work as it calls revalidate() and repaint() itself as seen here from JLabel#setIcon (JButton is the same):

     * 108: getfield      #294                // Field defaultIcon:Ljavax/swing/Icon;
     * 111: invokeinterface #346,  1          // InterfaceMethod javax/swing/Icon.getIconHeight:()I
     * 116: aload_2
     * 117: invokeinterface #346,  1          // InterfaceMethod javax/swing/Icon.getIconHeight:()I
     * 122: if_icmpeq     129
     * 125: aload_0
     * 126: invokevirtual #319                // Method revalidate:()V
     * 129: aload_0
     * 130: invokevirtual #318                // Method repaint:()V

thus something else is at fault like your LayoutManager not correctly supporting the addition of the new component and thus it doesnt get placed in a visible space, please post an SSCCE.

Also I see you are using setSize(..) and setLocation(..) so I get the feeling you are using the Absolute/null LayoutManager this is not recommend and can cause many problems. Rather use an appropriate LayoutManager see here for more:

Upvotes: 4

Related Questions