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.
Related
I have a rectangle, and I am trying to grow it like a graph of some sorts, but it does not show it growing in real time, it just has a white screen then I see a rectangle. Any help would be appreciated, thanks. The code I am having a problem with is under the ¨Animates the bar¨ comment.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Main extends JPanel {
static String[] mainArr;
static int start;
static boolean done = false;
static double datapoint1;
static double datapoint2;
static int jPlaceholder;
public static void main(String[] args) throws Exception {
// Creating the window
JFrame panel = new JFrame();
panel.setSize(450,250);
// Creating the window that shows the animation
JFrame drawingFrame = new JFrame();
drawingFrame.setSize(450,250);
JPanel jp = new JPanel();
jp.setLayout(null);
jp.setBackground(Color.red);
drawingFrame.add(jp);
// Creating all the text fields
JTextField dataTypesTextField = new JTextField("This box is currently not in use. Please do not type anything into this box");
dataTypesTextField.setBounds(50,50, 400,30);
panel.add(dataTypesTextField);
JTextField yearStartTextField = new JTextField("Type in this box what year your data starts in:");
yearStartTextField.setBounds(50,100, 400,30);
panel.add(yearStartTextField);
JTextField yearEndTextField = new JTextField("Type in this box what year your data ends in:");
yearEndTextField.setBounds(50,150, 400,30);
panel.add(yearEndTextField);
// Creating the button to submit the data
JButton enterButton = new JButton("Enter");
enterButton.setBounds(50,200, 100, 30);
panel.add(enterButton);
// =================================== ActionListener for enter button ========================================
enterButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (done==false) {
// Creating the variables to store the data the user just inputted
start = Integer.parseInt(yearStartTextField.getText());
int end = Integer.parseInt(yearEndTextField.getText());
mainArr = new String[end-start+1];
// Gets the data points
dataTypesTextField.setText("Datapoints you will use in order, space between each: ");
done = true;
} else {
// Getting all the data needed
mainArr = dataTypesTextField.getText().split(" ");
double[] datapoints = new double[mainArr.length];
for (int i=0; i<datapoints.length; i++) {
datapoints[i] = Double.parseDouble(mainArr[i]);
}
under here is where I had my problems I am pretty sure, but I could have screwed up somewhere else.
// Animates the bar
for (int i=0; i<datapoints.length-1; i++) {
// Getting all the datapoints
datapoint1 = datapoints[i];
datapoint2 = datapoints[i+1];
int j = 0;
while(j<50) {
j++;
int width = (int) (datapoint1+((datapoint2-datapoint1)/50)*j);
JPanel rectangle = new JPanel();
rectangle.setBackground(Color.black);
rectangle.setBounds(50, 50, width, 30);
jp.add(rectangle);
drawingFrame.setVisible(true);
rectangle.repaint();
System.out.println("The width is: "+width);
at first I thought it was because there was no pause between each ¨frame¨ but it still just shows a white screen, then it shows the rectangle.
try {
Thread.sleep(20);
} catch (Exception exp) {
}
}
}
}
}
});
// =====================================================================================================
// Finishes up both the windows
panel.setLayout(null);
panel.setVisible(true);
}
}
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 am writing GUI for a chat, and I have problem I can't seem to find a solution.
When button Send is clicked variable OKpressed should change to true and in function getUserInput it should recognize it changed but it doesn't..
It's acting like it still says false..
I tried printing out in Send that works, so problem is only that functiong getUserInput doesn't recognize variable as changed
Any help is appreciated..Here's the code
I can't attach all other classes so you can start it, but everything is working except the problem mentioned above
public class Chat extends Process {
public static class myFrame extends JFrame{
/** Creates a new instance of myFrame */
private JTextArea ChatBox=new JTextArea(10,45);
private JScrollPane myChatHistory=new JScrollPane(ChatBox,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
private JTextArea UserText = new JTextArea(5,40);
private JScrollPane myUserHistory=new JScrollPane(UserText,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
private JButton Send = new JButton("Send");
private JTextField User=new JTextField(20);
private String ServerName;
private String UserName;
boolean OKPressed = false;
String poruka;
public myFrame() {
setResizable(false);
setTitle("Client");
setSize(560,400);
Container cp=getContentPane();
cp.setLayout(new FlowLayout());
cp.add(new JLabel("Chat History"));
cp.add(myChatHistory);
cp.add(new JLabel("Chat Box : "));
cp.add(myUserHistory);
cp.add(Send);
cp.add(User);
Send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
poruka=(String)UserText.getText();
OKPressed = true;
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
static myFrame t=new myFrame();
public Chat(Linker initComm) {
super(initComm);
}
public synchronized void handleMsg(Msg m, int src, String tag){
if (tag.equals("chat")) {
System.out.println("Message from " + src +":");
System.out.println(m.getMessage());
t.ChatBox.append(src + ":" + m.getMessage() + "\n");
}
}
public String getUserInput() throws Exception {
while (t.OKPressed == false){}
String chatMsg=t.poruka;
return chatMsg;
}
public IntLinkedList getDest(BufferedReader din) throws Exception {
System.out.println("Type in destination pids with -1 at end:");
System.out.println("Only one pid for synch order:");
IntLinkedList destIds = new IntLinkedList(); //dest for msg
StringTokenizer st = new StringTokenizer(din.readLine());
// StringTokenizer st = new StringTokenizer(t.poruka);
while (st.hasMoreTokens()) {
int pid = Integer.parseInt(st.nextToken());
if (pid == -1) break;
else destIds.add(pid);
}
return destIds;
}
public static void main(String[] args) throws Exception {
String baseName = "Chat";
int myId = Integer.parseInt(args[0]);
int numProc = Integer.parseInt(args[1]);
Linker comm = null;
comm = new CausalLinker(baseName, myId, numProc);
Chat c = new Chat(comm);
for (int i = 0; i < numProc; i++)
if (i != myId) (new ListenerThread(i, c)).start();
BufferedReader din = new BufferedReader(
new InputStreamReader(System.in));
while (true){
System.out.println(c.getUserInput());
String chatMsg = c.getUserInput();
if (chatMsg.equals("quit")) break;
t.ChatBox.append(myId + ": " + chatMsg +"\n");
IntLinkedList destIds = c.getDest(din);
comm.multicast(destIds, "chat", chatMsg);
}
}
}
As you wrote, I cannot run you code, so it is kind of guess, however I think the problem is in empty infinite loop:
while (t.OKPressed == false){}
if you add anything inside, even:
while(t.OKPressed == false){
System.out.println();
}
It should work. It is connected with problem better described for example here: Threads: Busy Waiting - Empty While-Loop, and in post which duplicate it is.
i am building an algorithm simulation tool and I am struggling to get my mainframe class which instantiates and adds all the subcomponents to the JFrame to get the file system location of where the pseudocode is located (for the psuedocode panel.)
I have made every single algorithm have a string which details where the relevant text file information for each algorithm is.
I have a method which then takes the string when the algorithm is passed in and stores it into a string variable.
This string variable is then passed to the panel.
Unfortunately this is throwing a null pointer and I have been trying to debug this and can't get far.
public class SortAnimator extends JFrame
{
private static final int VALUES_LENGTH = 30;
private static final int FRAME_WIDTH = 1200;
private static final int FRAME_HEIGHT = 700;
private PsuedocodePanel pseudoPanel;
private Menu menu;
private InformationPanel infoPanel;
private String algoName;
public String algoLocation;
public SortAnimator(Sorter s) throws IOException
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu=new Menu();
pseudoPanel=new PsuedocodePanel();
ArrayComponent panel = new ArrayComponent();
infoPanel= new InformationPanel();
add(menu,BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
add(pseudoPanel,BorderLayout.WEST);
add(infoPanel,BorderLayout.SOUTH);
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setVisible(true);
int[] values = new int[VALUES_LENGTH];
for (int i = 0; i < values.length; i++)
values[i] = (int) (Math.random() * panel.getHeight());
s.setValues(values);
s.setPanel(panel);
Thread t = new Thread(s);
t.start();
algoName=s.getAlgorithmName();
algoLocation =s.getAlgorithmLocation();
System.out.println(algoLocation);
pseudoPanel.passFileLocation(algoLocation);
}
}
public class PsuedocodePanel extends JPanel{
private JTextArea txtArea;
private String textFile;
private String fileLocation;
public PsuedocodePanel() throws FileNotFoundException, IOException{
setLayout(new BorderLayout());
txtArea=new JTextArea();
txtArea.setEditable(false);
add(txtArea,BorderLayout.CENTER);
FileReader fr = new FileReader(this.fileLocation);
BufferedReader reader=new BufferedReader(fr);
txtArea.read(reader,null);
Dimension dim=getPreferredSize();//returns object
System.out.println(getPreferredSize());
dim.width=300;
dim.height=75;
setPreferredSize(dim);
Border innerBorder=BorderFactory.createTitledBorder("Algorithm Psuedocode");
Border outerBorder=BorderFactory.createEmptyBorder(5,5,5,5);
setBorder(BorderFactory.createCompoundBorder(outerBorder,innerBorder));
}
public void passFileLocation(String algoLocation) {
this.fileLocation= algoLocation;
}
Your PsuedocodePanel class creates a FileReader in its constructor, using this.fileLocation, but fileLocation will be null at that point in the code - see simplified code fragment below:
public class PsuedocodePanel extends JPanel{
private String fileLocation; // not initialised
// constructor does not accept a fileLocation...
public PsuedocodePanel() throws FileNotFoundException, IOException{
// ... so this.fileLocation is null here:
FileReader fr = new FileReader(this.fileLocation);
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.