更新来自另一个类的JLabel在Java Swing中不起作用。

huangapple 未分类评论48阅读模式
英文:

Update JLabel from another class doesn't work Java Swing

问题

这里有两个类,分别是 PanelEditSnapshot,这两个类都继承自 jPanel。

PanelEdit 类中有一个 jLabel。我想从 Snapshot 类中更新 PanelEdit 类中的这个 jLabel

我的程序流程是:用户必须先打开 PanelEdit,然后再打开 Snapshot,所以在从 Snapshot 类中的按钮点击后,会更新 PanelEdit 类中的 jLabel

> 打开 PanelEdit -> 打开 Snapshot -> 用户在 Snapshot 中点击按钮 -> 更新 PanelEdit 中的 jLabel

我的尝试:

  1. PanelEdit 类中创建一个设置方法:
public void setLabel(String label){
    jLabel1.setText(label);
}

然后在 Snapshot 类中调用这个设置方法:

PanelEdit pe = new PanelEdit();
pe.setLabel("test");

但是我的 PanelEdit 中的 jLabel 并没有更新。

  1. PanelEdit 类中将 jLabel 设置为公共的,这样 Snapshot 类可以直接访问它:
PanelEdit pe = new PanelEdit();
pe.jLabel1.setText("test");

但是仍然没有更新。

有人能帮我解决这个问题吗?

英文:

Here I have two classes there are PanelEdit and Snapshot which the classes extends jPanel

there is a jLabel on class PanelEdit. I want to update the JLabel on class PanelEdit from Snapshot class

my program flow : user have to open PanelEdit before open Snapshot, so after hit a button from Snapshot class, then would be update jLabel on PanelEdit.

> open PanelEdit -> Open Snapshot -> user hit button on Snapshot -> update jLabel on PanelEdit

My attempts are :

  1. create method setter on PanelEdit :
public void setLabel(String label){
    jLabel1.setText(label);
}

then on Snapshot hit the setter method :

 PanelEdit pe = new PanelEdit();
 pe.setLabel("test");

but my jLabel on PanelEdit doesn't update

  1. set public jLabel on PanelEdit, so Snapshot could access it directly
PanelEdit pe = new PanelEdit();
pe.jLabel1.setText("test");

and still doesn't update,

anyone can help me out ?

答案1

得分: 0

这是一个简单的示例。

PanelEdit a = new PanelEdit();
PanelEdit b = new PanelEdit();

a.setLabel("what");
b.setLabel("else");

在这个示例中,a.jLabel1 的文本将是 "what",b.jLabel1 的文本将是 "else"。

在构建界面时,您需要对创建的 PanelEdit 进行引用。

英文:

Here is a small example.

PanelEdit a = new PanelEdit();
PanelEdit b = new PanelEdit();

a.setLabel("what");
b.setLabel("else");

In this example, a.jLabel1 will have the text "what". b.jLabel1 will have the text "else".

You need a reference to the PanelEdit you created when you built your gui.

huangapple
  • 本文由 发表于 2020年7月23日 15:34:09
  • 转载请务必保留本文链接:https://java.coder-hub.com/63049109.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定