简体   繁体   English

从不同的类访问方法

[英]Accessing method from different class

I'm trying to call a class's void from a different class. 我试图从另一个班级调用一个班级的空白。 The objects work fine, but for some reason its not completing the action. 对象工作正常,但由于某种原因,它没有完成操作。

I'm making a black jack game, and I need some button to appear when the user enters a correct bet. 我正在制作黑杰克游戏,当用户输入正确的赌注时我需要一些按钮才能显示。 Here is what I have: 这是我有的:

 public static void showButtons(Boolean x) { // to show or hide the buttons
            if(x) {
                hitButton.setVisible(true);
                standButton.setVisible(true);
                separator.setVisible(true);
            }
            else {
                hitButton.setVisible(false);
                standButton.setVisible(false);
                separator.setVisible(false);

           }
}

Once the bet is verified as an integer, it passes through this: 一旦下注被验证为整数,它就会通过:

private void bdButtonActionPerformed(java.awt.event.ActionEvent evt) { //bdButton is the bet button
        ...
        if(validBet(s)) {
            bet = Integer.parseInt(s); // parses input string into an int
            System.out.println("bet accepted"); // debug to know if it works this far
            NewRound nr = new NewRound();
            System.out.println("created object");
            nr.newHand(bet);
            //showButtons(true); // this works, it changes the buttons, but only from here
        }
        else {
            ...
        }
    }

Here is the newHand method: 这是newHand方法:

public static void newHand(int bet) {
        System.out.println("In newHand"); // debug
        BlackJack b = new BlackJack();

        b.showButtons(true);
        System.out.println("passed showButtons"); // the code gets to here, but buttons are still not visible
    }

您的newHand方法是静态的,因此应该使用类名调用它。

The method is declared static, so assuming it is a class called TestClass , the way you would call the method looks like this: 该方法被声明为static,因此假设它是一个名为TestClass的类,您调用该方法的方式如下所示:

TestClass.newHand(int bet);

If you want to be able to just call 如果你想能够打电话

newHand(int bet);

in your current class, you would need to use static import, like this: 在当前的类中,您需要使用静态导入,如下所示:

import static your.package.TestClass.newHand;

But I would much prefer having it the first way. 但我更喜欢第一种方式。

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

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