简体   繁体   English

在类之间传递变量的最佳方法?

[英]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. 我有FishingMenu,用户可以在其中选择他们的选项,并且在整个第一堂课中都会使用这些选项。 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(). 我现在处理的方式是将菜单类中的所有相关变量设置为public,然后在主类中创建变量,并将其设置为等于菜单中的变量,如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. 我也不确定在这样的第一类(shouldBank,started,...等)类作用域中提供前四个变量是否正确,但是我在整个类中都使用它们,而且我不知道有更好的方法。 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. 此外,您可以为Menu类创建ValueObjects。 Also, I suggest you extract the ActionListener. 另外,建议您提取ActionListener。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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