从另一个类编辑对象?

时间:2017-07-23 12:26:54

标签: java swing user-interface

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

2 个答案:

答案 0 :(得分:1)

您需要在模板上调用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方法中使用它。

答案 1 :(得分:1)

Zabuza提出的解决方案是有效的。
还可以考虑在Template而不是TempList中创建Gui对象:

public class TempList extends JFrame{

    private Template template;

    public TempList() {

        //todo: JFrame constuction 
        template = new Template("image1");
    }

    public void setTemplateName(String name) {
        template.setName(name);
    }
}

通过Gui

FrameB,setTemplateName("new name");中使用它

p.s坚持Java命名约定。使用frameB