I have a GUI screen, and it has a label in it. I now want to set the label with a text as i have shown in below (Test). But it’s not getting updated. I think there’s an error in the follwoing code, where i am recreating a new object of FrameTest in the try block;
FrameTest frame = new FrameTest();
frame.setVisible(true); //(the full code given below)
The Full Code: Note: the following class is extended from JFrame
import java.awt.BorderLayout;
public class FrameTest extends JFrame {
private JPanel contentPane;
private JLabel lblLabel;
public void mainScreen() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrameTest frame = new FrameTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void writeLabel(String k){
this.lblLabel.setText(k);
}
public FrameTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
lblLabel = new JLabel("LABEL");
contentPane.add(lblLabel, BorderLayout.CENTER);
}
}
Test Class
public class Test {
public static void main(String[] args) {
FrameTest f = new FrameTest();
f.mainScreen();
f.writeLabel("FFFFF");
}}
Help, how can i get Text "FFFFF" displayed to the label ?
In your
mainScreen()you create a newFrameTestthat is distinct from the one you create in themainroutine, so it’s actually changing the text, of the invisible frame. Try this instead:Or simply: