Question

So i'm making a GUI in java. Say I have a Constructor method, say

        public class glmb extends JLabel implements ActionListener {
           public glmb(){
            Container C= getContentPane();
            C.setLayout(null);
                    myLabel.setBounds(0,0,30,30);
                    myLabel.setBounds(30,0,30,30);
            C.add(myLabel);
            C.add(myButt);
            MyButt.addActionListener(this);
                   setSize(400,400);
                   setVisible(true);
           }}

I have a JLabel with an ImageIcon inside the class:

           JLabel myLabel =new JLabel(new ImageIcon("mypic1.jpg"));

A button with an Action Listener, which will make the JLabel myLabel change the picture:

             if(e.getSource()==myButt)
             { myLabel =new JLabel(new ImageIcon("mypic2.jpg")); setSize(50,50);}

How do I make the picture change in the JFrame after I press the button, the button works because the frame changed size(see the setSize(50,50))? Thank You!!! Still new to java here, haha

Was it helpful?

Solution

Instead of using

myLabel =new JLabel(new ImageIcon("mypic2.jpg"));

use

myLabel.setIcon(new ImageIcon("mypic2.jpg"));

if i understand correctly this should work for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top