简体   繁体   中英

Best way to pass variables between classes?

private boolean shouldBank;
private boolean started;
private long startTime;
private String areaChoice;

private FishingArea fishingArea;

public Fishing (Main s) {
    this.s = s;
}

public void onStart() {
    FishingMenu menu = new FishingMenu();
    menu.setVisible(true);

    started = true;
    startTime = System.currentTimeMillis();//Gets time in milliseconds and stores it in a variable.

    if(menu.exit) {
        s.log("Script aborted. Exiting.");
        s.stop(false);
    }

    shouldBank = menu.shouldBank;
    fishingArea = menu.fishingArea;
    areaChoice = menu.areaChoice;
}

Relevant FishingMenu code:

btnStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {                
            fishingArea = fishingAreas[cmbArea.getSelectedIndex()];
            areaChoice = cmbArea.getSelectedItem().toString();

            shouldBank = chkBank.isSelected();

            exit = false;
            dispose();
        }
    });

I have FishingMenu where the user selects their options and those options are used throughout the first class. The way I am handling it right now is to set all the relevant variables in the menu class to public and then create variables in the main class and set them equal to those from the menu as you can see at the bottom of onStart(). I know this is a pretty bad way of doing this but I'm not sure of a better way of doing it. I'm also not sure if giving those top 4 variables in the first class (shouldBank, started, ...etc) class scope like that is correct but I use them throughout the class and again, I don't know a better way. Any suggestions for either problem?

I tried doing some Googling but I wasn't really sure how to word the questions.

You can make variables private and use setters to set the values. Further, you can create ValueObjects for your Menu class. Also, I suggest you extract the ActionListener.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM