I am working on a project but the program seems to have a bug that I can not find.
Here is an MCVE which reproduces the problem:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class SO{
JLabel label;
JButton button;
JPanel panel;
JFrame frame;
public static void main(String[] args){
new SO().start();
}
public void start()
{
label = new JLabel("Button not pressed");
button = new JButton("Press me");
frame = new JFrame();
panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
panel.add(label);
panel.add(button);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("Button was pressed");
label = new JLabel("Button is pressed"); //Doesn't work
frame.repaint();
}
});
}
}
The above program has a JLabel with some text and a JButton both of which are added into a JPanel which in turn is added to a JFrame.
When the button is pressed, I want the text in the JLabel to change. But the text doesn't get changed despite the println
executing every time I press the button.
What is the problem here?
You are creating a new object of the
JLabel
on clicking on the button but not adding it to theJPanel
orJFrame
after that.In spite of creating new object i.e.
do something like,
More Info