javanoob javanoob - 4 months ago 8
Java Question

Adding ImageIcon to already visible GUI on button click

I'm a bit confused as to why my program isn't working. I am trying to add a image to the frame when I click the button. I have verified in java that the file exists and it can find the photo. I have also verified that the button works. But when I compile and click the button it does nothing at all...if someone could guide me in the correct direction it would be much appreciated.

package gamePractice;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class window {

public static void main(String[] args){
JFrame frame = new JFrame("ex");

JPanel panel = new JPanel();
JButton button = new JButton();
button.setText("Press Me");

panel.add(button);
frame.add(panel);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button) {
ImageIcon img = new ImageIcon(getClass().getResource("t.jpg"));
JLabel stickLabel = new JLabel("yes", img, SwingConstants.CENTER);
JPanel panel2 = new JPanel();
panel2.add(stickLabel);
frame.add(panel2);
}
}
});
}
}

Answer

You are adding Components to an already visible container - you need to call let the LayoutManager know about the change by calling revalidate followed by repaint

panel2.add(stickLabel);
frame.add(panel2);
panel2.revalidate();
panel2.repaint();