When I run this code which should take the text from a JLabel, use a getter method to move it to the button action class, modifiy it and then use a setter method to set it in the original class, it updates the JLabel variable but does not update the GUI.
I have tried repaint(), revalidate(), doLayout() on the label, the frame and the panel that holds the label.
The class that initializes the label:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JButton;
public class Testing4 {
private JFrame frame;
private JLabel lblNewLabel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Testing4 window = new Testing4();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Testing4() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
lblNewLabel = new JLabel("label");
lblNewLabel.setBounds(52, 101, 277, 53);
frame.getContentPane().add(lblNewLabel);
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(114, 28, 156, 53);
frame.getContentPane().add(btnNewButton);
btnNewButton.addActionListener(new ButtonAction());
}
public String getLabelText()
{
return this.lblNewLabel.getText();
}
public void setLabelText(String text)
{
System.out.println(text);
this.lblNewLabel.setText(text);
System.out.println(lblNewLabel.getText());
}
}
If you look at the setLabelText(String) method, it sets the text to the label called lblNewLabel and then it prints out the text to the console in the next line of code. That .getText() shows that the label has been modified, however the GUI does not show that it has been modified.
Here is the code for the button:
public class ButtonAction implements ActionListener
{
Testing4 test;
public void actionPerformed(ActionEvent e)
{
test = new Testing4();
String x = test.getLabelText();
System.out.println(x);
x = x + " hello";
System.out.println(x);
test.setLabelText(x);
}
}
For all intents and purposes, this should update the GUI with the new text, I've done this before and not had an issue but something this time is causing an issue.