Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Help with actionListener and buttons

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    22
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Help with actionListener and buttons

    Ok so basically I want this program to change the text of a random JButton out of the 9 on the panel every 5 seconds (I have a timer firing with intervals of 5 seconds) to "mole" and then wait 5 seconds, and if the user doesn't click the button in the time it should change the text back to nothing. One of the problems I'm having is that putting in Thread.sleep() to make the program wait 5 seconds messes up the whole thing and for some reason it never even changes the text if the random JButton to "mole" in the first place. The other problem I'm having is that I want it to set the text to nothing and add one to the counter variable if the button clicked has "mole" as the text, but for some reason it's not working and doesn't add to counter or change the text of the JButton to nothing(even if the requirements for the if statement have been met). Any help anyone can offer to fix either of these would be very appreciated.

    import javax.swing.*;
    import javax.swing.Timer;
    import java.util.*;
    import java.awt.event.*;
    import java.awt.*;
     
    public class MoleGUI implements ActionListener{
     
    	JFrame field;
    	JPanel panel;
    	Timer t = new Timer(5000, this);
    	int counter;
    	ArrayList<JButton> holes;
    	int randButton;
     
     
    	public MoleGUI() {
    		field = new JFrame("Whack-a-Mole");
    		panel = new JPanel(new GridLayout(3,3));
    		field.setContentPane(panel);
    		field.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		holes = new ArrayList<JButton>();
     
    		//add and initialize 9 JButtons in the arrayList
    		for(int x = 0; x < 9;x++)
    			holes.add(new JButton());
     
    		//add the 9 JButtons to the panel
    		for(int x = 0;x < 9;x++)
    			panel.add(holes.get(x));
     
    		//add this as an actionListener for all 9 JButtons 
    		for(int x = 0;x < 9;x++)
    			holes.get(x).addActionListener(this);
     
    		counter = 0;
    	}
     
    	public void display(){
    		field.pack();
    		field.setVisible(true);
    		field.resize(500,500);
    		t.start();
    	}	
     
    	public void actionPerformed(ActionEvent e)
    	{
    		if(e.getSource() == t){
    			randButton = (int)((Math.random() * 8) + 1);
    			holes.get(randButton).setText("Mole");				
     
    		        try {Thread.sleep(1000);} catch (InterruptedException ie) { }
    			holes.get(randButton).setText("");
    		}
     
    		if(e.getSource() == holes.get(0) && holes.get(0).getText().equals("mole")){
    			counter ++;
    			holes.get(0).setText("");
    			System.out.println(counter);
    		}
     
    		if(e.getSource() == holes.get(1) && holes.get(1).getText().equals("mole")){
    			counter ++;
    			holes.get(1).setText("");
    			System.out.println(counter);
    		}
     
    		if(e.getSource() == holes.get(2) && holes.get(2).getText().equals("mole")){
    			counter ++;
    			holes.get(2).setText("");
    			System.out.println(counter);
    		}
     
    		if(e.getSource() == holes.get(3) && holes.get(3).getText().equals("mole")){
    			counter ++;
    			holes.get(3).setText("");
    			System.out.println(counter);
    		}
     
    		if(e.getSource() == holes.get(4) && holes.get(4).getText().equals("mole")){
    			counter ++;
    			holes.get(4).setText("");
    			System.out.println(counter);
    		}
     
    		if(e.getSource() == holes.get(5) && holes.get(5).getText().equals("mole")){
    			counter ++;
    			holes.get(5).setText("");
    			System.out.println(counter);
    		}
     
    		if(e.getSource() == holes.get(6) && holes.get(6).getText().equals("mole")){
    			counter ++;
    			holes.get(6).setText("");
    			System.out.println(counter);
    		}
     
    		if(e.getSource() == holes.get(7) && holes.get(7).getText().equals("mole")){
    			counter ++;
    			holes.get(7).setText("");
    			System.out.println(counter);
    		}
     
    		if(e.getSource() == holes.get(8) && holes.get(8).getText().equals("mole")){
    			counter ++;
    			holes.get(8).setText("");
    			System.out.println(counter);
    		}
    	}
    }
    Last edited by jm24; February 10th, 2012 at 10:36 PM.


  2. #2
    Member snowguy13's Avatar
    Join Date
    Nov 2011
    Location
    In Hyrule enjoying a chat with Demise and Ganondorf
    Posts
    339
    My Mood
    Happy
    Thanks
    31
    Thanked 48 Times in 42 Posts

    Default Re: Help with actionListener and buttons

    Could you please use the correct tags for your code? Here's the syntax: [highlight=Java]//your code here[/highlight]

    e.getSource() == t

    First of all, don't use == with objects. Instead, use a try statement, try to cast e to a Timer, and then use the <Timer>.equals() methods.

    (to class cast, simply use some code like this:

    Timer source = (Timer)e.getSource();

    Include this and the rest of the code for a timer within a try statement; if the source of e is a timer, you'll have no problems, but if e is not a timer, an exception will be thrown an caught, and the program will move on.)

    You could do the same thing with your buttons...

    if(e.getSource() == holes.get(0) && holes.get(0).getText().equals("mole")){
    counter ++;
    holes.get(0).setText("");
    System.out.println(counter);
    }

    Instead of this bulky code repeated over and over, you could use a try statement and attempt to class cast e.getSource() to a JButton. Once you do this, you can check if the source's text equals "mole", and avoid repeating the same statements over and over.

    As for your problems, I suggest putting in some println's in so that you can see what the program's actually doing.
    Use highlight tags to help others help you!

    [highlight=Java]Your prettily formatted code goes here[/highlight]

    Using these tags makes your code formatted, and helps everyone answer your questions more easily!




    Wanna hear something funny?

    Me too.

  3. The Following User Says Thank You to snowguy13 For This Useful Post:

    jm24 (February 10th, 2012)

  4. #3
    Member snowguy13's Avatar
    Join Date
    Nov 2011
    Location
    In Hyrule enjoying a chat with Demise and Ganondorf
    Posts
    339
    My Mood
    Happy
    Thanks
    31
    Thanked 48 Times in 42 Posts

    Default Re: Help with actionListener and buttons

    Now that I think about it, I believe it would be beneficial to create separate ActionListeners for your Timer and JButtons. That way, you could avoid some of those wicked if-statements and try-catching class casts. Note that an easy way to do a unique ActionListener is like this:

    Timer t = new Timer(3000, new ActionListener(){
       public void actionPerformed(ActionEvent e)
       {
          //what to do when Timer fires here
       }
    };
    /*By doing this, you create an ActionListener
    right in the declaration*/
    Use highlight tags to help others help you!

    [highlight=Java]Your prettily formatted code goes here[/highlight]

    Using these tags makes your code formatted, and helps everyone answer your questions more easily!




    Wanna hear something funny?

    Me too.

  5. The Following User Says Thank You to snowguy13 For This Useful Post:

    jm24 (February 10th, 2012)

  6. #4
    Junior Member
    Join Date
    Feb 2012
    Posts
    22
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Re: Help with actionListener and buttons

    So wait, I can have two different actionListeners within the same class? (sorry I'm a bit of a noob lol) Also if you could show me an example of the way you're saying to use casting with the try statements that would be very helpful too.

    EDIT: I got the 2 separate actionListeners thing (I just created a separate ButtonListener class to handle the button actions),
    but I would still appreciate an example of the casting with the try statements. Thanks for the help btw

    EDIT2: I added the following for the ButtonListener but it's telling me that source cannot be resolved:

    try{
    	JButton source = (JButton)e.getSource();
    } catch (ClassCastException c){
    	if(source.getText.equals("mole")){
    		counter++;
    		source.setText("");
    		System.out.println(counter);
    	}
    }
    Last edited by jm24; February 10th, 2012 at 11:18 PM.

  7. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with actionListener and buttons

    First of all, don't use == with objects. Instead, use a try statement, try to cast e to a Timer, and then use the <Timer>.equals() methods.
    I think its OK to test if the source of the event is a component by using the == operator.
    I wouldn't use the try{}catch.


    Can you make a small program (SSCCE) that compiles and executes to show the problem?

  8. #6
    Junior Member
    Join Date
    Feb 2012
    Posts
    22
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Re: Help with actionListener and buttons

    I would but I'm not really sure how to do that lol. And yea I was almost sure it was ok to use == as long as I wasn't messing around with aliases or anything like that but idk.

    EDIT: Oh ok I get what you're saying but yea for some reason I can't export from eclipse; it always gives me an error and then when I try to run it, it either doesn't run or it tells me it can't find the main class. I've tried specifying the main class but iddk nothing's worked lol.
    Last edited by jm24; February 11th, 2012 at 12:40 PM.

  9. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with actionListener and buttons

    it tells me it can't find the main class
    Does this error mean that you have a class named: main that you are trying to execute?
    For example: java main
    and the java program can not find the main.class file?

    Here is what I get with that command:

    Microsoft Windows XP [Version 5.1.2600]

    D:\JavaDevelopment\Testing\ForumQuestions8>java main
    Exception in thread "main" java.lang.NoClassDefFoundError: main
    Caused by: java.lang.ClassNotFoundException: main
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    Could not find the main class: main. Program will exit.

    D:\JavaDevelopment\Testing\ForumQuestions8>
    Note: Following the message in red is the name of the class that is missing: main.
    What class is missing when you try executing the program?
    Last edited by Norm; February 11th, 2012 at 12:56 PM.

  10. #8
    Junior Member
    Join Date
    Feb 2012
    Posts
    22
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Re: Help with actionListener and buttons

    No the name of my main class is MoleMain but yea I get that last line every time I export it into a runnable jar file and try to run it

  11. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with actionListener and buttons

    You need to figure out how to use the IDE. I don't use it so I can't help you.
    Do you know how to use the java command to execute a class file?
    >java classname
    For you if your class is not in a package:
    >java MoleGUI

  12. #10
    Junior Member
    Join Date
    Feb 2012
    Posts
    22
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Re: Help with actionListener and buttons

    Alright well thanks for the help anyway. I'll try to figure this out lol.

  13. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with actionListener and buttons

    Try asking on the IDE section of the forum: how to create a jar file with the IDE.

Similar Threads

  1. Help with ActionListener please
    By knightmetal in forum AWT / Java Swing
    Replies: 3
    Last Post: August 23rd, 2011, 05:41 PM
  2. ActionListener help
    By hello_world in forum What's Wrong With My Code?
    Replies: 10
    Last Post: July 27th, 2011, 11:45 PM
  3. ActionListener help
    By QBird in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 1st, 2011, 12:25 PM
  4. [SOLVED] ActionListener help
    By kbwalker87 in forum What's Wrong With My Code?
    Replies: 13
    Last Post: October 14th, 2010, 06:57 PM
  5. ActionListener Help?
    By Drag01 in forum AWT / Java Swing
    Replies: 1
    Last Post: March 30th, 2010, 08:21 PM