英文:
Update JLabel from another class doesn't work Java Swing
问题
这里有两个类,分别是 PanelEdit 和 Snapshot,这两个类都继承自 jPanel。
在 PanelEdit 类中有一个 jLabel。我想从 Snapshot 类中更新 PanelEdit 类中的这个 jLabel。
我的程序流程是:用户必须先打开 PanelEdit,然后再打开 Snapshot,所以在从 Snapshot 类中的按钮点击后,会更新 PanelEdit 类中的 jLabel。
> 打开 PanelEdit -> 打开 Snapshot -> 用户在 Snapshot 中点击按钮 -> 更新 PanelEdit 中的 jLabel。
我的尝试:
- 在 PanelEdit 类中创建一个设置方法:
public void setLabel(String label){
jLabel1.setText(label);
}
然后在 Snapshot 类中调用这个设置方法:
PanelEdit pe = new PanelEdit();
pe.setLabel("test");
但是我的 PanelEdit 中的 jLabel 并没有更新。
- 在 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 :
- 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
- set public
jLabel
onPanelEdit
, 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.
专注分享java语言的经验与见解,让所有开发者获益!
评论