I got the widow and the buttons into the GUI but for the life of me I can't get anything to output. I am suppose to enter a guess, and from a random number the game generates. It is suppose to tell me if I'm too high, too low or correct. Also, if it is not correct it's supposed to tell me if I am warm or cold. If any one could point me in the right direction on this I would be grateful. I don't know what I'm doing wrong on this. I have researched different topics but with the different ways to solve this problem none match what I was looking for.
Here's the code:
//all necessary imports
public class GuessGame extends JFrame
{
private static final long serialVersionUID = 1L;
private JFrame mainFrame;
private JTextField guessField;
private JLabel message1;
private JLabel message2;
private JLabel message3;
private JLabel message4;
private JLabel guessLabel;
private JLabel tooHigh;
private JLabel tooLow;
private JButton guessButton;
private JButton newGame;
private JButton exitButton;
private int randomNum = 0;
private final int MAX_NUM = 1000;
private final int MIN_NUM = 1;
private int guessCount;
private int lastDistance;
public GuessGame()
{
mainFrame = new JFrame();
guessField = new JTextField(4);
message4 = new JLabel("I have a number between 1 and 1000 -- can you guess my number?") ;
guessLabel = new JLabel("Please Enter Your Guess:");
guessButton = new JButton("Guess");
newGame = new JButton("New Game");
exitButton = new JButton("Exit");
Container c = mainFrame.getContentPane();
c.setLayout(new FlowLayout());
c.setBackground(Color.CYAN);
c.add(message4);
c.add(guessLabel);
c.add(guessField);
c.add(guessButton);
c.add(newGame);
c.add(exitButton);
newGame.setMnemonic('N');
exitButton.setMnemonic('E');
guessButton.setMnemonic('G');
mainFrame.setSize(420, 300);//Sets width and height of Window
mainFrame.setVisible(true);//Allows GUI to be visible
mainFrame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
GuessButtonsHandler gHandler = new GuessButtonsHandler();
guessField.addActionListener(gHandler);
ExitButtonsHandler eHandler = new ExitButtonsHandler();
exitButton.addActionListener(eHandler);
NewGameButtonsHandler nHandler = new NewGameButtonsHandler();
newGame.addActionListener(nHandler);
}
class GuessButtonsHandler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
Random rand = new Random();
int guess = 0;
int currDistance = 0;
boolean correct = false;
guess = Integer.parseInt(guessField.getText());//Converts String to Integer
if(guessCount == 0)
{
lastDistance = MAX_NUM;
}
if(guess >= MIN_NUM && guess <= MAX_NUM)
{
guessCount += 1;
}
if(guess > randomNum)
{
tooHigh.setText("Number To High!!!");
guessCount += 1;
}
else if(guess > randomNum)
{
tooLow.setText("Number To Low!!!");
guessCount += 1;
}
else
{
correct = true;
message2.setText("Correct!!!");
message2.setBackground(Color.GREEN);
guessField.setEditable(false);
}
if(!correct)
{
currDistance = Math.abs(guess - randomNum);
}
if(currDistance <= lastDistance)
{
message3.setText("You are getting warmer!!!");
mainFrame.add(message3).setBackground(Color.RED);
}
else
{
message4.setText("You are getting colder!!!");
mainFrame.add(message4).setBackground(Color.BLUE);
}
lastDistance = currDistance;
randomNum = rand.nextInt(1000) + 1;
}
}
class NewGameButtonsHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Random rand = new Random();
randomNum = rand.nextInt(1000) + 1;
guessCount = 0;
}
}
class ExitButtonsHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
}
public class GuessGameTest {
public static void main(String[] args)
{
new GuessGame();
}
}
You need to:
Add gHandler as a listener to the button too, not only to the text field:
guessField.addActionListener(gHandler);
guessButton.addActionListener(gHandler);
Keeping it in the text field too is a good idea: then the guess can be triggered by pressing enter too, not just clicking the button (this part actually works in your code).
You need to initialize the message labels, and add them somewhere. You have additions commented out, but the initializations are missing.
You don't really need labels for all possible messages. You want to display only a message for too high, too low, or correct guess at a time. Not two or more simultaneously. So one field is enough, just set the correct text.
You have the condition inverted when checking too low numbers.
You generate a new random number after each guess, so the "getting warmer" messages are not very useful. Also you don't need to create a new Random object every time you want a new random number.
Possibly others too, but hopefully these help you forward.
Related
I'm creating a TicTacToe program for a Java project. I'm using swing with a 3x3 panel as the GUI and integrating buttons into each box for the user to click. The problem is, I do not know how to run the WinCondition method (meaning when a user gets 3 in a row). I am not able to call it to the actionPerformed method in the button class, and I don't know where else it would be viable to call.
I have two classes, one is a button class and another is the actual game which creates the panel for the user.
I've tried thinking about where else I could implement it, but I cannot because I do not know another way to execute code when a button is pressed other than the actionPerformed method.
public class TicTacGame extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
JPanel p = new JPanel();
XOButton[] buttons = new XOButton[9];
public TicTacGame() {
super("TicTacToe");
setSize(400,400);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
p.setLayout(new GridLayout(3,3));
for(int i = 0; i < 9; i++) {
buttons[i] = new XOButton();
p.add(buttons[i]);
}
add(p);
setVisible(true);
}
public int winCondition() {
//I have left out the win condition method so this box doesn't get unnecessarily long
}
public static void main(String[] args) {
TicTacGame ttg = new TicTacGame();
}
}
public class XOButton extends JButton implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
ImageIcon X;
ImageIcon O;
//0 is nothing, 1 is X, 2 is O
int value = 0;
public static int turn = 1;
public XOButton() {
X = new ImageIcon(this.getClass().getResource("X.png"));
O = new ImageIcon(this.getClass().getResource("O.png"));
addActionListener(this);
}
public int getValue() {
return this.value;
}
public void actionPerformed(ActionEvent e) {
if(turn >= 5) {
int win = ttg.winCondition();
}
if(turn % 2 == 0) {
value += 2;
turn++;
}
else {
value++;
turn++;
}
value %= 3;
switch(value) {
case 0:
setIcon(null);
break;
case 1:
setIcon(X);
removeActionListener(this);
break;
case 2:
setIcon(O);
removeActionListener(this);
break;
}
}
}
What I expect is that whenever a button is clicked, the winCondition() method is executed to check if a user won or not.
there's a plenty ways to do that one of them
DON'T
create the win method static, so that you can access from any other class. for more info read comments below
1)you can pass a reference from TicTacGame class into XOButton class in the constructor.. so that you've the access to any other function in TicTacGame class
2)you can use interfaces....etc
I am creating a dumb phone (like old traditional phone) and I'm using GUI programming. I need help with dialing the numbers. I don't know how to get the numbers to pop up on the display and stay there, and also use the delete button to delete the numbers that is up on the display too. I will post a youtube link so you can see a sample run.
I am currently stuck on passing the text from the button of each number that should display the number, however it's displaying the text of the button. I also, don't know how to keep the number there when other buttons are pressed without it being reset.
Here is my code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.*;
public class DumbPhone extends JFrame
{
private static final long serialVersionUID = 1L;
private static final int WIDTH = 300;
private static final int HEIGHT = 500;
private static final String CALL_BUTTON_TEXT = "Call";
private static final String TEXT_BUTTON_TEXT = "Text";
private static final String DELETE_BUTTON_TEXT = "Delete";
private static final String CANCEL_BUTTON_TEXT = "Cancel";
private static final String SEND_BUTTON_TEXT = "Send";
private static final String END_BUTTON_TEXT = "End";
private static final String CALLING_DISPLAY_TEXT = "Calling...";
private static final String TEXT_DISPLAY_TEXT = "Enter text...";
private static final String ENTER_NUMBER_TEXT = "Enter a number...";
private JTextArea display;
private JButton topMiddleButton;
private JButton topLeftButton;
private JButton topRightButton;
private JButton[] numberButtons;
private JButton starButton;
private JButton poundButton;
private boolean isNumberMode = true;
private String lastPressed = "";
private int lastCharacterIndex = 0;
private Date lastPressTime;
public DumbPhone()
{
setTitle("Dumb Phone");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createContents();
setVisible(true);
topLeftButton.setEnabled(false);
}
private void createContents()
{
//create JPanel, and JTextArea display
JPanel panel = new JPanel(new GridLayout(5,3));
display = new JTextArea();
display.setPreferredSize(new Dimension(280, 80));
display.setFont(new Font("Helvetica", Font.PLAIN, 32));
display.setLineWrap(true);
display.setEnabled(false);
panel.add(display);
//create JButtons
topLeftButton = new JButton(DELETE_BUTTON_TEXT);
topMiddleButton = new JButton((CALL_BUTTON_TEXT));
topRightButton = new JButton((TEXT_BUTTON_TEXT));
numberButtons = new JButton[10];
numberButtons[1] = new JButton("<html><center>1<br></center></html>");
numberButtons[2] = new JButton("<html><center>2<br>ABC</center></html>");
numberButtons[3] = new JButton("<html><right>3<br>DEF</right></html>");
numberButtons[4] = new JButton("<html><center>4<br>GHI</center></html>");
numberButtons[5] = new JButton("<html><center>5<br>JKL</center></html>");
numberButtons[6] = new JButton("<html><center>6<br>MNO</center></html>");
numberButtons[7] = new JButton("<html><center>7<br>PQRS</center></html>");
numberButtons[8] = new JButton("<html><center>8<br>TUV</center></html>");
numberButtons[9] = new JButton("<html><center>9<br>WXYZ</center></html>");
numberButtons[0] = new JButton("<html><center>0<br>space</center></html>");
poundButton = new JButton("#");
starButton = new JButton("*");
//add JButtons to buttons JPanel
panel.add(topLeftButton);
panel.add(topMiddleButton);
panel.add(topRightButton);
panel.add(numberButtons[1]);
panel.add(numberButtons[2]);
panel.add(numberButtons[3]);
panel.add(numberButtons[4]);
panel.add(numberButtons[5]);
panel.add(numberButtons[6]);
panel.add(numberButtons[7]);
panel.add(numberButtons[8]);
panel.add(numberButtons[9]);
panel.add(starButton);
panel.add(numberButtons[0]);
panel.add(poundButton);
//add Listener instance (inner class) to buttons
topLeftButton.addActionListener(new Listener());
topMiddleButton.addActionListener(new Listener());
topRightButton.addActionListener(new Listener());
//JButton[] array = new JButton[10];
for (int i = 0; i < numberButtons.length; i++)
{
numberButtons[i].addActionListener(new Listener());
numberButtons[i] = new JButton(String.valueOf(i));
}
starButton.addActionListener(new Listener());
poundButton.addActionListener(new Listener());
//add display and buttons to JFrame
setLayout(new BorderLayout());
add(display, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
}
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == topLeftButton)
{
if(lastPressTime == null)
{
display.setText(ENTER_NUMBER_TEXT);
}
else
{
topLeftButton.setEnabled(true);
lastCharacterIndex--;
lastPressed = lastPressTime.toString();
}
}
else if(e.getSource() == topMiddleButton)
{
if(lastPressTime == null || lastCharacterIndex == 0)
{
display.setText(ENTER_NUMBER_TEXT);
}
else
{
display.setText(CALLING_DISPLAY_TEXT);
}
}
else if(e.getSource() == topRightButton)
{
if(lastPressTime == null || lastCharacterIndex == 0)
{
display.setText(TEXT_DISPLAY_TEXT);
}
else
{
display.setText(CALLING_DISPLAY_TEXT);
}
}
else
{
topLeftButton.setEnabled(true);
if (e.getSource() instanceof JButton)
{
//String text = ((JButton) e.getSource()).getText();
display.setText(lastPressed + " f" + numberButtons[lastCharacterIndex].getText());
}
}
Date currentPress = new Date();
long currentTime = currentPress.getTime();
if(lastPressTime != null)
{
//long lastPressTime = lastPressTime.getTime();
//subtract lastPressTime from currentPress time to find amount of time elapsed since last button pressed.
}
lastPressTime = currentPress;
String buttonLetters = ""; // Parse Letter from button (e.g "abc").
//update lastCharacterIndex.
lastCharacterIndex++;
lastCharacterIndex = lastCharacterIndex % buttonLetters.length();
}
}
for example, if I push the button 2, instead of giving me "2", it will give me < html>< center>2ABC < / center >< / html >
Therefore, I need help with
Having the numberButtons, when pushed to show the numbers that were pushed.
Be able to delete those numbers.
Here is the link to the sample run: https://www.youtube.com/watch?v=evmGWlMSqqg&feature=youtu.be
Try starting the video 20 seconds in.
to delete the number, you can use the labelname.setText("")
At a basic level, you simply want to maintain the "numbers" separately from the UI. This commonly known as a "model". The model lives independently of the UI and allows the model to be represented in any number of possible ways based on the needs of the application.
In your case, you could use a linked list, array or some other simple sequential based list, but the easiest is probably to use a StringBuilder, as it provides the functionality you require (append and remove) and can make a String very simply.
So, the first thing you need to do is create an instance of model as an instance level field;
private StringBuilder numbers = new StringBuilder(10);
this will allow the buffer to be accessed any where within the instance of the class.
Then you need to update the model...
else
{
topLeftButton.setEnabled(true);
if (e.getSource() instanceof JButton)
{
String text = numberButtons[lastCharacterIndex].getText();
numbers.append(text);
}
}
To remove the last character you can simply use something like...
if (numbers.length() > 0) {
numbers.deleteCharAt(numbers.length() - 1);
}
Then, when you need to, you update the UI using something like...
display.setText(numbers.toString());
Now, this is just basic concepts, you will need to take the ideas and apply it to your code base
I have been working on this code for a really long time and i just can't seem to figure out my problem. i want to be able to play a list of songs one right after another and i thought i would be able to do that with a simple recursive method that delays the average length of a song, and have it call the next song and play it... However it only plays the very first song and then stops after that and nothing else happens... I have asked countless people to look at this and nobody can help me out.. And no this is not a school project, it is a music player that my mother would like me to use at a party in the next upcoming weekend, so this is like my last ditch effort... Any help with this would be greatly appreciated!!!
private JLabel messageLabel;
private JButton playlist;
private JPanel panel;
BufferedImage image;
AudioStream audioStream1, audioStream2, audioStream3;
//Object[] music = new Object[3];
private final int WINDOW_WIDTH = 800;
private final int WINDOW_HEIGHT = 525;
// File destinationss
private String s1 = "C:\\Users\\Tony\\Desktop\\Java\\NetBeansProjects\\Gui Stuff\\src\\No_Pressure.wav";
private String s2 = "C:\\Users\\Tony\\Desktop\\Java\\NetBeansProjects\\Gui Stuff\\src\\Grateful_Dead_-_Touch_of_Grey.wav";
private String s3 = "C:\\Users\\Tony\\Desktop\\Java\\NetBeansProjects\\Gui Stuff\\src\\Stairway_to_Heaven_Led_Zeppelin_Lyrics.wav";
InputStream in1 = new FileInputStream(s1);
InputStream in2 = new FileInputStream(s2);
InputStream in3 = new FileInputStream(s3);
private ArrayList music;
public JukeBoxWithArrays() throws IOException {
music = new ArrayList();
audioStream1 = new AudioStream(in1);
audioStream2 = new AudioStream(in2);
audioStream3 = new AudioStream(in3);
music.add(audioStream1);
music.add(audioStream2);
music.add(audioStream3);
setTitle("Juke Box Playlist");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
messageLabel = new JLabel("Click the Button to play the playlist");
// Create the Playlist button
playlist = new JButton("Playlist number 1");
// Register the event Listener
playlist.addActionListener(new PlaylistListener());
// Create the panel
panel = new JPanel();
image = ImageIO.read(new File("C:\\Users\\Tony\\Desktop\\Java\\NetBeansProjects\\Gui Stuff\\src\\jukebox2.jpg"));
panel.add(messageLabel);
panel.add(playlist);
panel.add((new JLabel(new ImageIcon(image))));
// Add the panel to the Content Pane
add(panel);
// Display the Window
setVisible(true);
}
private class PlaylistListener implements ActionListener {
int x = 0;
public void actionPerformed(ActionEvent e) {
try {
playMusic(x);
} catch (InterruptedException ex) {
Logger.getLogger(JukeBoxWithArrays.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void playMusic(int x) throws InterruptedException {
if (x > music.size()) {
AudioPlayer.player.stop((InputStream) music.get(x));
} else {
AudioPlayer.player.start((InputStream) music.get(x));
}
Thread.sleep(5 * 60 * 1000); // I believe this is where I am running into my problem
playMusic(x++);
}
}
#SuppressWarnings("restriction")
public static void main(String[] args) throws Exception {
JukeBoxWithArrays jbwa = new JukeBoxWithArrays();
jbwa.pack();
}
}
It seems your code is failing for the same reason this:
private static int x = 0;
public static void main(String[] args) throws ParseException {
int x = 0;
doSomething(x);
doSomething(x);
doSomething(x);
doSomething(x);
doSomething(x);
}
private static void doSomething(int x) {
System.out.println(x++);
}
Outputs this:
0
0
0
0
0
Your Listener has an x field, that your are passing by value between the methods. You should remove the x argument on playMusic(), so everytime it increments x, it would use the object field instead.
program suppose to run "Guess the number" game
after guessing the number correctly , there's an option to start over
Pressing the "playAgainBtn" make the program stuck.
Another issue is after guessing the "guessText" cant be .selectAll
any insight will be welcomed
Tnx.
public class GuessTheNumberGame extends JFrame
{
private int randomNumber;
private boolean correctGuess;
private JLabel startMsg;
private JLabel enterGuessJLabel;
private JButton playAgainBtn;
private JLabel msgToPlayer;
private JTextField guessText;
private int previousGuess; // previous guessed number hot/cold
private int numOfGuess;
private Container container;
public GuessTheNumberGame()
{
container = getContentPane();
startMsg = new JLabel();
enterGuessJLabel = new JLabel();
guessText = new JTextField(10);
guessText.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
int playerGuess = Integer.parseInt(event.getActionCommand());
if ( playerGuess == randomNumber )
{
msgToPlayer.setText("Great ! u guessed in " + numOfGuess + "Guesses");
correctGuess = true;
}
else
{
wrongGuess(playerGuess);
}
}
}
);
msgToPlayer = new JLabel("");
playAgainBtn = new JButton("Play Again");
ButtonHandler buttonHandler = new ButtonHandler();
playAgainBtn.addActionListener(buttonHandler);
setLayout(new FlowLayout());
add(startMsg);
add(enterGuessJLabel);
add(guessText);
add(msgToPlayer);
add(playAgainBtn);
}
protected class ButtonHandler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent event)
{
startGame();
}
}
public void startGame()
{
previousGuess = 1000;
numOfGuess = 1;
correctGuess = false;
Random rand = new Random();
randomNumber = rand.nextInt(1000) + 1;
startMsg.setText( "I have a number between 1 and 1000. can you Guess my Number?" );
playAgainBtn.setVisible( false );
while ( !correctGuess)
{
enterGuessJLabel.setText( "Please enter your " + numOfGuess + " guess: " );
}
playAgainBtn.setVisible(true);
}
private void wrongGuess(int playerGuess)
{
numOfGuess++;
if ( Math.abs(playerGuess - randomNumber) > previousGuess )
container.setBackground( Color.GREEN);
else
container.setBackground( Color.RED);
previousGuess = Math.abs(playerGuess - randomNumber);
if (playerGuess > randomNumber)
msgToPlayer.setText("Too High");
else
msgToPlayer.setText( "Too Low" );
}
}
When you start the application, startGame() runs on the main thread, which is OK. When you press playAgainBtn, it calls startGame() on the AWT Dispatch Thread, thus tying up this thread, prohibiting the AWT from processing events. Try this to free up the AWT Dispatch Thread:
protected class ButtonHandler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent event)
{
new Thread() {
#Override
public final void run() {
startGame();
}
}.start();
}
}
The problem is that your startGame method, called when the button is clicked, has an infinite loop in it.
while ( !correctGuess)
{
enterGuessJLabel.setText( "Please enter your " + numOfGuess + " guess: " );
}
The correctGuess variable will never be changed so your program will just execute the setText command endlessly.
The way Swing (and all GUI frameworks) work is that you must always respond to an event such as a button click and then return control.
So I was trying to understand using a Gui in Java and did so by making a little guess the number game. It compiles correctly, however when I run the program it just shows the frame with "Congratulations you win!" at the top. My main question is why the dialog boxes aren't popping up at all and what I should do to fix that. On a related note, when I had the code as JOptionPane.showInputDialog(this,"Play again? Y/N") I got the error message "non-static variable this cannot be referenced from a static context." My secondary, and much less important question, is how to make the message be in the center of the box vertically as well as horizontally.
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
public class RandomNumberGame{
public static JLabel higherThan;
public static JPanel tooHigh;
public static JLabel lowerThan;
public static JPanel tooLow;
public static JPanel exactlyCorrect;
public static JLabel correctAnswer;
public static JFrame guiFrame;
public static void main(String[] args){
RandomFun();
}
public static void RandomFun()
{
Scanner input=new Scanner(System.in);
guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Fun Games!");
guiFrame.setSize(500,500);
guiFrame.setLocationRelativeTo(null);
guiFrame.setVisible(true);
final JPanel tooHigh = new JPanel();
higherThan = new JLabel("Too High!");
final JPanel tooLow = new JPanel();
lowerThan = new JLabel("Too Low!");
final JPanel exactlyCorrect = new JPanel();
correctAnswer = new JLabel("Congratulations, you won!");
tooHigh.add(higherThan);
tooLow.add(lowerThan);
exactlyCorrect.add(correctAnswer);
guiFrame.add(tooHigh, BorderLayout.CENTER);
guiFrame.add(tooLow, BorderLayout.CENTER);
guiFrame.add(exactlyCorrect, BorderLayout.CENTER);
}
public static void GuessNumber(){
String again;
String lastGuess = "0";
boolean moreGame=true;
int lastGuessInt = Integer.parseInt(lastGuess.toString());
int winner = (int) (Math.random()*999+1);
while(moreGame){
lastGuess = JOptionPane.showInputDialog("Guess a Number");
if(winner < lastGuessInt){
tooHigh.setVisible(true);
tooLow.setVisible(false);
exactlyCorrect.setVisible(false);
}
else if(winner > lastGuessInt){
tooHigh.setVisible(false);
tooLow.setVisible(true);
exactlyCorrect.setVisible(false);
}
else{
tooHigh.setVisible(false);
tooLow.setVisible(false);
exactlyCorrect.setVisible(true);
moreGame=false;
}
}
again = JOptionPane.showInputDialog("Play again? Y/N");
switch(again){
case "y": case "Y":
GuessNumber();
break;
case "n": case "N":
System.exit(0);
break;
}
}
}
Why the "mis-behavior":
Your main method calls RandomFun()
And RandomFun() then creates a JFrame and displays.
It adds 3 JPanels all in the BorderLayout.CENTER position!
Thus only the last JPanel will show because it will cover all the previously added JPanels as per BorderLayout's documented behavior.
Thus your code is behaving exactly as you'd expect it to.
Other issues include a gross over-use of the static modifier, calling setVisible(true) on the JFrame before adding all components, setting the size of the JFrame, creating a method, GuessNumber() that is never called by viable running code, code not adhering to Java naming conventinons (methods and fields should begin with a lower-case letter, classes with an upper-case letter),...
If I were in your shoes, I'd put the GUI coding to the side as I'd first want to concentrate on learning Java basics, including avoiding all static methods and fields and instead creating true OOPs-compliant classes, since this understanding is critical prior to delving into GUI coding. Just a few weeks of study should be enough to get you strong enough to then try some Swing coding.
My attempt to create a guessing game program:
import java.awt.BorderLayout;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.text.JTextComponent;
#SuppressWarnings("serial")
public class RandomNumberGame2 extends JPanel {
private static final int LOW = 0;
private static final int HIGH = 100;
public static final String START_GAME = "Please guess the random number between "
+ LOW + " and " + HIGH;
public static final String TO_HIGH = "Your guess is too high. Please try again";
public static final String TO_LOW = "Your guess is too low. Please try again";
public static final String CONGRATS_YOU_WIN = "Congratulations, you win!!!";
private Random random = new Random();
private int randomNumber; // holds the randomly selected number
private JTextField inputField = new JTextField(5); // where user enters guess
private JButton submitButton = new JButton(new SubmitAction("Submit", KeyEvent.VK_S));
private JButton resetButton = new JButton(new ResetAction("Reset", KeyEvent.VK_R));
private JLabel statusLabel = new JLabel(START_GAME, SwingConstants.CENTER);
public RandomNumberGame2() {
// so field will select all when gains focus
inputField.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
JTextComponent textComp = (JTextComponent) e.getSource();
textComp.selectAll();
}
});
// so input field will submit number if enter is pressed
inputField.addActionListener(submitButton.getAction());
JPanel centerPanel = new JPanel(); // uses flow layout by default
centerPanel.add(new JLabel("Enter number here:"));
centerPanel.add(inputField);
centerPanel.add(submitButton);
centerPanel.add(resetButton);
setLayout(new BorderLayout());
add(statusLabel, BorderLayout.PAGE_START);
add(centerPanel, BorderLayout.CENTER);
resetGame();
}
public void resetGame() {
randomNumber = random.nextInt(HIGH - LOW) + LOW;
inputField.setText("");
statusLabel.setText(START_GAME);
inputField.requestFocusInWindow();
inputField.selectAll();
}
private class SubmitAction extends AbstractAction {
public SubmitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
try {
int input = Integer.parseInt(inputField.getText().trim());
if (input > randomNumber) {
statusLabel.setText(TO_HIGH);
} else if (input < randomNumber) {
statusLabel.setText(TO_LOW);
} else {
statusLabel.setText(CONGRATS_YOU_WIN);
}
inputField.requestFocusInWindow();
inputField.selectAll();
} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(RandomNumberGame2.this,
"Please enter only integer data", "Non-numeric Data Error",
JOptionPane.ERROR_MESSAGE);
inputField.setText("");
}
}
}
private class ResetAction extends AbstractAction {
public ResetAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
resetGame();
}
}
private static void createAndShowGui() {
RandomNumberGame2 mainPanel = new RandomNumberGame2();
JFrame frame = new JFrame("Fun Games 2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}