问题描述
目前我有一个图形用户界面,可以让用户选择程序应该如何运行:
Currently I have a GUI that has options for the user to select on how the program should run:
//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,但它们必须是静态的:
When the start button is clicked I want to pass all the variables from the GUI into the main class. The only way I knew how to do it was to use getter/setters but they have to be static:
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++ 的引用传递?
Most say avoid static variables. What is the correct way if I am unable to use a constructor because my main class is always running and the GUI is just a window that can be opened to change variables on demand? Perhaps pass by reference similar to C++?
推荐答案
将它写入一个属性文件并从那里读取它.这样下次再次使用它时,他可以拥有以前的值.
Write it to a property file and read it from there.So that when next time one uses it again he can have the previous values.
这篇关于在没有静态变量的情况下共享 GUI 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!