Results 1 to 13 of 13
  1. #1
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    93
    Rep Power
    0

    Default Implementing ActionListener on image button

    Is there something special about this? I would think not, however all of the buttons in my application work except those with images.

    Here's an example of one:

    Java Code:
    // Class #1
    // All components defined as private initially, used in initComponents() later to build GUI
    private JButton btnRock = new JButton();
    /** Create the frame. **/
    	public GameView() {
    		initComponents(); // Initialize components
    	} // End of GameView Method
    	public void initComponents() {
    // ROCK BUTTON
    		btnRock = (JButton) mainController.createIcon("rock");
    		btnRock.setForeground(new Color(0, 0, 0));
    		btnRock.setBounds(12, 34, 97, 67);
    		pnlGame.add(btnRock);	
    }
    // ACTION LISTENERS
    	public void addRockListener(ActionListener listen){
    		btnRock.addActionListener(listen);
    	}
    // Class #2 - controller
    public MainController(LoginView login, GameView game, WinnerDialog dialog) {
    		this.login = login;
    		this.game = game;
    		this.dialog = dialog;
    
    RockButtonListener rockListener = new RockButtonListener(); // RPSLS game pieces
    		game.addRockListener(rockListener);
    }
    // ....
    public class RockButtonListener implements ActionListener {
    		public void actionPerformed(ActionEvent e) {
    			game.disableButtons("rock");
    			btn = "rock";
    		}
    	} // End of RockButtonListener()
    // METHOD FOR IMAGE CONTROL
        public Component createIcon(String description) {
    		ImageIcon icon = null;
    		Component component = null;
    		String resource = "";
    		// Switch statement to retrieve filepath from enum map
    		switch(description.toLowerCase()){
    			case "rock":
    				resource = ImagesEnum.ROCK.getFilePath();
    				break;
    			case "paper":
    				resource = ImagesEnum.PAPER.getFilePath();
    				break;
    			case "scissors":
    				resource = ImagesEnum.SCISSORS.getFilePath();
    				break;		
    			case "lizard":
    				resource = ImagesEnum.LIZARD.getFilePath();
    				break;
    			case "spock":
    				resource = ImagesEnum.SPOCK.getFilePath();
    				break;
    		} // end of switch statement
                   icon = new ImageIcon(this.getClass().getResource(resource));
                   component = new JButton();
    		((JButton) component).setIcon(icon);
    		return component;
    	} // End of createIcon() Method
    Anyone see something here I'm missing? I've been stared at this for a couple hours last night, I just don't get it.
    Last edited by mallorz; 11-29-2014 at 12:39 AM.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,033
    Rep Power
    6

    Default Re: Implementing ActionListener on image button

    You haven't explained what the problem is. Your code is also confusing because you are casting the return of a createIcon to JButton. And what does game.disableButtons do? You need to submit a Short, Self Contained, Correct Example to demonstrate the problem.

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

  3. #3
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    93
    Rep Power
    0

    Default Re: Implementing ActionListener on image button

    Quote Originally Posted by jim829 View Post
    You haven't explained what the problem is. Your code is also confusing because you are casting the return of a createIcon to JButton. And what does game.disableButtons do? You need to submit a Short, Self Contained, Correct Example to demonstrate the problem.

    Regards,
    Jim
    Jim - Thank you for the reply. I tried to only include the code relative to the ActionListener and creation of the buttons. All methods work, the createIcon method returns an image to thebutton. Game.disableButtons is a call to the other class (from within the controller) that disables all the image buttons other than that selected (there are 5). This one doesn't work properly, because the ActionListeners assigned to the image buttons don't seem to be responding at all. I will try to adjust the code above to include more of the guts.

    Please let me know if that is better.

    Again, the problem here - the ActionListener assigned to the button with an image on it does not trigger the associated code within the appropriate method.
    Last edited by mallorz; 11-29-2014 at 12:31 AM.

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

    Default Re: Implementing ActionListener on image button

    One thing I notice is that you assign component as a null in the method createIcon. But you don't change it and return the same component. Also, you can't cast an arbitrary component to a specific type. You can only cast an instance of JButton or one of its subclasses to JButton. I would think this would generate some compiler errors.

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

  5. #5
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    93
    Rep Power
    0

    Default Re: Implementing ActionListener on image button

    Quote Originally Posted by jim829 View Post
    One thing I notice is that you assign component as a null in the method createIcon. But you don't change it and return the same component. Also, you can't cast an arbitrary component to a specific type. You can only cast an instance of JButton or one of its subclasses to JButton. I would think this would generate some compiler errors.

    Regards,
    Jim
    That's probably just me messing up the parsing of the code to create a short example for the post. I fixed it, sorry about that. The images work fine - the ActionListener does not.

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

    Default Re: Implementing ActionListener on image button

    If you place print statements in the actionListener do they execute when you press the button? If so, then the problem may be in the disableButtons method. Putting print statements in some of the other methods you create can also help verify they are being called when expected.

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

  7. #7
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    93
    Rep Power
    0

    Default Re: Implementing ActionListener on image button

    Quote Originally Posted by jim829 View Post
    If you place print statements in the actionListener do they execute when you press the button? If so, then the problem may be in the disableButtons method. Putting print statements in some of the other methods you create can also help verify they are being called when expected.

    Regards,
    Jim
    Jim, that was the first thing I tried. I don't understand it. Especially since when I compare the code/syntax from those buttons to the others they are identical. I've also tried running my program in Debug, but it just skips past those and faults with a NullPointerException (do to the code not being executed from the image button being pressed).

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,033
    Rep Power
    6

    Default Re: Implementing ActionListener on image button

    I also just noticed that your first statement creates a JButton. But then when you init components, it overwrites it. It might help if you showed the code leading up to where the NPE was thrown and the actual exception trace.

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

  9. #9
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    93
    Rep Power
    0

    Default Re: Implementing ActionListener on image button

    Quote Originally Posted by jim829 View Post
    I also just noticed that your first statement creates a JButton. But then when you init components, it overwrites it. It might help if you showed the code leading up to where the NPE was thrown and the actual exception trace.

    Regards,
    Jim
    I just changed that, didn't make a difference in this particular issue but perhaps is bad coding practice.

    Here's a description of the program: A user plays "Rock, Paper, Scissors, Lizard, Spock" against the computer. Once the user makes their selection by clicking an image button, all other image buttons get disabled (disableButtons method). The value selected gets passed in and the non-matching buttons get disabled. The user then clicks a 'Play' button for the comparing and such.

    Java Code:
    public MainController(LoginView login, GameView game, WinnerDialog dialog) {
    		this.login = login;
    		this.game = game;
    		this.dialog = dialog;
    		
    		LoginButtonListener loginListener = new LoginButtonListener(); // LoginView
    		login.addLoginListener(loginListener);
    		PlayButtonListener playListener = new PlayButtonListener(); // GameView
    		game.addPlayListener(playListener);
    		RockButtonListener rockListener = new RockButtonListener(); // RPSLS game pieces
    		game.addRockListener(rockListener);
    		PaperButtonListener paperListener = new PaperButtonListener(); 
    		game.addRockListener(paperListener);
    		ScissorsButtonListener scissorsListener = new ScissorsButtonListener(); 
    		game.addRockListener(scissorsListener);
    		LizardButtonListener lizardListener = new LizardButtonListener(); 
    		game.addRockListener(lizardListener);
    		SpockButtonListener spockListener = new SpockButtonListener(); 
    		game.addRockListener(spockListener);
    		QuitButtonListener quitListener = new QuitButtonListener(); // GameView & WinnerDialog
    		game.addQuitListener(quitListener);
    		dialog.addQuitListener(quitListener);
    		BackButtonListener backListener = new BackButtonListener(); // Winner Dialog
    		dialog.addBackListener(backListener);
    	} // End of MainController() Method
    // ROCK BUTTON  (imagine one for each)
    	public class RockButtonListener implements ActionListener {
    		public void actionPerformed(ActionEvent e) {
    			game.disableButtons("rock");
    			btn = "rock";
    		}
    	} // End of RockButtonListener() 
    // PLAY BUTTON
    	public class PlayButtonListener implements ActionListener {
    		public void actionPerformed(ActionEvent e) {
    			game.disableButtons(btn); // NullPointException (If "rock" is passed in, buttons paper/scissors/lizard/spock get disabled (shown below))
    			Boolean valid = validPlay(Double.parseDouble(game.getBet()));
    			if (valid) {
    				gameController.setUserBet(Double.parseDouble(game.getBet()));
    				action(btn);
    			}
    			else
    				displayMessage("Funds not available. Change your bet or quit the game.");
    		}
    	} // End of PlayButtonListener()
    
    // Back in Class #1
    // BUTTON CONTROL
    	public void disableButtons(String x) {
    		switch(x) {
    			case "rock":
    				btnPaper.setEnabled(false);
    				btnScissors.setEnabled(false);
    				btnLizard.setEnabled(false);
    				btnSpock.setEnabled(false);
    				break;
    			case "paper":
    				btnRock.setEnabled(false);
    				btnScissors.setEnabled(false);
    				btnLizard.setEnabled(false);
    				btnSpock.setEnabled(false);
    				break;
    			case "scissors":
    				btnRock.setEnabled(false);
    				btnPaper.setEnabled(false);
    				btnLizard.setEnabled(false);
    				btnSpock.setEnabled(false);
    				break;
    			case "lizard":
    				btnRock.setEnabled(false);
    				btnPaper.setEnabled(false);
    				btnScissors.setEnabled(false);
    				btnSpock.setEnabled(false);
    				break;
    			case "spock":
    				btnRock.setEnabled(false);
    				btnPaper.setEnabled(false);
    				btnScissors.setEnabled(false);
    				btnLizard.setEnabled(false);
    				break;
    		}
    	} // End of disableButtons()
    Stack Trace:
    Java Code:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at edu.witc.RPSLS.view.GameView.disableButtons(GameView.java:283)
    	at edu.witc.RPSLS.controller.MainController$PlayButtonListener.actionPerformed(MainController.java:127)
    	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    	at java.awt.Component.processMouseEvent(Unknown Source)
    	at javax.swing.JComponent.processMouseEvent(Unknown Source)
    	at java.awt.Component.processEvent(Unknown Source)
    	at java.awt.Container.processEvent(Unknown Source)
    	at java.awt.Component.dispatchEventImpl(Unknown Source)
    	at java.awt.Container.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    	at java.awt.Container.dispatchEventImpl(Unknown Source)
    	at java.awt.Window.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    	at java.awt.EventQueue.access$200(Unknown Source)
    	at java.awt.EventQueue$3.run(Unknown Source)
    	at java.awt.EventQueue$3.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue$4.run(Unknown Source)
    	at java.awt.EventQueue$4.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue.dispatchEvent(Unknown Source)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.run(Unknown Source)

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

    Default Re: Implementing ActionListener on image button

    What is the value of btn in PlayButtonListener before you call game.disableButtons? It may be null which could cause the problem. It seems to be that you are trying to disable the btn before it is initialized.

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

  11. #11
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    93
    Rep Power
    0

    Default Re: Implementing ActionListener on image button

    Quote Originally Posted by jim829 View Post
    What is the value of btn in PlayButtonListener before you call game.disableButtons? It may be null which could cause the problem. It seems to be that you are trying to disable the btn before it is initialized.

    Regards,
    Jim
    I assign it at the very top of mainController as null. I actually just added it though, so it couldn't be the source of the issue. Interesting idea though.

    I got rid of the 'null' assignment and just declared the String.

    It is showing as null though because "btn" gets assigned a value in RockActionListener() for example, which isn't getting triggered.
    Last edited by mallorz; 11-29-2014 at 01:44 AM.

  12. #12
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    93
    Rep Power
    0

    Default Re: Implementing ActionListener on image button

    So here are some things I tried this morning.

    First, I deleted all the button objects in the code and re-created them (I'm using WindowBuilder). No difference.

    Next, I thought maybe the ActionListers were not getting added because the call to the mainController is in a difference class which passes in the LoginView, GameView, and WinnerDialog. Originally, in the GameView where the buttons are created, I simply created an instance of the MainController (private MainController mainController = new MainController(); ) to reference in the code (I have an empty constructor to MainController() as well. I thought maybe the ActionListeners were not getting assigned because there was no code in that constructor, so I altered it to pass in the GameView and moved the ActionListeners to that.

    Example:
    In GameView
    Java Code:
    private MainController mainController = new MainController(this.getView());
    In MainController
    Java Code:
    public MainController(GameView game) {
    		PlayButtonListener playListener = new PlayButtonListener(); // GameView
    		game.addPlayListener(playListener);
    		RockButtonListener rockListener = new RockButtonListener(); // RPSLS game pieces
    		game.addRockListener(rockListener);
    		PaperButtonListener paperListener = new PaperButtonListener(); 
    		game.addRockListener(paperListener);
    		ScissorsButtonListener scissorsListener = new ScissorsButtonListener(); 
    		game.addRockListener(scissorsListener);
    		LizardButtonListener lizardListener = new LizardButtonListener(); 
    		game.addRockListener(lizardListener);
    		SpockButtonListener spockListener = new SpockButtonListener(); 
    		game.addRockListener(spockListener);
    	}
    	
    	public MainController(LoginView login, GameView game, WinnerDialog dialog) {
    		this.login = login;
    		this.game = game;
    		this.dialog = dialog;
    		
    		LoginButtonListener loginListener = new LoginButtonListener(); // LoginView
    		login.addLoginListener(loginListener);
    		
    		QuitButtonListener quitListener = new QuitButtonListener(); // GameView & WinnerDialog
    		game.addQuitListener(quitListener);
    		dialog.addQuitListener(quitListener);
    		BackButtonListener backListener = new BackButtonListener(); // Winner Dialog
    		dialog.addBackListener(backListener);
    	} // End of MainController() Method
    With the code like that, I get NullPointerExceptions where the ActionListers are added in the GameView.

    Java Code:
    // ACTION LISTENERS
    	public void addPlayListener(ActionListener listen) {
    		btnKeepPlaying.addActionListener(listen);
    	}
    	
    	public void addQuitListener(ActionListener listen) {
    		btnQuit.addActionListener(listen);
    	}
    	
    	public void addRockListener(ActionListener listen){ // Null Pointer Exception
    		btnRock.addActionListener(listen);
    	}
    	
    	public void addPaperListener(ActionListener listen){
    		btnPaper.addActionListener(listen);
    	}
    	
    	public void addScissorsListener(ActionListener listen){
    		btnScissors.addActionListener(listen);
    	}
    	
    	public void addLizardListener(ActionListener listen){
    		btnLizard.addActionListener(listen);
    	}
    	
    	public void addSpockListener(ActionListener listen){
    		btnSpock.addActionListener(listen);
    	}
    After playing with this and thinking about it, I decided that this could not be the reason and put it all back to how it was initially coded because the Play and Quit buttons from the GameView respond to the ActionListers just fine.

    Hopefully that all makes sense. Anyone else got ideas? I'm using Eclipse; haven't said that yet.

  13. #13
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    93
    Rep Power
    0

    Default Re: Implementing ActionListener on image button

    Found it!!

    If you guys look at the code above where I add my ActionListeners in the MainController method, instead of using the "add[x]Listener" method in my GameView class, they are ALL "addRockListener".

    Wow. Two days on this and I've looked and looked at that! I guess it's easy to get lost in text. I feel like a grade A moron.

    Jim - Thanks for your replies.
    Last edited by mallorz; 11-30-2014 at 12:27 AM.

Similar Threads

  1. Problem implementing ActionListener??
    By ryanonnfire54 in forum New To Java
    Replies: 3
    Last Post: 11-16-2010, 05:39 PM
  2. Problem w/ ActionListener on a button
    By qwertyuiop23 in forum AWT / Swing
    Replies: 2
    Last Post: 11-02-2009, 07:25 AM
  3. Replies: 8
    Last Post: 03-09-2009, 12:32 PM
  4. implementing a button instead.
    By birdofprey in forum AWT / Swing
    Replies: 3
    Last Post: 02-18-2008, 04:21 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
  •