从另一个类访问GUI组件

hor*_*HAY 1 java user-interface swing

我是Java的新手,而且我遇到了一堵砖墙.我想从另一个类访问GUI组件(在一个类中创建).我正在从一个类创建一个新的GUI类,就像这样;

GUI gui = new GUI();
Run Code Online (Sandbox Code Playgroud)

我可以访问该类中的组件,但是当我去另一个班级时我不能.我真的只需要访问JTextAreas更新他们的内容.有人能指出我正确的方向,任何帮助都非常感谢.

GUI 类:

public class GUI {

    JFrame frame = new JFrame("Server");        
    ...
    JTextArea textAreaClients = new JTextArea(20, 1);  
    JTextArea textAreaEvents = new JTextArea(8, 1);

    public GUI()
    {
        frame.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 3));     
        ...
        frame.setVisible(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*tha 6

首先尊重封装规则.做你的领域private.接下来,getters您需要访问您需要访问的字段.

public class GUI {
    private JTextField field = new JTextField();

    public GUI() {
        // pass this instance of GUI to other class
        SomeListener listener = new SomeListener(GUI.this);
    }

    public JTextField getTextField() {
        return field;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您将要将GUI传递给任何需要访问文本字段的类.说一ActionListener堂课.使用构造函数注入(或"传递引用")来传递GUI类.当你这样做时,它GUI中引用的SomeListener是相同的,你不会创建一个新的(它不会引用你需要的同一个实例).

public class SomeListener implements ActionListener {
    private GUI gui;
    private JTextField field;

    public SomeListener(GUI gui) {
        this.gui = gui;
        this.field = gui.getTextField();
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然上述可能的工作,它可能是unnecesary.首先考虑一下你想要对文本字段做什么.如果某些操作可以在GUI类中执行,但您只需要访问类中的某些内容来执行它,那么您可以interface使用需要执行某些操作的方法来实现.像这样的东西

public interface Performable {
    public void someMethod();
}

public class GUI implements Performable {
    private JTextField field = ..

    public GUI() {
        SomeListener listener = new SomeListener(GUI.this);
    }

    @Override
    public void someMethod() {
         field.setText("Hello");
    }
}

public class SomeListener implements ActionListener {
    private Performable perf;

    public SomeListener(Performable perf) {
        this.perf = perf;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        perf.someMethod();
    }
}
Run Code Online (Sandbox Code Playgroud)