猿问

运行时 Swing JFrame GUI 窗口为空

我使用 Swing 库构建了一个更高/更低的游戏。当我运行代码时,我没有收到任何错误或警告。当我尝试运行代码时出现问题,窗口是空的,而不是它应该的样子。我使用 NetBeans 进行编程。我的项目中有 2 个不同的文件,这是代码...


HiLoGUI.java:


import java.awt.Dimension;

import javax.swing.*;


public class HiLoGUI extends JFrame {

    private JTextField txtGuess;

    private JLabel outputLabel;

    private int theNumber;


    public void newGame() {

        theNumber = (int)(Math.random() * 100 + 1);

    }


    public void checkGuess() {

        String guessText = txtGuess.getText();

        String message = "";

        int guess = Integer.parseInt(guessText);


        if (guess < theNumber) {

            message = guess + " is too low. Try again.";

        }

        else if (guess > theNumber) {

            message = guess + " is too high. Try again.";

        }

        else {

            message = guess + " is correct. You win!";

        }

        outputLabel.setText(message);

    } 


    public static void main(String[] args) {

        HiLoGUI theGame = new HiLoGUI();

        theGame.newGame();

        theGame.setSize(new Dimension(450,300));

        theGame.setVisible(true);

    }


}


largeQ
浏览 269回答 1
1回答

守候你守候我

您正在从错误的类中调用方法,根据 Swing 文档,不需要创建新的 JFrame 对象,因此设置其可见性就足够了。
随时随地看视频慕课网APP

相关分类

Java
我要回答