I have made a UI that guesses the number that the user is thinking of(0 - 100), and I am wondering if it can be improved(I guess this is simple AI). I tried to shorten it as best I could, but it still seems a bit "fluffed." I would greatly appreciate anyone willing to help me shorten and/or improve it. It has 3 buttons, a "Too High", "Too Low", and "Just Right" button, and the guess is displayed in the center of the window. I have posted an image below also.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class NumberGuesser extends JFrame {
private static final long serialVersionUID = 1L;
private Random rand = new Random();
private int min = 0;
private int max = 100;
private int guess = rand.nextInt(max);
private JLabel guesses;
private Font font = new Font("Times New Roman", Font.BOLD, 30);
public NumberGuesser() {
initGUI();
setTitle("Number Guesser");
pack();
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void initGUI() {
JLabel title = new JLabel(" I Guess Your Number(0-100) ");
title.setFont(font);
title.setHorizontalAlignment(JLabel.CENTER);
title.setBackground(Color.BLACK);
title.setForeground(Color.WHITE);
title.setOpaque(true);
add(title, BorderLayout.NORTH);
guesses = new JLabel(Integer.toString(guess));
guesses.setFont(font);
guesses.setHorizontalAlignment(JLabel.CENTER);
add(guesses, BorderLayout.CENTER);
JPanel buttons = new JPanel();
add(buttons, BorderLayout.SOUTH);
JButton higher = new JButton("Too High");
higher.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
max = guess;
guessAgain(min, max);
}
});
buttons.add(higher);
JButton correct = new JButton("Just Right");
correct.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
guesses.setText("I WIN!");
}
});
buttons.add(correct);
JButton lower = new JButton("Too Low");
lower.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
min = guess;
guessAgain(min, max);
}
});
buttons.add(lower);
}
private void guessAgain(int min, int max) {
guess = min + (int)(Math.random() * ((max - min) + 1));
guesses.setText(Integer.toString(guess));
}
public static void main(String[] args) {
try {
String laf = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(laf);
}
catch (Exception e) {}
EventQueue.invokeLater(new Runnable(){
public void run() {
new NumberGuesser();
}
});
}
}
The output looks like this: