Page 1 of 4 123 ... LastLast
Results 1 to 20 of 77
Like Tree2Likes

Thread: ActionListener to display different ImageIcons:

  1. #1
    jocdrew21 is online now Senior Member
    Join Date
    Jan 2014
    Posts
    106
    Rep Power
    0

    Default ActionListener to display different ImageIcons:

    If you look at line 74 you will see my actionPerformed method where I want to switch the icon displayed on the JButton. I know I still have to add the images to the button however I am running into a few issues here.

    Therefore my main question is, am I even approaching this problem correctly? In my next class it will be vital that I can decipher what each icon is display on the JButton. I am working on programing A* but I have to get everything talking first.

    Please take a look at line 74, any advice would be greatly appreciated.

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.*;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    
    public class Screen implements ActionListener
    {
    	JButton start;
    	JButton reset;
    	JButton box[][] = new JButton[20][20];
    	JLabel lbl;
    	//Icons to be displayed in box[][]
    	ImageIcon wall;
    	ImageIcon begin;
    	ImageIcon end;
    	
    	//counter how many time box[][] was pressed to enable
    	//the Image Icons
    	private int counter=0;
    	 
    	Screen()
    	{
    		//main frame
    		JFrame j = new JFrame("A* Algorithm");
    	
    		//setting main frame
    		j.setSize(1200,500);
    		j.setLayout(new BorderLayout());
    		j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		
    		//create Panel for multi array buttons
    		JPanel p = new JPanel();
    		p.setLayout(new GridLayout(20,20));
    		
    		//create command buttons "start" and "restart"
    		JPanel CmdBtns = new JPanel();
    		
    		//create buttons matrix of buttons
    		for(int row=0;row<20;row++)
    		{
    			for(int col=0;col<20;col++)
    			{   //create new matrix buttons
    				box[row][col] = new JButton();
    				//add buttons to panel
    				p.add(box[row][col]);
    			}
    		}
    		
    		//create start button
    		start = new JButton("Start");
    		CmdBtns.add(start);
    		
    		//create reset button
    		reset = new JButton("Reset");
    		CmdBtns.add(reset);
    		
    		//Centering matrix buttons onto main JFrame
    		j.add(p,BorderLayout.CENTER);
    		
    		//adding start and restart buttons
    		j.add(CmdBtns,BorderLayout.SOUTH);
    		
    		j.setVisible(true);
    	}
    	
    	//handling matrix buttons
    	public void actionPerformed(ActionEvent ae)
    	{
    		//counting how many times button the the matrix was pressed
    		counter++;
    		//reseting counter to zero if the buttons was pressed three times
    		counter%=3;
    		
    		if(ae.getActionCommand().equals(box))
    		{
    			switch(counter)
    			{
    			case 0:
    				//display wall icon
    				break;
    			case 1:
    				//display start icon
    				break;
    			case 2:
    				//display end icon
    				break;
    			
    				default:
    					break;
    		
    			}
    		}
    	}
    	
    	public static void main(String[] args)
    	{
    		new Screen();
    	}
    
    }

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,890
    Rep Power
    25

    Default Re: ActionListener to display different ImageIcons:

    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,354
    Rep Power
    6

    Default Re: ActionListener to display different ImageIcons:

    I can't comment on your 'question' because the only thing that line points at is an incrementing integer. I can look at that all I want, its not going to tell me what is inside your head. I can make a pretty good guess but it is your job as a person asking a question to make it so I don't have to do that. So you have to actually complete your code before you can start asking questions about it, or be able to properly explain it using for example pseudo code.

    I do spot a likely bug in your code on line 78.

    Java Code:
    if(ae.getActionCommand().equals(box))
    I'm pretty sure you meant that to be:

    Java Code:
    f(ae.getSource().equals(box))
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  4. #4
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,025
    Rep Power
    6

    Default Re: ActionListener to display different ImageIcons:

    I'm not certain the OP mean that either since box is an array. So the comparison will still return false.

    Now if you want to record how many times a specific JButton in the matrix was pressed, you don't need to compare anything. Just create a map<JButton, Integer> and index it from the source of the event to get the counter for that button. Assuming that was your intention.

    Regards,
    Jim
    gimbal2 likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  5. #5
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,354
    Rep Power
    6

    Default Re: ActionListener to display different ImageIcons:

    Dangit, you're right of course. Oh well, I tried and failed.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  6. #6
    jocdrew21 is online now Senior Member
    Join Date
    Jan 2014
    Posts
    106
    Rep Power
    0

    Default Re: ActionListener to display different ImageIcons:

    I want to keep track of how many times each button is pressed and reset each button every third time it is pressed.

    To start off it is set to null
    press once it is set to wall
    pressed twice set to begin
    pressed three times, set to end
    pressed fourth time it is back to null and the process repeats for each button.

    The above buttons will be used to find a path, if it is null it will be check to see if it is one of the nodes on the shortest path, walls will not be checked and the program will start from the “start” icon and end when it find the “end” icon.

    map<JButton,Integer> is a hash table correct? I was reading about it and it seemed to behave as a set. I am more familiar with C++ and trying to learn swing and get better at java. Thought this would be a fun challenging project and I appreciate the advice.

    I am also posting this question in another forum:
    ActionListener changing ImageIcons:
    Only saying that because I have a feeling norm posted that comment as if I was trying to mislead posters on here.

    http://www.youtube.com/watch?v=FNRfSQDF7TA
    This above link is something like what I am trying to do. I will eventually add a few more path find algorithms to the options but one step at a time.
    Last edited by jocdrew21; 05-23-2014 at 07:53 PM.

  7. #7
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,025
    Rep Power
    6

    Default Re: ActionListener to display different ImageIcons:

    The map is a hash table. It behaves as a set in that it can't have duplicate keys. But the keys map to some value. It is simply a way to achieve fast lookup of items which don't lend themselves to direct access lookup structures like arrays.

    And there is nothing wrong with cross posting as long as you let folks know (like you just did). That way, someone won't waste their time repeating an answer that was posted elsewhere (assuming they took the time to look at the other posts).

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  8. #8
    jocdrew21 is online now Senior Member
    Join Date
    Jan 2014
    Posts
    106
    Rep Power
    0

    Default Re: ActionListener to display different ImageIcons:

    So basically extend JButton, and use the map library. I will give it a shot.

    Being that I am implementing modules to the counter (counter%=3) will it be counter productive? Meaning I willing be sending the key value of 1-3, will it allowing the most recent number in as the present value and ignore the others? I think I just answered my own question as I wrote this but I just want to make sure.

  9. #9
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,890
    Rep Power
    25

    Default Re: ActionListener to display different ImageIcons:

    If you extend JButton, the new class could keep the count in a class instance variable.
    If you don't understand my response, don't ignore it, ask a question.

  10. #10
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,025
    Rep Power
    6

    Default Re: ActionListener to display different ImageIcons:

    I never said extend JButton. But if you do, then you can do what Norm said and store the counter in an instance field. Then you don't need the map.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  11. #11
    jocdrew21 is online now Senior Member
    Join Date
    Jan 2014
    Posts
    106
    Rep Power
    0

    Default Re: ActionListener to display different ImageIcons:

    I thought about all the advice I have been getting and then I thought what if I use an inner class to hand handle the buttons actions. I am still working on the box[][] matrix of buttons at the moment. I decided to create and inner class inside the loop line 47 for each button. This way the whole interface will be in one class and I can extend it later.

    When I run the program and click on one of the buttons nothing happens:

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.*;
    
    public class Screen extends JButton  
    {
        JButton start;
        JButton reset;
        JButton box[][] = new JButton[20][20];
        JLabel lbl;
        //Icons to be displayed in box[][]
        ImageIcon wall;
        ImageIcon begin;
        ImageIcon end;
         
        //counter how many time box[][] was pressed to enable
        //the Image Icons
        private int counter=0;
          
        Screen()
        {
            //main frame
            JFrame j = new JFrame("A* Algorithm");
         
            //setting main frame
            j.setSize(1200,500);
            j.setLayout(new BorderLayout());
            j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             
            //create Panel for multi array buttons
            JPanel p = new JPanel();
            p.setLayout(new GridLayout(20,20));
             
            //create command buttons "start" and "restart"
            JPanel CmdBtns = new JPanel();
             
            //create buttons matrix of buttons
            for(int row=0;row<20;row++)
            {
                for(int col=0;col<20;col++)
                {   //create new matrix buttons
                    box[row][col] = new JButton();
                    //handling matrix buttons with inner class
                    box[row][col].addActionListener(new ActionListener()
                    {
                    public void actionPerformed(ActionEvent ae)
                    {
                        //counting how many times button the the matrix was pressed
                        counter++;
                        //reseting counter to zero if the buttons was pressed three times
                        counter%=4;
                        
                        wall = new ImageIcon("wall.png");
                		begin = new ImageIcon("begin.png");
                		end = new ImageIcon("end.png");
                         
                        if(ae.getSource().equals(box))
                        {
                            switch(counter)
                            {
                            case 0:
                                //has not been selected
                            	setIcon(null);
                                break;
                            case 1:
                            	//display wall icon
                            	setIcon(wall);
                                break;
                            case 2:
                            	//display start icon
                            	setIcon(begin);
                                break;
                            case 3:
                            	//display end icon
                            	setIcon(end);
                                default:
                                    break;
                            }
                        }
                    }
                    });
                    //add buttons to panel
                    p.add(box[row][col]);
                }
            }
            //create start button
            start = new JButton("Start");
            CmdBtns.add(start);
             
            //create reset button
            reset = new JButton("Reset");
            CmdBtns.add(reset);
            
            //handling start and reset buttons
            //with inner class
            start.addActionListener(new ActionListener()
            {
        	public void actionPerformed(ActionEvent ae)
        	{
        		if(ae.getSource().equals("Start"))
        		{
        			
        		}
        		else
        		{
        			
        		}
        		
        	}
            });
             
            //Centering matrix buttons onto main JFrame
            j.add(p,BorderLayout.CENTER);
             
            //adding start and restart buttons
            j.add(CmdBtns,BorderLayout.SOUTH);
             
            j.setVisible(true);
        }
          
        public static void main(String[] args)
        {
            new Screen();
        }
     
    }
    Last edited by jocdrew21; 05-24-2014 at 04:54 PM.

  12. #12
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,025
    Rep Power
    6

    Default Re: ActionListener to display different ImageIcons:

    First, whether or not to use an inner class is not the problem. Why is Screen subclassing JButton? This makes no sense from an OO perspective. And more importantly, what is the purpose of the box array? Where do you or are you planning to reference this array. I have a hunch that you may not need it.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  13. #13
    jocdrew21 is online now Senior Member
    Join Date
    Jan 2014
    Posts
    106
    Rep Power
    0

    Default Re: ActionListener to display different ImageIcons:

    I need to make an multi array for an A* algorithm. I will extend this class so I can access the current state of each button to see if it is a wall, start location or end location.

    post #6 has a link to what I am trying to do.

    I extended JButton so I can setIcon to the buttons if they were pressed
    Last edited by jocdrew21; 05-24-2014 at 05:17 PM.

  14. #14
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,890
    Rep Power
    25

    Default Re: ActionListener to display different ImageIcons:

    Java Code:
    if(ae.getSource().equals(box))
    That compares a component(returned by getSource()) to an array: box. It will never be true.

    Also since each button has a dedicated listener added to it, there is no need to test the source of the event. It can only come from the one JButton that it was added to.

    The ImageIcons don't need to be loaded every time a button is pressed. Once in the program is enough.
    If you don't understand my response, don't ignore it, ask a question.

  15. #15
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,025
    Rep Power
    6

    Default Re: ActionListener to display different ImageIcons:

    Do you access the state of each button anywhere else in the program besides the actionPerformed method?

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  16. #16
    jocdrew21 is online now Senior Member
    Join Date
    Jan 2014
    Posts
    106
    Rep Power
    0

    Default Re: ActionListener to display different ImageIcons:

    Thank you very much norm, yes that was a little silly for me to check if a certain buttons was pressed when each button has its own actionListener. I set the ImageIcons as global variables so now I am no longer creating new ones every time.

    @Jim yes it is very important I know every single buttons state. I will extend this class and will need to know if the button is null, a wall or the start or end button.

    If though I made these changes the buttons are still not showing any output :(

    Fixed method below:
    Java Code:
    Screen()
        {
            //main frame
            JFrame j = new JFrame("A* Algorithm");
         
            //setting main frame
            j.setSize(1200,500);
            j.setLayout(new BorderLayout());
            j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             
            //create Panel for multi array buttons
            JPanel p = new JPanel();
            p.setLayout(new GridLayout(20,20));
             
            //create command buttons "start" and "restart"
            JPanel CmdBtns = new JPanel();
             
            //create buttons matrix of buttons
            for(int row=0;row<20;row++)
            {
                for(int col=0;col<20;col++)
                {   //create new matrix buttons
                    box[row][col] = new JButton();
                    //handling matrix buttons with inner class
                    box[row][col].addActionListener(new ActionListener()
                    {
                    public void actionPerformed(ActionEvent ae)
                    {
                        //counting how many times button the the matrix was pressed
                        counter++;
                        //reseting counter to zero if the buttons was pressed three times
                        counter%=4;
                          
                            switch(counter)
                            {
                            case 0:
                                //has not been selected
                            	setIcon(null);
                                break;
                            case 1:
                            	//display wall icon
                            	setIcon(wall);
                                break;
                            case 2:
                            	//display start icon
                            	setIcon(begin);
                                break;
                            case 3:
                            	//display end icon
                            	setIcon(end);
                                default:
                                    break;
                        }
                    }
                    });

  17. #17
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,890
    Rep Power
    25

    Default Re: ActionListener to display different ImageIcons:

    buttons are still not showing any output
    Try debugging the code by adding some println() statements to print out messages when methods are called and when the values of variables are changed so you can see what code is being executed and what the values in the variables are when a button is pressed.
    If you don't understand my response, don't ignore it, ask a question.

  18. #18
    jocdrew21 is online now Senior Member
    Join Date
    Jan 2014
    Posts
    106
    Rep Power
    0

    Default Re: ActionListener to display different ImageIcons:

    Will do norm thanks.

    My next step to tackle is to add values to each button. For example move cost values and distance values. I suppose that does't matter what I am using it for but do I just create a variable and a loop setting the values to each button?

    In other words will each button behave as if it is a inner class have its own variables that I can access in other methods?

  19. #19
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,890
    Rep Power
    25

    Default Re: ActionListener to display different ImageIcons:

    add values to each button
    That would be easy to do by making a new class that extends the JButton class and putting the needed values in that class. In the action listener method cast the source of the event to your class and be able to access its methods.
    If you don't understand my response, don't ignore it, ask a question.

  20. #20
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,025
    Rep Power
    6

    Default Re: ActionListener to display different ImageIcons:

    It's too difficult to explain something like this piece meal. Have you read about actionListeners and such in the Java tutorials? I have included an example piece of code which demonstrates what Norm and I have been talking about regarding buttons.

    Java Code:
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class ButtonDemo extends JPanel implements ActionListener{
    
       JFrame           frame;
       final static int width  = 500;
       final static int height = 120;
    
       public ButtonDemo() {
          frame = new JFrame();
          frame.setPreferredSize(new Dimension(width, height));
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.add(this);
          frame.pack();
          frame.setLocationRelativeTo(null);
          for (int j = 1; j < 11; j++) {
             MyButton b = new MyButton();
             b.addActionListener(this); // same action listener instance
             b.setText("Button " + j);
             add(b);
          }
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          new ButtonDemo();
       }
    
    
       public void actionPerformed(ActionEvent ae) {
          Object obj = ae.getSource(); // which button was pressed
          if (obj instanceof MyButton) {
             MyButton b = (MyButton)obj;
             b.count++;
             System.out.println(b.getText() + ":  count = " + b.count);
          }
       }
    }
    
    class MyButton extends JButton {
       int count = 0;
       // additional state, methods, and constructor(s) as required
       // can be added here.
    }

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Page 1 of 4 123 ... LastLast

Similar Threads

  1. Comparing ImageIcons
    By nubshat in forum New To Java
    Replies: 4
    Last Post: 03-10-2013, 05:56 AM
  2. Replies: 3
    Last Post: 01-31-2012, 01:01 AM
  3. Replies: 1
    Last Post: 05-31-2010, 09:46 AM
  4. Replies: 1
    Last Post: 03-09-2009, 04:18 AM
  5. Problems with ImageIcons
    By The_L in forum AWT / Swing
    Replies: 2
    Last Post: 10-24-2008, 03:04 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •