0

I've built a Higher/Lower game, using the Swing library. When I run the code I don't get any errors or warnings. The problem appears when I try running the code, the window is empty, not the way it should be. I use NetBeans to program.There are 2 different files in my project, here is the code...

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);
    }

}

The window should look like this: NetBeans screenshot

EDIT: The other files code:

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: I've changed the main class of HiLoGUI.java
I was creating a wrong object. New main:

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

Now it claims that I need to create that method (newGame) in the JFrame file.

Alejandro
  • 100
  • 1
  • 10
  • Welcome to SO. You need to initialize the components (`JLabel`, `JTextField`) and **add** them to the container. See some basic swing [tutorials](http://www.java2s.com/Code/Java/Swing-JFC/HelloWorldSwing.htm). – c0der Oct 06 '18 at 14:43
  • Welcome to StackOverflow, Alejandro. Could you please post the code from the other file? – BigKangu Oct 06 '18 at 14:44
  • `HiLoGUI theGame = new HiLoGUI();` - you didn't post the code from your constructor so we have no idea what your code does. `theGame.newGame();` - all that statement does is set the value of the variable. So where do you even create the GUI? – camickr Oct 06 '18 at 14:47
  • You never create the JFrame with the GUI, the HiLoJFrame, in the first program's main method -- which main method do you call? – Hovercraft Full Of Eels Oct 06 '18 at 14:50
  • @HovercraftFullOfEels I edited the code (edit2) but it doesn't work anyways. – Alejandro Oct 06 '18 at 18:23
  • @camickr I edited the code (**edit2**). Thanks for pointing that out. – Alejandro Oct 06 '18 at 18:26
  • @Alejandro, `Now it claims that I need to create that method (newGame) in the JFrame file.` - so then do that. Why are you trying to create two separate classes. If the HiLoFrame contains all the components, then it should probably contain all the logic that manipulates those components. This is the simplest form of design. – camickr Oct 06 '18 at 20:01
  • @camickr I will try to combine both files. Will update the post either it works or not. Thanks! – Alejandro Oct 07 '18 at 00:09

1 Answers1

0

You are calling a method from the wrong class, according to the Swing docs, it is not needed to create a new JFrame object, so setting its visibility is enough. Check this out: How To Call JFrame from another Java class

BigKangu
  • 167
  • 9