Page 1 of 2 12 LastLast
Results 1 to 20 of 33
  1. #1
    Join Date
    Apr 2011
    Posts
    24
    Rep Power
    0

    Default NullPointerException Error

    I am trying to create a paint program. I am using Eclipse SDK and I keep getting this error:

    Exception in thread "main" java.lang.NullPointerException
    at Button2.setColor(Button2.java:68)
    at Button2.<init>(Button2.java:30)
    at EmptyFrameTest.main(EmptyFrameTest.java:9)

    Here are my three classes:
    1st

    [HTML]
    XML Code:
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    
    public class ColorScribble extends Applet 
    {	
    	private int last_x = 0;
        private int last_y = 0;
        public void actionPreformed(ActionEvent event)
        {
        	
        }
        // called when the user clicks
        public boolean mouseDown(Event e, int x, int y)
        {
            last_x = x; last_y = y;
            return true;
        }
        // called when the mouse moves with the button down
        public boolean mouseDrag(Event e, int x, int y)
        {
        	Graphics2D g2 = (Graphics2D) getGraphics();
        	Button2 test = new Button2();
    	    test.paintComponent(g2, x, y, last_x, last_y);
            last_x = x;
            last_y = y;
            return true;
        }
        
    }
    2nd
    XML Code:
    import javax.swing.JFrame;
    import java.applet.*;
    import javax.swing.JPanel;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JComboBox;	
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.GridLayout;
    	
    public class Button2 extends JFrame
    {
    		public Button2()
    		{
    			
    		class ChoiceListener implements ActionListener 
    		{
    			public void actionPerformed (ActionEvent event) 
    			{
    				setColor();
    			}
    		}	
    			listener = new ChoiceListener();
    			setLayout(new GridLayout(2,2))
                            createControlPanel();
    			setColor();
    			setSize(FRAME_WIDTH, FRAME_HEIGHT);
    		}
    
    		public void createControlPanel()
    		{
    			JPanel facenamePanel = createComboBox();
    				
    			JPanel controlPanel = new JPanel();
    			controlPanel.setLayout(new GridLayout(3,1));
    			controlPanel.add(facenamePanel);
    			add(controlPanel);		
    		}
    		public JPanel createComboBox()
    		{
    			facenameCombo = new JComboBox();
    			facenameCombo.addItem("Black");
    			facenameCombo.addItem("Blue");
    			facenameCombo.addItem("Red");
    			facenameCombo.addItem("Blue");
    			facenameCombo.addItem("Green");
    			facenameCombo.addItem("Orange");
    			facenameCombo.addItem("Pink");
    			facenameCombo.addItem("Yellow");
    			facenameCombo.setEditable(true);
    			facenameCombo.addActionListener(listener);
    			
    			
    			JPanel panel = new JPanel();
    			panel.add(facenameCombo);
    			return panel;
    			
    			
    		}
    		private  Color color;
    		public void setColor()
    		{
    			System.out.println(facenameCombo);
    			String facename = (String) facenameCombo.getSelectedItem();		
    			if (facename.equals("Blue")) color = (Color.BLUE);
    				
    			else if(facename.equals("Black")) color = (Color.BLACK);
    				
    			else if (facename.equals("Blue")) color = (Color.BLUE);
    				
    			else if (facename.equals("Red")) color = (Color.RED);
    				
    			else if (facename.equals("Green")) color = (Color.GREEN);
    				
    			else if (facename.equals("Orange")) color = (Color.ORANGE);
    				
    			else if (facename.equals("Pink")) color = (Color.PINK);
    				
    			else if (facename.equals("Yellow")) color = (Color.YELLOW);
    			
    			}	
    		public void paintComponent(Graphics g, int x, int y, int last_x, int last_y) 
    		{
    		g.setColor(color);	
    		g.drawLine(x, y, last_x, last_y);	
    		}
    		
    		public JComboBox facenameCombo;
    		public String facename;
    		private ActionListener listener;
    		private static final int FRAME_WIDTH = 600;
    		private static final int FRAME_HEIGHT=800;
    		private JPanel panel;
    		private Graphics g;
    		private Graphics2D g2;
    	}
    3rd.

    XML Code:
    import java.awt.GridLayout;
    
    import javax.swing.JFrame;
    
    public class EmptyFrameTest 
    {
    	public static void main (String [ ] args)
    	{
    	JFrame frame = new Button2();
            frame.setSize(1200,700);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	frame.setVisible(true);
            ColorScribble scribble = new ColorScribble();
            scribble.setSize(1100,700);
            frame.add(scribble);
           	}
    }

    Any tips on how to fix?
    Last edited by PorgrammingNoob117; 04-15-2011 at 11:25 PM.

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default

    For future reference, please use the code tags.

    As is your code is barely readable. That being said, the exception points you to the precise location of the problem, eg the setColor method...what could be null in the method? What variables do you try to access in this method? Add some println statements in there to see...(hint: where is the variable facenameCombo initialized?)

    Further, don't call getGraphics - override paintComponent() and do the drawing there.

  3. #3
    Join Date
    Apr 2011
    Posts
    24
    Rep Power
    0

    Default

    Ok so I found out that the facenameCombo box is null and i tried importing facenameCombo into the method parameters but that didn't work... Any suggestions? Also, how do you override paintComponent? (I'm really new to programming fyi)

  4. #4
    ra4king's Avatar
    ra4king is offline Senior Member
    Join Date
    Apr 2011
    Location
    Atlanta, Georgia, US
    Posts
    396
    Rep Power
    4

    Default

    Overriding a method is just like creating a new method, you just declare it as any other method. paintComponent() must be protected or public, it must return nothing (void), and it must accept a Graphics object as parameter.

  5. #5
    Join Date
    Apr 2011
    Posts
    24
    Rep Power
    0

    Default

    Ok so it would be something like this?
    public void protected paintComponent(Graphics g)
    {
    g2.setColor(test.color);
    g2.drawLine(last_x, last_y, x, y);
    }
    And that would go in the color scribble class correct?
    Also I still havn't figured out how to get JComboBox to be not null. Do I have to call upon the method or initate facenameCombo in the constructor or what?

  6. #6
    ra4king's Avatar
    ra4king is offline Senior Member
    Join Date
    Apr 2011
    Location
    Atlanta, Georgia, US
    Posts
    396
    Rep Power
    4

    Default

    If you reread my post, you will see I said public or protected.

    Java Code:
    public void paintComponent(Graphics g) {
    //drawing code
    }

  7. #7
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

  8. #8
    Join Date
    Apr 2011
    Posts
    24
    Rep Power
    0

    Default

    Ok so I got that, but the JComboBox facenameCombo is still null, how do I make it initalized? Adding input via the method parameters doesn't work and calling upon the create facenamCombo method before trying to set the color doesn't work either along with adding facenameCombo = new JComboBox in the setColor method. Any suggestions on how to make facenameCombo unnull?

  9. #9
    ra4king's Avatar
    ra4king is offline Senior Member
    Join Date
    Apr 2011
    Location
    Atlanta, Georgia, US
    Posts
    396
    Rep Power
    4

    Default

    Oh that's because here:
    Java Code:
    public JPanel createComboBox() {
    	[COLOR="Red"]JComboBox facenameCombo = new JComboBox();[/COLOR]  //needs to be "facenameCombo = new JComboBox();"
    	facenameCombo.addItem("Black");
    	facenameCombo.addItem("Blue");
    	facenameCombo.addItem("Red");
    	facenameCombo.addItem("Blue");
    	facenameCombo.addItem("Green");
    	facenameCombo.addItem("Orange");
    	facenameCombo.addItem("Pink");
    	facenameCombo.addItem("Yellow");
    	facenameCombo.setEditable(true);
    	facenameCombo.addActionListener(listener);
    	
    	JPanel panel = new JPanel();
    	panel.add(facenameCombo);
    	return panel;
    }
    You need to remove the first "JComboBox" because doing so does not assign the instance variable, but only assigns this local one the object. This is called variable shadowing, when you create a new variable with the same name as an instance variable.

  10. #10
    Join Date
    Apr 2011
    Posts
    24
    Rep Power
    0

    Default

    That got rid of the error, and it runs well except for the fact that now the color does not change when I use the combo box. It always stays black. I printed facenameCombo and got this: javax.swing.JComboBox[,0,0,0x0,invalid,layout=javax.swing.plaf.metal.Met alComboBoxUI$MetalComboBoxLayoutManager,alignmentX =0.0,alignmentY=0.0,border=,flags=4194632,maximumS ize=,minimumSize=,preferredSize=,isEditable=true,l ightWeightPopupEnabled=true,maximumRowCount=8,sele ctedItemReminder=Black]
    This looks to still be null and my program still doesn't work correctly.... Any more suggestions?

  11. #11
    Join Date
    Apr 2011
    Posts
    24
    Rep Power
    0

    Default

    I found something out, when I click the combo box and choose a different color for 1 line
    the color changes shown by selectedItemReminder=Orange so from what I understand, as soon as I start dragging the mouse on the JFrame, the color resets to black

  12. #12
    ra4king's Avatar
    ra4king is offline Senior Member
    Join Date
    Apr 2011
    Location
    Atlanta, Georgia, US
    Posts
    396
    Rep Power
    4

    Default

    I just saw a problem in your code.
    In your createControlPanel() method, you do "add(controlPanel,BorderLayout.SOUTH)". That is supposed to throw an exception since you're not using a BorderLayout in your JFrame, but a GridLayout. Try just setting that to "add(controlPanel)"

    EDIT: Whoa it looks like you're calling frame.setLayout(new GridLayout(2,2)) after initializing all the components and adding them. That doesn't work well since you've already got a component. You have to set the GridLayout first then add all the components you want.
    Last edited by ra4king; 04-15-2011 at 11:16 PM.

  13. #13
    Join Date
    Apr 2011
    Posts
    24
    Rep Power
    0

    Default

    Ok I only set it to add(controlPanel) and I put setLayout(new GridLayout(2,2)) in the constructor of the Button2 class yet still the code doesn't work..... The variable just keeps resetting because the second after I drag, the println statement for the facenameCombo tells me that it is again black, so 1 pixel is orange or whatever I choose, but the rest is black

    Edit: I updated code.
    Last edited by PorgrammingNoob117; 04-15-2011 at 11:30 PM.

  14. #14
    Join Date
    Apr 2011
    Posts
    24
    Rep Power
    0

    Default

    Wait, could the problem be that the class is creating another JComboBox every time I click/drag the mouse and that is why the variable is changing?

  15. #15
    ra4king's Avatar
    ra4king is offline Senior Member
    Join Date
    Apr 2011
    Location
    Atlanta, Georgia, US
    Posts
    396
    Rep Power
    4

    Default

    What are you dragging? :O

  16. #16
    Join Date
    Apr 2011
    Posts
    24
    Rep Power
    0

    Default

    I am dragging the mouse across the Jframe with the right or left mouse button held down

  17. #17
    ra4king's Avatar
    ra4king is offline Senior Member
    Join Date
    Apr 2011
    Location
    Atlanta, Georgia, US
    Posts
    396
    Rep Power
    4

    Default

    What are you dragging your mouse for?

  18. #18
    Join Date
    Apr 2011
    Posts
    24
    Rep Power
    0

    Default

    I'm dragging the mouse to draw a line, look at the ColorScribble class. I'm using mouse events to draw lines because I'm trying to make a paint program

  19. #19
    Join Date
    Apr 2011
    Posts
    24
    Rep Power
    0

    Red face

    Here I figured out how to fix part of the problem. Here is my new code:
    1st class: (Draws the lines on the JFrame)
    XML Code:
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    
    public class ColorScribble extends Applet 
    {	
    	private int last_x = 0;
        private int last_y = 0;
        public void actionPreformed(ActionEvent event)
        {
        	
        }
        // called when the user clicks
        public boolean mouseDown(Event e, int x, int y)
        {
            last_x = x; last_y = y;
            return true;
        }
        // called when the mouse moves with the button down
        public boolean mouseDrag(Event e, int x, int y)
        {
        	Graphics2D g2 = (Graphics2D) getGraphics();
        	ComboLOLCAT test = new ComboLOLCAT();
        	Color color1 = test.getColor();
        	System.out.println("ColorScribble " + color1);
        	test.paintComponent(g2, x, y, last_x, last_y, color1);
            last_x = x;
            last_y = y;
            return true;
        }
    }
    2nd Class: (Creates the button and supposed to change color)
    XML Code:
    import javax.swing.JFrame;
    import java.applet.*;
    import javax.swing.JPanel;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JComboBox;	
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.GridLayout;
    	
    public class ComboLOLCAT extends JFrame
    {
    		public ComboLOLCAT()
    		{
    			Color color = Color.black;
    		class ChoiceListener implements ActionListener 
    		{
    			public void actionPerformed (ActionEvent event) 
    			{
    				JComboBox cb = (JComboBox) event.getSource();
    				Object newItem = cb.getSelectedItem();
    				setColor((String) newItem);
    			}
    		}	
    			listener = new ChoiceListener();
    			setLayout(new GridLayout(2,2));
    			createControlPanel();
    			setSize(FRAME_WIDTH, FRAME_HEIGHT);
    			System.out.println("Constructor " + color);
    		}
    		
    		public void createControlPanel()
    		{
    			JPanel facenamePanel = createComboBox();
    				
    			JPanel controlPanel = new JPanel();
    			controlPanel.setLayout(new GridLayout(3,1));
    			controlPanel.add(facenamePanel);
    			add(controlPanel);		
    		}
    		public JPanel createComboBox()
    		{
    			facenameCombo = new JComboBox();
    			facenameCombo.addItem("Black");
    			facenameCombo.addItem("Blue");
    			facenameCombo.addItem("Red");
    			facenameCombo.addItem("Blue");
    			facenameCombo.addItem("Green");
    			facenameCombo.addItem("Orange");
    			facenameCombo.addItem("Pink");
    			facenameCombo.addItem("Yellow");
    			facenameCombo.setEditable(true);
    			facenameCombo.addActionListener(listener);
    			
    			JPanel panel = new JPanel();
    			panel.add(facenameCombo);
    			return panel;
    		}
    		public void setColor(String newItem)
    		{		
    			if (newItem.equals("Blue")) color = (Color.BLUE);
    				
    			else if(newItem.equals("Black")) color = (Color.BLACK);
    				
    			else if (newItem.equals("Blue")) color = (Color.BLUE);
    				
    			else if (newItem.equals("Red")) color = (Color.RED);
    				
    			else if (newItem.equals("Green")) color = (Color.GREEN);
    				
    			else if (newItem.equals("Orange")) color = (Color.ORANGE);
    				
    			else if (newItem.equals("Pink")) color = (Color.PINK);
    				
    			else if (newItem.equals("Yellow")) color = (Color.YELLOW);
    			System.out.println("setColor method " + color);
    			}	
    		public Color getColor() 
    		{
    			System.out.println("getColor method " + color);
    			return color;
    		}
    		public void paintComponent(Graphics2D g2, int x, int y, int last_x, int last_y, Color color1) 
    		{
    		System.out.println("The color is " + color);
    		g2.setColor(color1);	
    		g2.drawLine(x, y, last_x, last_y);	
    		}
    		private JComboBox facenameCombo;
    		private String facename;
    		private ActionListener listener;
    		private static final int FRAME_WIDTH = 600;
    		private static final int FRAME_HEIGHT=800;
    		private Graphics g;
    		private Graphics2D g2;
    		private JPanel panel;
    		public Color color;
    }
    3rd Class: (Creates the JFrame and sets a JApplet as the lower half of JFrame)
    XML Code:
    import java.awt.GridLayout;
    
    import javax.swing.JFrame;
    
    public class EmptyFrameTest 
    {
    	public static void main (String [ ] args)
    	{
    		JFrame frame = new ComboLOLCAT();
    		frame.setSize(1200,700);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setVisible(true);
            ColorScribble scribble = new ColorScribble();
            scribble.setSize(1100,700);
            frame.add(scribble);
           	}
    }
    ***If you run this program you'll see that the color is initially set as Black as intended and the Color is set to the correct color whenever a new Item is selected on the ComboBox, but the color is null when accessed by the getColor method. I believe that the class is uninitializing the variable.

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

    Default

    You seem to be doing your graphics wrong as you don't want to get the Graphics object via getGraphics, you don't want to draw directly in an Applet or any root container, and in fact you don't even want to use an Applet or JApplet class. Instead you should do your drawing in the paintComponent method of a JPanel or JComponent and you should read the Swing graphics tutorials before taking another step as you have some assumptions that need to be discarded.

    edit: heck, you've already been told these recommendations by others in your thread above. Why ignore them as they are correct?

Page 1 of 2 12 LastLast

Similar Threads

  1. Need Help with NullPointerException Error
    By waterisgood5 in forum New To Java
    Replies: 2
    Last Post: 11-10-2010, 08:27 PM
  2. NullPointerException error
    By Aggror in forum New To Java
    Replies: 2
    Last Post: 09-29-2010, 03:31 PM
  3. Replies: 1
    Last Post: 12-05-2009, 08:28 AM
  4. awt TextField nullPointerException error
    By k2k in forum AWT / Swing
    Replies: 3
    Last Post: 02-24-2009, 05:24 AM
  5. ERROR: nullPointerException
    By mathias in forum New To Java
    Replies: 1
    Last Post: 08-05-2007, 07:54 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
  •