Results 1 to 2 of 2
  1. #1
    brachaalizah is offline Member
    Join Date
    Oct 2010
    Posts
    1
    Rep Power
    0

    Default JButton setColor problems

    On click, the background of the button is supposed to cycle between 6 different colors. Not sure what is going wrong here. It will compile, but give "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" on click.

    Java Code:
    private class ColorButtonListener implements ActionListener
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    			if (colorCounter==0)
    			{
    				button1.setBackground(Color.ORANGE);
    				colorCounter++;
    			}
    			else if (colorCounter==1)
    			{
    				button1.setBackground(Color.YELLOW);
    				colorCounter++;
    			}
    			else if (colorCounter==2)
    			{
    				button1.setBackground(Color.CYAN);
    				colorCounter++;
    			}
    			else if (colorCounter==3)
    			{
    				button1.setBackground(Color.LIGHT_GRAY);
    				colorCounter++;
    			}
    			else if (colorCounter==4)
    			{
    				button1.setBackground(Color.GRAY);
    				colorCounter++;
    			}
    			else if (colorCounter==5)
    			{
    				button1.setBackground(Color.BLACK);
    				colorCounter=0;
    			}
    			
    		}

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You never tell us which line causes the exception, but I'm guessing it's one of the lines where you try to set the color of button1, and that button1 is in fact null. You can check this out by having
    Java Code:
    if (colorCounter==0) {
       System.out.println("button1 is null: " + (button1 == null));
       button1.setBackground(Color.ORANGE);
       colorCounter++;
    }

    And then if it is in fact null, go back and try to see where you think that you are initializing this JButton.

Similar Threads

  1. JTextField setColor()
    By Insomniac Riot in forum AWT / Swing
    Replies: 2
    Last Post: 10-22-2010, 09:53 PM
  2. setColor() gives a null error on execution
    By gothrog in forum AWT / Swing
    Replies: 10
    Last Post: 09-01-2010, 03:06 AM
  3. Replies: 2
    Last Post: 04-21-2010, 07:34 PM
  4. Problems with ActionEvent for JButton
    By TrueBear in forum AWT / Swing
    Replies: 1
    Last Post: 08-24-2009, 05:26 PM
  5. Problems with jButton ActionPerformed
    By susan in forum AWT / Swing
    Replies: 3
    Last Post: 08-07-2007, 05:19 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
  •