在我的程序中,从第一个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/

10-12 00:35
查看更多