I'm new in Java and I need your help in implementing a GUI. Below is a Guessing Game code. It works.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class GuessGame extends JFrame {
private JTextField guessTextField;
private JLabel introLabel, guessLabel, clueLabel;
private JButton enterB, playAgainB;
private int randomNumber;
public GuessGame() {
super("Guessing Game!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creates components
enterB = new JButton("Guess");
playAgainB = new JButton("Quit");
introLabel = new JLabel("I have a number between 1 and 1000.");
guessLabel = new JLabel("Can you guess my number? Please enter your guess:");
clueLabel = new JLabel("");
// comment2 = new JLabel(" ");
guessTextField = new JTextField(5);
//content pane
Container c = getContentPane();
setLayout(new FlowLayout());
//adding component to the pane
c.add(introLabel);
c.add(guessLabel);
c.add(guessTextField);
//c.add(comment2);
c.add(enterB);
c.add(playAgainB);
c.add(clueLabel);
//enterB.setMnemonic('G');
//playAgainB.setMnemonic('Q');
setSize(350, 200);
setLocationRelativeTo(null);
setVisible(true);
//setResizable(false);
initializeNumber();
//creating the handler
GuessButtonHandler ghandler = new GuessButtonHandler(); //instantiate new object
enterB.addActionListener(ghandler); // add event listener
QuitButtonHandler qhandler = new QuitButtonHandler();
playAgainB.addActionListener(qhandler);
}
private void initializeNumber() {
randomNumber = new Random().nextInt(1000) + 1;
System.out.println(randomNumber);
}
class QuitButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
class GuessButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
int getUserInput;
int diff;
int Difference;
try {
getUserInput = Integer.parseInt(guessTextField.getText().trim());
if (getUserInput == randomNumber) {
clueLabel.setText(" Correct!");
}
if (getUserInput > randomNumber) {
clueLabel.setText(" Too High");
} else {
clueLabel.setText(" Too Low");
}
}
catch (NumberFormatException e1) {
clueLabel.setText("Enter a VALID number!");
}
}
}
public static void main(String args[]) {
//instantiate gueesgame object
GuessGame app = new GuessGame();
}
}
However, the color of the window should change into red or blue. Please help me with this code. I'm new in Java and it's syntax. I'd really appreciate your help. Thank you!
You could use:
current = Integer.parseInt(guessTextField.getText().trim());
if (!firstTime) {
if (getUserInput > previous) {
getContentPane().setBackground(Color.red);
} else {
getContentPane().setBackground(Color.blue);
}
}
where firstTime and previous are class member variables.
Don't forget to assign previous if the getUserInput == randomNumber is not met.
Update:
You are setting the background blue twice:
if (getUserInput < randomNumber) {
clueLabel.setText("Too Low");
getContentPane().setBackground(Color.blue); <------ remove this extra call
previous = getUserInput;
}
A code is better than thousand words.....
if (current_Input > previous) {
c.setBackground(Color.red);
} else {
c.setBackground(Color.blue);
}
Related
Im making a simon game and i have no idea what to do. I got sound and all that good stuff working but as for everything else I have no idea what im doing. I need some help making the buttons work and flash in the right order. (comments are failed attempts) Any help is very much appreciated.
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.ArrayList;
public class Game extends JFrame
{
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int sequence1;
int[] anArray;
public Game()
{
anArray = new int[1000];
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score");
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try{sound1 = Applet.newAudioClip(wavFile1.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound2 = Applet.newAudioClip(wavFile2.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound3 = Applet.newAudioClip(wavFile3.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound4 = Applet.newAudioClip(wavFile4.toURL());}
catch(Exception e){e.printStackTrace();}
setVisible(true);
}
public class Button1Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound1.play();
}
}
public class Button2Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound2.play();
}
}
public class Button3Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound3.play();
}
}
public class Button4Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound4.play();
}
}
/*
public static int[] buttonClicks(int[] anArray)
{
return anArray;
}
*/
public class Button5Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
for (int i = 1; i <= 159; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
anArray[i] = randomNum;
System.out.println("Element at index: "+ i + " Is: " + anArray[i]);
}
buttonClicks(anArra[3]);
/*
for (int i = 1; i <= 100; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt((4 - 1) + 1) + 1;
if(randomNum == 1)
{
button1.doClick();
sequence1 = 1;
System.out.println(sequence1);
}
else if(randomNum == 2)
{
button2.doClick();
sequence1 = 2;
System.out.println(sequence1);
}
else if(randomNum == 3)
{
button3.doClick();
sequence1 = 3;
System.out.println(sequence1);
}
else
{
button4.doClick();
sequence1 = 4;
System.out.println(sequence1);
}
}
*/
}
}
}
Below is some code to get you started. The playback of the sequences is executed in a separate thread, as you need to use delays in between. This code is by no means ideal. You should use better names for the variables and refactor to try to create a better and more encapsulated game model. Maybe you could use this opportunity to learn about the MVC design pattern?
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Game extends JFrame {
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int level;
int score;
int[] anArray;
int currentArrayPosition;
public Game() {
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
level = 0;
score = 0;
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score: " + String.valueOf(score));
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try {
sound1 = Applet.newAudioClip(wavFile1.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound2 = Applet.newAudioClip(wavFile2.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound3 = Applet.newAudioClip(wavFile3.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound4 = Applet.newAudioClip(wavFile4.toURL());
} catch (Exception e) {
e.printStackTrace();
}
setVisible(true);
}
public class Button1Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound1.play();
buttonClicked(button1);
}
}
public class Button2Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound2.play();
buttonClicked(button2);
}
}
public class Button3Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound3.play();
buttonClicked(button3);
}
}
public class Button4Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound4.play();
buttonClicked(button4);
}
}
private void buttonClicked(JButton clickedButton) {
if (isCorrectButtonClicked(clickedButton)) {
currentArrayPosition++;
addToScore(1);
if (currentArrayPosition == anArray.length) {
playNextSequence();
} else {
}
} else {
JOptionPane.showMessageDialog(this, String.format("Your scored %s points", score));
score = 0;
level = 0;
label1.setText("Score: " + String.valueOf(score));
}
}
private boolean isCorrectButtonClicked(JButton clickedButton) {
int correctValue = anArray[currentArrayPosition];
if (clickedButton.equals(button1)) {
return correctValue == 1;
} else if (clickedButton.equals(button2)) {
return correctValue == 2;
} else if (clickedButton.equals(button3)) {
return correctValue == 3;
} else if (clickedButton.equals(button4)) {
return correctValue == 4;
} else {
return false;
}
}
public class Button5Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
playNextSequence();
}
}
private void playNextSequence() {
level++;
currentArrayPosition = 0;
anArray = createSequence(level);
(new Thread(new SequenceButtonClicker())).start();
}
private int[] createSequence(int sequenceLength) {
int[] sequence = new int[sequenceLength];
for (int i = 0; i < sequenceLength; i++) {
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
sequence[i] = randomNum;
}
return sequence;
}
private JButton getButtonFromInt(int sequenceNumber) {
switch (sequenceNumber) {
case 1:
return button1;
case 2:
return button2;
case 3:
return button3;
case 4:
return button4;
default:
return button1;
}
}
private void flashButton(JButton button) throws InterruptedException {
Color originalColor = button.getBackground();
button.setBackground(new Color(255, 255, 255, 200));
Thread.sleep(250);
button.setBackground(originalColor);
}
private void soundButton(JButton button) {
if (button.equals(button1)) {
sound1.play();
} else if (button.equals(button2)) {
sound2.play();
} else if (button.equals(button3)) {
sound3.play();
} else if (button.equals(button4)) {
sound4.play();
}
}
private void addToScore(int newPoints) {
score += newPoints;
label1.setText("Score: " + String.valueOf(score));
}
private class SequenceButtonClicker implements Runnable {
public void run() {
for (int i = 0; i < anArray.length; i++) {
try {
JButton nextButton = getButtonFromInt(anArray[i]);
soundButton(nextButton);
flashButton(nextButton);
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, "Interrupted", ex);
}
}
}
}
}
I'm trying to write a program where you guess a random generated number (from 1-1000) and the program will tell you if you're getting close or not. The problem I'm having is that I have to have the background change color according to how close you are to the answer. Red is closer, blue is further away. I have the code but I can't figure out why the background isn't working. Is it something to do with the container? Thank you!
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Random;;
public class GuessGame extends JFrame
{
private JButton newGameButton;
private JButton enterButton;
private JButton exitButton;
private JTextField guessBox;
private JLabel initialTextLabel;
private JLabel enterLabel;
private JLabel userMessageLabel;
private int randomNumber;
private int userGuess;
private int counter = 0;
private int lastGuess = 0;
private Color background;
Container container;
public GuessGame()
{
super("Guessing Game");
newGameButton = new JButton("New Game");
exitButton = new JButton("Exit Game");
enterButton = new JButton("Enter");
guessBox = new JTextField(4);
initialTextLabel = new JLabel("I have a number between 1 and 1000 can you guess my number?");
enterLabel = new JLabel("Please enter your first guess.");
userMessageLabel = new JLabel("");
randomNumber = new Random().nextInt(1000) + 1;
container=getContentPane();
container.setLayout(new FlowLayout());
container.add(initialTextLabel);
container.add(enterLabel);
container.add(guessBox);
container.add(newGameButton);
container.add(enterButton);
container.add(exitButton);
container.add(userMessageLabel);
setSize(400, 150);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
newGameButtonHandler nghandler = new newGameButtonHandler();
newGameButton.addActionListener(nghandler);
ExitButtonHandler exithandler = new ExitButtonHandler();
exitButton.addActionListener(exithandler);
enterButtonHandler enterhandler = new enterButtonHandler();
enterButton.addActionListener(enterhandler);
}
class newGameButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
getContentPane();
background=Color.lightGray;
userMessageLabel.setText("");
randomNumber = new Random().nextInt(1000) + 1;
}
}
class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
class enterButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
userGuess = Integer.parseInt(guessBox.getText());
compareGuess(userGuess, randomNumber);
}
}
public void paint(Graphics g)
{
super.paint(g);
container.setBackground(background);
}
public void compareGuess(int userGuess, int randomNumber)
{
counter++;
if (userGuess == randomNumber)
{
userMessageLabel.setText("You are correct, it took you: " + counter + " tries");
getContentPane();
background=Color.green;
}
else if (userGuess > randomNumber)
{
userMessageLabel.setText("Too high");
}
else if (userGuess < randomNumber)
{
userMessageLabel.setText("Too Low");
}
if (counter > 1)
{
if ((randomNumber - userGuess) > (randomNumber - lastGuess))
{
getContentPane();
background=Color.red;
}
else if ((randomNumber - userGuess) < (randomNumber - lastGuess))
{
getContentPane();
background=Color.blue;
}
else
{
getContentPane();
background=Color.gray;
}
}
lastGuess = userGuess;
}
public static void main(String[] args)
{
GuessGame myGuessGame = new GuessGame();
myGuessGame.setVisible(true);
}
}
You are trying to override paint(Graphics g) function of JFrame. We should not override paint function of Top level component like JFrame.
Use a custom component extending JPanel and override its paintComponent(Graphics g) function and don't forget to call super.paintComponent(g) inside this function.
When any update should be made to the painting of a component, invoke component.repaint() on that component to reflect the changes on the GUI.
Please have a tour to the Official tutorial page: Lesson: Performing Custom Painting
I addition to Sage's comments, you are calling setBackground from within the paint, which is simply going to make another request to paint...again and again and again...
The other problem is, you are changing the background of the frame, not it's content pane.
Instead, get rid of your paint method, you're not doing anything with it...
Instead, when you want to change the color, simply call getContentPane().setBackground(...), for example...
class newGameButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
getContentPane().setBackground(Color.lightGray);
userMessageLabel.setText("");
randomNumber = new Random().nextInt(1000) + 1;
}
}
If that doesn't work, you may need to call getContentPane().repaint()
I am making a clone of minesweeper with (slightly modified) JButtons. Because there are so many game tiles in minesweeper, I am storing them as an array. When I try and add the buttons to the Frame using a for loop, I get a nullpointerexception on the buttons. The class ButtonObject is extended from the JButton class with just two extra variables and getter/setter methods. What is going wrong?
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class Minesweeper extends JFrame implements ActionListener{
JLabel starttitle;
ButtonObject[] minefield;
JFrame frame;
Random r = new Random();
int rand;
JPanel startscreen;
JPanel gamescreen;
int gamesize;
JButton ten;
JButton tfive;
JButton fifty;
GridLayout layout;
public Minesweeper()
{
frame = new JFrame("Minesweeper");
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);;
startscreen = new JPanel();
startScreen();
}
public void startScreen()
{
ten = new JButton("10 x 10");
tfive = new JButton("25 x 25");
fifty = new JButton("50 x 50");
starttitle = new JLabel("Welcome to minesweeper. Click a game size to begin.");
frame.add(startscreen);
startscreen.add(starttitle);
startscreen.add(ten);
startscreen.add(tfive);
startscreen.add(fifty);
ten.addActionListener(this);
tfive.addActionListener(this);
fifty.addActionListener(this);
}
public void initializeGame()
{
minefield = new ButtonObject[gamesize];
for(int i = 0;i<gamesize;i++)
{
minefield[i]=new ButtonObject();
rand = r.nextInt(5);
if(rand==5)
{
minefield[i].setButtonType(true);//this tile is a mine
}
}
}
public void gameScreen()
{
frame.getContentPane().removeAll();
frame.repaint();
initializeGame();
for(int i = 0;i<minefield.length;i++)
{
gamescreen.add(this.minefield[i]);//EXCEPTION HERE
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==ten)
{
gamesize = 99;
gameScreen();
}
else if(e.getSource()==tfive)
{
gamesize = 624;
gameScreen();
}
else if(e.getSource()==fifty)
{
gamesize = 2499;
gameScreen();
}
else
{
System.out.println("Fatal error");
}
}
public static void main(String[] args)
{
new Minesweeper();
}
}
Well, you never initialize your gamescreen variable, so that's totally normal you get a NullPointerException at this line.
Hi everybody I am a bit of stack here. When I run the program and press the button submit it is supposed to change 4 pictures in every 2 seconds.However it is not redisplaying the images. If anyone can give me a hand it would be great. I am using eclipse and the program is compiling and running. Here is the code.
/** Here is the GUI of the program
* class name SlideShowGui.java
* #author Kiril Anastasov
* #date 07/03/2012
*/
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SlideShowGui extends JPanel implements ActionListener, Runnable
{
JLabel name, comments, images;
JTextField namejtf, commentsjtf, captionjtf;
JButton submit;
ImageIcon pictures1, pictures2, pictures3, pictures4;
//ImageIcon []pictures2 = {galileo1.jpg};
SlideShowGui()
{
name = new JLabel("Name:");
this.add(name);
namejtf = new JTextField(15);
this.add(namejtf);
comments = new JLabel("Comments:");
this.add(comments);
commentsjtf = new JTextField(15);
this.add(commentsjtf);
submit = new JButton("Submit");
this.add(submit);
submit.addActionListener(this);
pictures1 = new ImageIcon("galileo1.jpg");
images = new JLabel(pictures1);
this.add(images);
pictures2 = new ImageIcon("galileo2.jpg");
this.add(images);
pictures3 = new ImageIcon("galileo3.jpg");
this.add(images);
pictures4 = new ImageIcon("galileo4.jpg");
this.add(images);
captionjtf = new JTextField(24);
this.add(captionjtf);
//pictures = new ImageIcon("galileo1.jpg");
// images.setIcon(pictures);
}
public void actionPerformed(ActionEvent ae)
{
Thread t = new Thread(this);
t.start();
if(ae.getSource() == submit)
{
int i = 0;
boolean go = true;
while(go)
{
i++;
System.out.println(i);
try
{
Thread.sleep(2000);
if(i == 1)
{
pictures1 = new ImageIcon("galileo1.jpg");
images.setIcon(pictures1);
System.out.println("picture 1 should be displayed here");
}
if(i == 2)
{
pictures2 = new ImageIcon("galileo2.jpg");
images.setIcon(pictures2);
System.out.println("picture 2 should be displayed here");
}
if(i == 3)
{
pictures3 = new ImageIcon("galileo3.jpg");
images.setIcon(pictures3);
System.out.println("picture 3 should be displayed here");
}
if(i == 4)
{
pictures4 = new ImageIcon("galileo4.jpg");
images.setIcon(pictures4);
System.out.println("picture 4 should be displayed here");
}
if(i == 4)
{
i = 0;
}
}
catch (InterruptedException ie)
{
System.out.println("thread exception");
}
}
}
}
public void run()
{
}
}
/**The driver class of the program. Here is the JFrame
* class name TestSlideShow.java
* #author Kiril Anastasov
* #date 07/03/2012
*/
import java.awt.*;
import javax.swing.*;
public class TestSlideShow
{
public static void main(String[] args)
{
JFrame application = new JFrame();
SlideShowGui panel = new SlideShowGui();
application.add(panel);
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setSize(300,600);
application.setLocation(400,100);
application.setVisible(true);
}
}
Always use javax.swing.Timer never use Thread.sleep(...) in Swing atleast. Here try this code, but do replace the path to your images :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SlideShow extends JPanel
{
private int i = 0;
private Timer timer;
private JLabel images = new JLabel();
private Icon bg = UIManager.getIcon("OptionPane.warningIcon");
private Icon red = UIManager.getIcon("OptionPane.errorIcon");
private Icon blue = UIManager.getIcon("OptionPane.informationIcon");
private ImageIcon pictures1, pictures2, pictures3, pictures4;
private ActionListener action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
boolean go = true;
i++;
System.out.println(i);
if(i == 1)
{
images.setIcon(bg);
System.out.println("picture 1 should be displayed here");
}
if(i == 2)
{
images.setIcon(red);
System.out.println("picture 2 should be displayed here");
}
if(i == 3)
{
images.setIcon(blue);
System.out.println("picture 3 should be displayed here");
}
if(i == 4)
{
images.setIcon(bg);
System.out.println("picture 4 should be displayed here");
}
if(i == 5)
{
go = false;
timer.stop();
System.exit(0);
}
revalidate();
repaint();
}
};
public SlideShow()
{
JFrame frame = new JFrame("SLIDE SHOW");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.getContentPane().add(this);
add(images);
frame.setSize(300, 300);
frame.setVisible(true);
timer = new Timer(2000, action);
timer.start();
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new SlideShow();
}
});
}
}
The whole if (i == ... part can be simplified. Declare a static class member in SlideShowGUI:
private final static ImageIcon[] icons = {new ImageIcon("galileo1.jpg"),
new ImageIcon("galileo2.jpg"),
new ImageIcon("galileo3.jpg"),
new ImageIcon("galileo4.jpg")};
and use it in the replacement of the if statements:
images.setIcon(icons[i-1]);
System.printf("Picture %s should be displayed%n", i-1);
if (i == 4) {
i = 0;
}
You can simplify your code as Andreas_D mentioned.
Your current design will block the main thread as you call Thread.sleep() to it, this will freeze your application.
If you would like to update the Image, you should implement the update code inside run() method.
So if you detect the user press on submit JButton, create and start the new Thread for updating UI.
I am trying to write a program in Java that takes a random number from 1-1000 and then as the guess it the background color changes to blue(cold) or red(warm) if they are in the number. I am new to java GUI, but I think the rest of the logic is right, not sure. It compiles, but the guess button doesn't work. Any guidance will be appreciated.
package guessGame;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.color.*;
import java.util.Random;
import java.util.Random;
import java.util.logging.FileHandler;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class GuessGame extends JFrame
{
private JFrame mainFrame;
private JButton GuessButton;
private JButton QuitButton;
private JLabel prompt1, prompt2;
private JTextField userInput;
private JLabel comment = new JLabel("What is your destiny?");
private JLabel comment2 = new JLabel (" ");
//private int number, guessCount;
//private int lastGuess;
private int randomNumber;
private Color background;
public GuessGame()
{
mainFrame = new JFrame ("Guessing Game!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creates components
GuessButton = new JButton("Guess");
QuitButton = new JButton("Quit");
prompt1 = new JLabel("I have a number between 1 and 1000.");
prompt2 = new JLabel("Can you guess my number? Enter your Guess:");
comment = new JLabel ("What is your destiny?");
comment2 = new JLabel (" ");
userInput = new JTextField(5);
//userInput.addActionListener(new GuessHandler());
//content pane
Container c = mainFrame.getContentPane();
c.setLayout(new FlowLayout());
//adding component to the pane
c.add(prompt1);
c.add(prompt2);
c.add(userInput);
c.add(comment2);
c.add(GuessButton);
c.add(QuitButton);
c.add(comment);
GuessButton.setMnemonic('G');
QuitButton.setMnemonic('Q');
mainFrame.setSize(300,200);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
mainFrame.setResizable(false);
// define and register window event handler
// mainFrame.addWindowListener(new WindowAdapter() {
// public void windowClosing(WindowEvent e)
// { System.exit(0); }
// });
//creating the handler
GuessButtonHandler ghandler = new GuessButtonHandler(); //instantiate new object
GuessButton.addActionListener(ghandler); // add event listener
QuitButtonHandler qhandler = new QuitButtonHandler();
QuitButton.addActionListener(qhandler);
}
public void paint (Graphics g)
{
super.paint(g);
setBackground(background);
}
class QuitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
class GuessButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int getUserInput=0;
int diff;
int Difference;
randomNumber = new Random().nextInt(1001);
try {
getUserInput = Integer.parseInt(
userInput.getText().trim());
} catch (NumberFormatException ex){
comment.setText("Enter a VALID number!");
return;
}
if (getUserInput == randomNumber){
JOptionPane.showMessageDialog(null, "CONGRATULATIONS! You got it!!",
"Random Number: " + randomNumber,
JOptionPane.INFORMATION_MESSAGE);
randomNumber = new Random().nextInt(1000) + 1;
return;
}
if (getUserInput > randomNumber){
comment.setText( "Too High. Try a lower number." );
diff=getUserInput - randomNumber;
Difference=Math.abs(diff);
} else {
comment.setText( "Too Low. Try a higher number." );
diff=randomNumber - getUserInput;
Difference=Math.abs(diff);
}
if(Difference<=25){
comment2.setText("Cold");
setBackgroundColor(Color.blue);
}
if(Difference<=10){
comment2.setText("Warm");
setBackgroundColor(Color.red);
}
else {
}
}
private void setBackgroundColor(Color color) {
setBackgroundColor(color);
}
}
public static void main(String args[]) {
//instantiate gueesgame object
GuessGame app = new GuessGame();
}
}
The colors aren't changing because your setBackgroundColor always uses Color.black. Change it to:
private void setBackgroundColor(Color color) {
setBackground(color);
}
As for the number always being zero. You do not instantiate the randomNumber field. Add this to your constructor:
randomNumber = new Random().nextInt(1001);
Another problem I noticed was you added a window listener to ensure the program exits when you close the window. This is implemented in JFrame. In the constructor add:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Instead of using the deprecated method:
mainFrame.show();
use the not deprecated:
mainFrame.setVisible(true);
Furthermore you have a field, which is never queried:
private Color background;
It's best to do the logic before connecting it to the gui. It's a lot easier to test and find the worst bugs.
Refactored code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class GuessGame extends JFrame {
private JTextField userInput;
private JLabel comment = new JLabel("What is your destiny?");
private JLabel comment2 = new JLabel(" ");
private int randomNumber;
public GuessGame() {
super("Guessing Game!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creates components
JButton guessButton = new JButton("Guess");
JButton quitButton = new JButton("Quit");
JLabel prompt1 = new JLabel("I have a number between 1 and 1000.");
JLabel prompt2 = new JLabel("Can you guess my number? Enter your Guess:");
comment = new JLabel("What is your destiny?");
comment2 = new JLabel(" ");
userInput = new JTextField(5);
//content pane
Container c = getContentPane();
setLayout(new FlowLayout());
//adding component to the pane
c.add(prompt1);
c.add(prompt2);
c.add(userInput);
c.add(comment2);
c.add(guessButton);
c.add(quitButton);
c.add(comment);
guessButton.setMnemonic('G');
quitButton.setMnemonic('Q');
setSize(300, 200);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
initializeNumber();
//creating the handler
GuessButtonHandler ghandler = new GuessButtonHandler(); //instantiate new object
guessButton.addActionListener(ghandler); // add event listener
QuitButtonHandler qhandler = new QuitButtonHandler();
quitButton.addActionListener(qhandler);
}
private void initializeNumber() {
randomNumber = new Random().nextInt(1000) + 1;
}
class QuitButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
class GuessButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
int getUserInput;
int diff;
int Difference;
try {
getUserInput = Integer.parseInt(userInput.getText().trim());
if (getUserInput == randomNumber) {
JOptionPane.showMessageDialog(null, "CONGRATULATIONS! You got it!!",
"Random Number: " + randomNumber,
JOptionPane.INFORMATION_MESSAGE);
initializeNumber();
return;
}
if (getUserInput > randomNumber) {
comment.setText("Too High. Try a lower number.");
diff = getUserInput - randomNumber;
Difference = Math.abs(diff);
} else {
comment.setText("Too Low. Try a higher number.");
diff = randomNumber - getUserInput;
Difference = Math.abs(diff);
}
if (Difference <= 25) {
comment2.setText("Cold");
GuessGame.this.setBackgroundColor(Color.blue);
}
if (Difference <= 10) {
comment2.setText("Warm");
GuessGame.this.setBackgroundColor(Color.red);
}
} catch (NumberFormatException ex) {
comment.setText("Enter a VALID number!");
}
}
}
private void setBackgroundColor(Color color) {
getContentPane().setBackground(color);
}
public static void main(String args[]) {
//instantiate gueesgame object
GuessGame app = new GuessGame();
}
}
You have more Swing components than you need, and you seem to be adding one set to the frame while manipulating another set. For example, you have two JTextFields, fieldBox and userInput. You add userInput to the frame, but check fieldBox for input in the Guess button handler. Since fieldBox is always empty, the NumberFormatException is caught by your exception handler (which should really just catch NumberFormatException, not Exception), and comment is updated with "Enter a VALID number!". However, just like with the double text area, comment isn't actually added to the frame, prompt1 and prompt2 are, so you can't see the change
I would write your logic without a UI first and test it until it was 100% correct. Just use a command line, text UI at first. Once that's done, put a GUI in front of it. It'll help to isolate your problems: once the text-driven logic is right, you'll know that future problems are due to UI.
It makes your MVC separation cleaner as well.