从一个Java类获取变量到GUI形式Java类JLabel

时间:2014-05-30 09:58:09

标签: java swing class user-interface

如果我在DisplayForm.java GUI中按下connectBtn,我想在DisplayForm.java GUI中获取device connected: true JLabel,但我无法获得变量String connected =" true" ;当我在DisplayForm.java中按connectBtn时,从ArduinoDisplay.java到DisplayForm.java connectedDevice JLabel。

ArduinoDisplay.java的一部分

    String connected = "";

    public void initialize() {
    if (portId == null) {
        System.out.println("Could not find COM port.");
        connected = "False";
        System.out.println("CONNECTED: " + connected + " PORT: " + devCom);
        return;
        } else if( portId != null) {
        connected = "True";
        System.out.println("CONNECTED: " + connected + " PORT: " + devCom);
        } else {
        connected = "False";
        System.out.println("CONNECTED: " + connected + " PORT: " + devCom);
    }
}

public static void main(String[] args) throws Exception {
    ArduinoDisplay main = new ArduinoDisplay();
    main.initialize();


    // Start GUI
    DisplayForm gui = new DisplayForm();
    gui.setVisible(true);
}

DisplayForm.java的一部分

private void connectBtnActionPerformed(java.awt.event.ActionEvent evt) {
    ArduinoDisplay ad = new ArduinoDisplay();
    String devCon = ad.connected;
    deviceConnected.setText(devCon);
}

如果需要更多代码,请告诉我,谢谢

1 个答案:

答案 0 :(得分:1)

将连接变量放在任何方法之外,不允许直接访问它(使用getter方法)

public class ArduinoDisplay {
    private String connected = "false":


public String getConnected (){
    return this.connected;
}
....
}

并且这样:

private void connectBtnActionPerformed(java.awt.event.ActionEvent evt) {
    ArduinoDisplay ad = new ArduinoDisplay();
    String devCon = ad.getConnected();
    deviceConnected.setText(devCon);
}

Side Note :尝试使用boolean而不是String。如果你需要几种状态,可以选择Enum。它可以节省您的时间并消除开发人员的错误