共享没有静态变量的GUI变量

时间:2019-01-21 19:35:37

标签: java user-interface pass-by-reference

当前,我有一个GUI,其中包含一些供用户选择程序运行方式的选项:

//Inside GUI.java, start button has clicked -> send all objects to Main class
private void startButtonClicked(MouseEvent e) {
    Main.setMain(selectedObj.getItemAt(selectedObj.getSelectedIndex()));
    Main.setOwnCar(userName.getText().trim());
    Main.enableNaps(weSleep.isSelected());
    Main.useOwnHouse(useOwnHouse.isSelected());
    if (weSleep.isSelected()) {
        Integer minSleep = (Integer) minVal.getValue();
        Integer maxSleep = (Integer) maxVal.getValue();
        Main.setSleepMinMax(minSleep, maxSleep);
    }
    setVisible(false);
}

单击开始按钮后,我要将所有变量从GUI传递到主类。我知道怎么做的唯一方法是使用getter / setter,但它们必须是静态的:

static void setSleepMinMax(int min, int max) {
    sleepMin = min;
    sleepMax = max;
    Log("Sleeping debug: [min->" + min + "] [max->" + max + "]");
}

//Inside an infinite loop I have this which is at the top
//until the GUI is closed it does not start the rest of the program
if (gui.isVisible()) {
    Log("Waiting for GUI vars");
    return 1000;
}
if (!getOwnCar.isEmpty())
    Log("Using " + ownerCarName);

通常说避免静态变量。如果由于主类始终在运行并且GUI只是可以打开以根据需要更改变量的窗口而无法使用构造函数,那么正确的方法是什么?也许通过引用类似于C ++?

2 个答案:

答案 0 :(得分:0)

设计取决于您自己。您还可以传递对象引用或使用一些标准的设计模式(GOF-单例)。

您还可以查看: Singleton

import java.util.Random;

public class PassVar {
private int mainVar = 0;
private MyObj myobj;
public static void main(String[] args) 
{
    PassVar pv = new PassVar();

    pv.new MyObj(pv);
    System.out.println("value="+pv.mainVar);
    pv.new ChangeValue(pv);
    System.out.println("value="+pv.mainVar);
    pv.new ChangeValue(pv);
    System.out.println("value="+pv.mainVar);

    pv.myobj = pv.new MyObj();
    System.out.println("myobj_i="+pv.myobj.i);
    pv.new MyObj(pv);
    System.out.println("myobj_i="+pv.myobj.i);
    pv.new MyObj(pv);
    System.out.println("myobj_i="+pv.myobj.i);

}
public void setMainVar(int i)
{
    mainVar = i;
}
    class ChangeValue
    {
        ChangeValue(PassVar pv)
        {
            pv.setMainVar(new Random().nextInt() %100);
        }
    }

    class MyObj
    {
        public int i=-1;
        MyObj() {}
        MyObj(PassVar pv)
        {
            i = 10+new Random().nextInt(10);
            pv.myobj = this;
        }

    }
}

输出:

value=0
value=11 (random between -99 ... 99)
value=77

myobj_i=-1
//set obj.ref. in PassVar from MyObj
myobj_i=18 (random between 10 ... 19)
myobj_i=12

答案 1 :(得分:0)

将其写入属性文件并从那里读取。这样,当下一次再次使用它时,他就可以拥有以前的值。