问题
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);
}
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);
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++?
回答1:
The design it's up to your side. You could pass also the object reference or use some standard design patterns (GOF - singleton).
You could look also at: 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;
}
}
}
Output:
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
回答2:
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.
来源:https://stackoverflow.com/questions/54296709/sharing-gui-variables-without-static-variables