我有以下绘制标签的类。 (我这里只给出了部分代码)。一切正常,标签显示出来。
现在,我有另一个名为 Caller
类的类。我有一个方法,我将用它来更改此标签的值。我该怎么做
public class MyClass{
private JLabel label;
MyClass(){
run();
}
public void editTheLabelsValue (String text) {
label.setText(text);
frame.repaint();
}
run(){
.... // there were more code here, i removed it as it's not relevant to the problem
label = new JLabel("Whooo");
label.setBounds(0, 0, 50, 100);
frame.getContentPane().add(label);
.....
}
稍后,我将使用以下类来更改上述标签的文本。我怎样才能做到这一点。
public class Caller {
void methodA(){
MyClass mc = new MyClass();
mc.editTheLabelsValue("Hello");
}
}
1.) 执行 methodA() 时,文本 Hello
不会显示在 Label 字段上。它仍然保持为 Whooo
。我该如何纠正这个问题。我希望在执行该方法后标签文本为 Hello
。
最佳答案
我看到的直接问题是,您似乎正在使用 null
布局,或者您不了解布局管理器的工作原理。
以下代码通过 setText
方法调用更新子类中主类的标签。该方法每秒调用一次
public class PaintMyLabel {
private int counter = 0;
public static void main(String[] args) {
new PaintMyLabel();
}
public PaintMyLabel() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final MasterPane master = new MasterPane();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(master);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
counter++;
master.setText("Now updated " + counter + " times");
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
});
}
public class MasterPane extends JPanel {
private JLabel label;
public MasterPane() {
label = new JLabel("Original text");
setLayout(new GridBagLayout());
add(label);
}
public void setText(String text) {
label.setText(text);
}
}
}
如果您使用的是 null
布局,请停止它。只是不要。您只会在极少数情况下使用 null
布局,我怀疑这不是其中之一。
关于java - 更改另一个类的 JLabel 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13405928/