运行时,Swing JFrame GUI窗口为空

时间:2018-10-06 14:37:55

标签: java swing user-interface netbeans jframe

我已经使用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);
    }

}

该窗口应如下所示: NetBeans screenshot

编辑: 其他文件代码:

public class HiLoJFrame extends javax.swing.JFrame {    
    /**
     * Creates new form HiLoJFrame
     */
    public HiLoJFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        titleLabel = new javax.swing.JLabel();
        chooseLabel = new javax.swing.JLabel();
        txtGuess = new javax.swing.JTextField();
        guessButton = new javax.swing.JButton();
        outputLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setName("HiLoGame"); // NOI18N

        titleLabel.setFont(new java.awt.Font("SansSerif", 1, 24)); // NOI18N
        titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        titleLabel.setText("High/Lower Game");
        titleLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);

        chooseLabel.setFont(new java.awt.Font("SansSerif", 0, 15)); // NOI18N
        chooseLabel.setText("Guess a name between 1 to 100");

        txtGuess.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtGuessActionPerformed(evt);
            }
        });

        guessButton.setFont(new java.awt.Font("Ubuntu", 0, 18)); // NOI18N
        guessButton.setText("Guess");
        guessButton.setCursor(new java.awt.Cursor(java.awt.Cursor.MOVE_CURSOR));
        guessButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guessButtonActionPerformed(evt);
            }
        });

        outputLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        outputLabel.setText("Enter a number and press Guess");
        outputLabel.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap(50, Short.MAX_VALUE)
                        .addComponent(chooseLabel)
                        .addGap(18, 18, 18)
                        .addComponent(txtGuess, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(136, 136, 136)
                                .addComponent(guessButton, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(78, 78, 78)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(titleLabel)
                                    .addComponent(outputLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(titleLabel)
                .addGap(75, 75, 75)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txtGuess, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(chooseLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
                .addComponent(guessButton, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(53, 53, 53)
                .addComponent(outputLabel)
                .addGap(35, 35, 35))
        );

        titleLabel.getAccessibleContext().setAccessibleDescription("");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 422, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 346, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap()))
        );

        getAccessibleContext().setAccessibleName("HiLoGame");

        pack();
    }// </editor-fold>                        

    private void txtGuessActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void guessButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
        HiLoGUI hilogui = new HiLoGUI();
        hilogui.checkGuess();
    }                                           

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> {
            new HiLoJFrame().setVisible(true);
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel chooseLabel;
    private javax.swing.JButton guessButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel outputLabel;
    private javax.swing.JLabel titleLabel;
    private javax.swing.JTextField txtGuess;
    // End of variables declaration                   
}

EDIT2: 我已经更改了HiLoGUI.java的主类。
我创建了错误的对象。 新主:

public static void main(String[] args) {
        HiLoJFrame theGame = new HiLoJFrame();
        theGame.newGame();
        theGame.setSize(new Dimension(450,300));
        theGame.setVisible(true);
    }

现在,它声称我需要在 JFrame 文件中创建该方法(newGame)。

2 个答案:

答案 0 :(得分:0)

根据Swing文档,您从错误的类调用方法,不需要创建新的JFrame对象,因此设置其可见性就足够了。检查一下:How To Call JFrame from another Java class

答案 1 :(得分:-2)

您创建了两个变量来存储标签,并且文本字段没有初始化它们,也没有将它们添加到框架中,也没有设置标签和字段的宽度,高度和位置。

因此,您需要先对其进行初始化。可能在newGame函数中。

outputLabel = new JLabel();
txtGuess = new JTextfield();

然后设置这些参数。

outputLabel.setBounds(10,20,50,100);
txtGuess.setBounds(10,80,50,100);
//Or with other values.

然后添加到框架中。

theGame.addImpl(outputLabel, null, 0);
theGame.addImpl(txtGuess, null, 0);

但是我不确定这最后一部分。 请先阅读Java文档。

编辑:好的,我看到您已经通过GUI添加了它们。那时我的回答无济于事。