1
\$\begingroup\$

I have implemented a "Guess number game" using Swing. The idea is that the user enters a range and the program makes guesses of the number.

This is the first time I'm implementing this kind of application. If there are any improvements I should make to the code let me know. I will be grateful for any suggestions.

public class GuessNumberGame extends JFrame {
    private int minValue = 0;
    private int maxValue = 1;
    private int fail = 0;
    private int i = 0;

    private boolean isGameStart = true;

    public GuessNumberGame() {
        initComponents();
        initComboBox();
        fail = (maxValue-minValue)/2 + 1;
        nextValue();
    }

    private void nextValue(){
        numberLabel.setText("Is your secret number\n " + (minValue+maxValue)/2 + " ?");
    }

    private void initComboBox(){
        styleComboBox.addItem("Metal");
        styleComboBox.addItem("Nimbus");
    }

    private void styleComboBoxActionPerformed(ActionEvent e) {
        String style = (String) styleComboBox.getSelectedItem();
        switch (style){
            case "Metal":
                try {
                    UIManager.setLookAndFeel(new MetalLookAndFeel());
                    SwingUtilities.updateComponentTreeUI(this);
                } catch (UnsupportedLookAndFeelException e1) {
                    e1.printStackTrace();
                }
                break;
            case "Nimbus":
                try {
                    UIManager.setLookAndFeel(new NimbusLookAndFeel());
                    SwingUtilities.updateComponentTreeUI(this);
                } catch (UnsupportedLookAndFeelException e1) {
                    e1.printStackTrace();
                }
                break;
        }
    }

    private void moreButtonMouseClicked(MouseEvent e) {
        if(isGameStart) {
            ++i;
            fail();
            minValue = (minValue + maxValue) / 2 + 1;
            nextValue();
        }
    }

    private void lessButtonMouseClicked(MouseEvent e) {
        if (isGameStart) {
            ++i;
            fail();
            maxValue = (minValue + maxValue) / 2;
            nextValue();
        }
    }

    private void endButtonMouseClicked(MouseEvent e) {
        if (isGameStart) {
            endLabel.setText("Good Guess!");
            isGameStart = false;
            i = 0;
        }
    }

    private void updateButtonMouseClicked(MouseEvent e) {
        try {
            minValue = Integer.parseInt(minTextField.getText());
            maxValue = Integer.parseInt(maxTextField.getText());
            if (maxValue < minValue) {
                int v = maxValue;
                maxValue = minValue;
                minValue = v;
            }
            errorLabel.setText("");
            isGameStart = true;
            nextValue();
            endLabel.setText("");
            fail = (maxValue-minValue)/2 + 1;
        } catch (NumberFormatException err) {
            errorLabel.setText("You did something wrong....!");
            isGameStart = false;
        }
    }

    private void fail() {
        if (i > fail) {
            endLabel.setText("Strange move...");
            i = 0;
            isGameStart = false;
        }
    }

private void initComponents() {
    // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
    styleComboBox = new JComboBox();
    endButton = new JButton();
    lessButton = new JButton();
    moreButton = new JButton();
    fromLabel = new JLabel();
    toLabel = new JLabel();
    updateButton = new JButton();
    numberLabel = new JLabel();
    header = new JLabel();
    endLabel = new JLabel();
    minTextField = new JTextField();
    maxTextField = new JTextField();
    errorLabel = new JLabel();
    label6 = new JLabel();

    //======== this ========
    setResizable(false);
    Container contentPane = getContentPane();
    contentPane.setLayout(null);

    //---- styleComboBox ----
    styleComboBox.addActionListener(e -> styleComboBoxActionPerformed(e));
    contentPane.add(styleComboBox);
    styleComboBox.setBounds(355, 20, 125, 20);

    //---- endButton ----
    endButton.setText("MY NUMBER!!");
    endButton.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            endButtonMouseClicked(e);
        }
    });
    contentPane.add(endButton);
    endButton.setBounds(300, 175, 110, 40);

    //---- lessButton ----
    lessButton.setText("LESS");
    lessButton.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            lessButtonMouseClicked(e);
        }
    });
    contentPane.add(lessButton);
    lessButton.setBounds(90, 175, 90, 40);

    //---- moreButton ----
    moreButton.setText("MORE");
    moreButton.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            moreButtonMouseClicked(e);
        }
    });
    contentPane.add(moreButton);
    moreButton.setBounds(200, 175, 90, 40);

    //---- fromLabel ----
    fromLabel.setText("From");
    contentPane.add(fromLabel);
    fromLabel.setBounds(10, 60, 30, fromLabel.getPreferredSize().height);

    //---- toLabel ----
    toLabel.setText("To");
    contentPane.add(toLabel);
    toLabel.setBounds(15, 100, 30, toLabel.getPreferredSize().height);

    //---- updateButton ----
    updateButton.setText("START OVER!");
    updateButton.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            updateButtonMouseClicked(e);
        }
    });
    contentPane.add(updateButton);
    updateButton.setBounds(360, 270, 125, 40);

    //---- numberLabel ----
    numberLabel.setHorizontalAlignment(SwingConstants.CENTER);
    contentPane.add(numberLabel);
    numberLabel.setBounds(130, 115, 225, 45);

    //---- header ----
    header.setText("GUESS NUMBER GAME!");
    header.setHorizontalAlignment(SwingConstants.CENTER);
    contentPane.add(header);
    header.setBounds(135, 20, 215, 30);

    //---- endLabel ----
    endLabel.setHorizontalAlignment(SwingConstants.LEFT);
    endLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 20));
    contentPane.add(endLabel);
    endLabel.setBounds(175, 275, 160, 25);
    contentPane.add(minTextField);
    minTextField.setBounds(50, 55, 50, 25);
    contentPane.add(maxTextField);
    maxTextField.setBounds(50, 95, 50, 25);
    contentPane.add(errorLabel);
    errorLabel.setBounds(10, 285, 190, 25);
    contentPane.add(label6);
    label6.setBounds(320, 120, 65, 0);

    contentPane.setPreferredSize(new Dimension(515, 350));
    pack();
    setLocationRelativeTo(getOwner());
    // JFormDesigner - End of component initialization  //GEN-END:initComponents
}
\$\endgroup\$
1
\$\begingroup\$
  • private int i = 0;: This needs a better name.
  • fail: This, too. Fail means what? Is it a counter?
  • isGameStart: Better: gameStarted, the is-prefix is usually used for method getters for boolean variables, but isGameStarted isn't that bad as variable name
  • method styleComboBoxActionPerformed: I don't like the name. You already have initComboBox, initComponents, the styleComboBox doesn't really fit in.
  • method styleComboBoxActionPerformed: The "Metal" and "Nimbus" Strings are used more than once, so it's usually a good idea to extract those to a constant. That way you can avoid, that it's changed at one place and forgotton at the other place. Better would be to use an enum anyway.
  • method styleComboBoxActionPerformed: There's code duplication (setLookAndFeel, updateComponentTreeUI, catch block), you can actually declare a LookAndFeel variable and assign it your switch case.
  • moreButtonMouseClicked and lessButtonMouseClicked has a lot of duplicated code too, the only difference is setting the maxValue/minValue. You can actually set those values, and call a new method from both existing methods which do the rest.
  • fail method: Fail what?

Other than that, the code is quite straightforward, the "stuff, which has to be done" is separated into subroutines.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.