问题
I want to change the text of a JLabel outside of the method I created it in.
I've looked through the other pages on the same topic but I still cannot get it to work. Perhaps I am lacking knowledge of Java to solve this by myself. Would you please help me?
package autumn;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
private JFrame frame;
JLabel TestLabel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Main() {
initialize();
setText();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel TestLabel = new JLabel("");
TestLabel.setBounds(0, 0, 46, 14);
frame.getContentPane().add(TestLabel);
}
void setText() {
TestLabel.setText("Works!");
}
}
回答1:
You have a class field JLabel TestLabel
.
But in the initialize
method you shadow this field by using a local variable with the same name:
JLabel TestLabel = new JLabel("");
so the class field is not initialized and the later call to setText
fails.
Therefore simply write:
TestLabel = new JLabel(""); // assigns to Main.TestLabel
来源:https://stackoverflow.com/questions/33474297/java-changing-the-text-of-jlabel-inside-another-method