在我的程序中,从第一个JFrame(GUI)中单击一个按钮(标记为“更改模板”),该按钮将打开第二个JFrame(TempList)。
还有一个模板类。
public class Template {
private String name;
public Template(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
name = this.name;
}
GUI类
public class GUI extends javax.swing.JFrame {
private static TempList FrameB = null;
private Template template = new Template("image1");
public GUI() {
initComponents();
}
private void ChangeTemplateActionPerformed(java.awt.event.ActionEvent evt) {
if (FrameB == null) {
FrameB = new TempList();
} else {
if (FrameB.isVisible()) {
FrameB.hide();
} else {
FrameB.show();
}
}
}
从TempList,您应该能够单击一个按钮,该按钮更改在GUI中创建的Template对象的名称。
我应该在TempList类中编写什么代码,以便在按下按钮时更改GUI类中Template对象的名称?
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// Change Template?
this.setVisible(false); //closes Templist
}
最佳答案
您需要在模板上调用setName(...)
。因此,您需要引用要更改其名称的Template
实例。如果没有此引用,则需要将其与方法或构造函数等一起传递。
一个不错的选择(取决于您的总体结构)可能是在构造TempList
时通过它。因此,更改您的TempList
构造函数并添加一个Template
参数,如下所示:
public class TempList {
// Member variable to memorize the template for later use
private Template mTemplate;
// Constructor with Template argument
public class TempList(Template template) {
this.mTemplate = template;
}
// Other stuff of TempList
...
}
然后,您可以在
TempList
中的方法中使用该引用,如下所示:private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// Change the name
mTemplate.setName("New Name");
this.setVisible(false); //closes Templist
}
当然,您现在还需要在创建
TempList
时传递引用,请查看以下代码段:private void ChangeTemplateActionPerformed(java.awt.event.ActionEvent evt) {
if (FrameB == null){
// We need to also pass the reference to Template now by using the newly created constructor
FrameB = new TempList(template);
} else {
if (FrameB.isVisible()){
FrameB.hide();
} else {
FrameB.show();
}
}
}
现在,您的
TempList
知道了Template
,将其存储在mTemplate
内,并在jButton2ActionPerformed
方法中使用了它。关于java - 从另一个类编辑对象?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45265086/