在应用程序中显示控制台日志

时间:2021-07-25 08:58:31

标签: java swing console jframe jbutton

我刚刚创建了一个简单的逻辑,它生成一个 1 到 100 之间的数字。如果是偶数,它会打印出“Heads”,如果是奇数,它会在控制台中打印出“Tails”。

>

然后我还使用 JbuttonJframe 添加了一个按钮。当我执行代码时,我在单独的窗口应用程序中得到了一个开始游戏按钮,但是如何让游戏逻辑显示在窗口应用程序中而不是在控制台中?

想象一下,当我执行代码时,会弹出一个带有“开始游戏”按钮的小窗口,我必须将该窗口向右拖动,然后单击它,游戏逻辑开始在控制台中(我有查看我的 IDE 以了解打印出来的内容)。

游戏逻辑代码:

package com.headOrTails;

import java.util.*;

public class GameLogic {
    public void gameLogicFunction() { // Generate random number and if it is an odd number prints head, else tails

        Scanner input = new Scanner(System.in);
        long randomNumber = (int)(Math.random() * 100);

        boolean isPlaying = true;
        String userContinue;

        do{

            if (randomNumber % 2 == 0) {
                System.out.println("Heads");
                System.out.println("And btw the number was " + randomNumber);

            } else {
                System.out.println("Tails");
                System.out.println("And btw the number was " + randomNumber);
            }

            System.out.println("Do you want to conitnue? y or n");
            userContinue = input.next();

        } while (userContinue.equals("y") || userContinue.equals("Y"));
    }
}

出现的框架的代码是:

package com.headOrTails;

import javax.swing.*;

public class MyFrame extends JFrame {

    // init game logic class
    GameLogic game1 = new GameLogic();

    MyFrame() {

        // Init button and design it
        JButton button = new JButton(); // init button
        button.setBounds(200,100,100,50);
        button.addActionListener(e -> game1.gameLogicFunction()); // use lambda expression to run game logic
        button.setText("Start game");

        // create and size the application window
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(null);
        this.setSize(500,500);
        this.setVisible(true);
        this.add(button);
    }
}

0 个答案:

没有答案