Page 1 of 2 12 LastLast
Results 1 to 20 of 23
  1. #1
    Rolf83's Avatar
    Rolf83 is offline Member
    Join Date
    Jun 2011
    Location
    Malmö, Sweden
    Posts
    18
    Rep Power
    0

    Default [Solved] JPanel draw graphic on key event

    Hi

    I am trying to adapt some code I found regarding drawing lines on keyevents. I took it from an applet.

    Now I want to do a similar class extended on a JPanel, I have the following code:

    Java Code:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JPanel;
    
    public class drawtest extends JPanel implements KeyListener {
    
    	private static final long serialVersionUID = 1L;
        int width, height;
        Image backbuffer;
        int kx, ky;
        Graphics backg;
    
      public drawtest() {
    
          width = getSize().width;
          height = getSize().height;
          backbuffer = createImage( width, height );
          kx = 10;
          ky = 10;
          backg = backbuffer.getGraphics();
          backg.setColor( Color.black );
           
    
          addKeyListener( this );
      
      
      }
      
      public void paintComponent(Graphics g) {update( g );}
      
    public void keyPressed(KeyEvent e) {
    	
        if (e.getKeyChar()=='d'){kx ++;}
        if (e.getKeyChar()=='s'){ky ++;}
        if (e.getKeyChar()=='a'){kx --;}
        if (e.getKeyChar()=='w'){ky --;}    
        
       // backg.drawImage( img, 0, 0, this );
        backg.drawLine( kx, ky, kx, ky );
        repaint();
        e.consume();
    	
    }
    
    @Override
    public void keyReleased(KeyEvent e) {
    	// TODO Auto-generated method stub
    	
    }
    
    @Override
    public void keyTyped(KeyEvent e) {
    	// TODO Auto-generated method stub
    	
    }
    
    public void update( Graphics g ) {g.drawImage( backbuffer, 0, 0, this );}
    
    
    }
    It seems like in the current construct that the getImage to the variable backbuffer fails...
    Anyone who can get me in the right direction?

    Note: the class is called from another JFrame class...

    -----------------------------------------------------------------------------------------------------------

    I am still new in this posting stuff, but to make it easy I put my rather simplistic solution here, it works for me:

    Java Code:
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JPanel;
    
    public class drawtest extends JPanel implements KeyListener {
    
    private static final long serialVersionUID = 1L;
        int width, height;
        int kx, ky;
    
    
      public drawtest() {
          kx = 10;
          ky = 10;
          addKeyListener( this );
      }
      
      public void paintComponent(Graphics g) {
    	  g.drawLine( kx, ky, kx, ky );
      }
      
    	public void keyPressed(KeyEvent e) {
    
                        if (e.getKeyChar()=='d'){kx ++;}
    	    if (e.getKeyChar()=='s'){ky ++;}
    	    if (e.getKeyChar()=='a'){kx --;}
    	    if (e.getKeyChar()=='w'){ky --;}    
    	    repaint();
    	    e.consume();
    	}
    
    	public void keyReleased(KeyEvent e) {}
    	public void keyTyped(KeyEvent e) {}
    
    }
    Last edited by Rolf83; 06-04-2011 at 12:32 PM. Reason: found a solution

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

    Default

    First, is your method update meant to override the parent class update? Whether the answer is yes or no, I'd highly recommend renaming this method to avoid override conflicts if all you wish to do is draw your image. Second, is your key listener being called? A component requires focus for this to be the case. Add some println's in there to make sure that code is being called.

  3. #3
    Rolf83's Avatar
    Rolf83 is offline Member
    Join Date
    Jun 2011
    Location
    Malmö, Sweden
    Posts
    18
    Rep Power
    0

    Default

    I am not sure what you mean sorry, so I rather explain what I want it to do. What I want is a JPanel sitting in a JFrame where I can via keyevents draw in the JPanel

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,327
    Rep Power
    25

    Default

    the getImage to the variable backbuffer fails
    What error do you get?

    Why are you calling the setColor method outside of the paintComponent method? (use this one vs paint in Swing components)

    You should do all your drawing in the paintComponent method. Do you calculations in the listener and call repaint. after a brief moment, the JVM will call paintComponent where you make your drawing.

    Please add code tags when posting code. See: BB Code List - Java Forums

  5. #5
    Rolf83's Avatar
    Rolf83 is offline Member
    Join Date
    Jun 2011
    Location
    Malmö, Sweden
    Posts
    18
    Rep Power
    0

    Default

    Java Code:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at Matchbox_stickman.drawtest.<init>(drawtest.java:29)
    	at Matchbox_stickman.MainFrame.getJContentPane(MainFrame.java:42)
    	at Matchbox_stickman.MainFrame.getJFrame(MainFrame.java:31)
    	at Matchbox_stickman.MainFrame.access$0(MainFrame.java:24)
    	at Matchbox_stickman.MainFrame$1.run(MainFrame.java:19)
    	at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    	at java.awt.EventQueue.access$000(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$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)

    The setcolor is leftover from a similar code, it can be deleted... as long as it will draw a line on the key events I specified

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,327
    Rep Power
    25

    Default

    at Matchbox_stickman.drawtest.<init>(drawtest.java:29 )
    There is a variable with a null value on line 29.

  7. #7
    Rolf83's Avatar
    Rolf83 is offline Member
    Join Date
    Jun 2011
    Location
    Malmö, Sweden
    Posts
    18
    Rep Power
    0

    Default

    ok I cleaned up the code and removed the setcolor which gave me the nullpointer, now the code looks like this:
    Java Code:
    package Matchbox_stickman;
    
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JPanel;
    
    public class drawtest extends JPanel implements KeyListener {
    
    	private static final long serialVersionUID = 1L;
        int width, height;
        Image backbuffer;
        int kx, ky;
        Image img;
        Graphics backg;
    
      public drawtest() {
          width = getSize().width;
          height = getSize().height;
          backbuffer = createImage( width, height );
          kx = 10;
          ky = 10;
          backg = backbuffer.getGraphics();
          addKeyListener( this );
      }
      
      public void paintComponent(Graphics g) {update( g );}
      
    public void keyPressed(KeyEvent e) {
    	
        if (e.getKeyChar()=='d'){kx ++;}
        if (e.getKeyChar()=='s'){ky ++;}
        if (e.getKeyChar()=='a'){kx --;}
        if (e.getKeyChar()=='w'){ky --;}    
        backg.drawLine( kx, ky, kx, ky );
        repaint();
        e.consume();
    	
    }
    
    public void keyReleased(KeyEvent e) {}
    public void keyTyped(KeyEvent e) {}
    public void update( Graphics g ) {g.drawImage( backbuffer, 0, 0, this );}
    
    }
    and gives the following error:

    Java Code:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at Matchbox_stickman.drawtest.<init>(drawtest.java:24)
    	at Matchbox_stickman.MainFrame.getJContentPane(MainFrame.java:42)
    	at Matchbox_stickman.MainFrame.getJFrame(MainFrame.java:31)
    	at Matchbox_stickman.MainFrame.access$0(MainFrame.java:24)
    	at Matchbox_stickman.MainFrame$1.run(MainFrame.java:19)
    	at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    	at java.awt.EventQueue.access$000(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$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)

  8. #8
    Rolf83's Avatar
    Rolf83 is offline Member
    Join Date
    Jun 2011
    Location
    Malmö, Sweden
    Posts
    18
    Rep Power
    0

    Default

    which is this variable
    backg = backbuffer.getGraphics();

  9. #9
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,453
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Rolf83 View Post
    which is this variable
    backg = backbuffer.getGraphics();
    Your backbuffer variable is null; go backwards in your code and see where you (try to) set it to a sensible value. Sprinkle a couple of System.out.println( ... ) calls in your code and see what actually happens and where it happens. Nullpointer exceptions are easy to find that way.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  10. #10
    Rolf83's Avatar
    Rolf83 is offline Member
    Join Date
    Jun 2011
    Location
    Malmö, Sweden
    Posts
    18
    Rep Power
    0

    Default

    well I did that already, and it happens in the constructor... it simply doesnt get any value

    Java Code:
      public drawtest() {
          width = getSize().width;
          height = getSize().height;
          backbuffer = createImage( width, height );
          kx = 10;
          ky = 10;
          backg = backbuffer.getGraphics();
          addKeyListener( this );
      }
    more specifically:

    Java Code:
          backbuffer = createImage( width, height );

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,327
    Rep Power
    25

    Default

    What are you going to use the variable: backbuffer for?

  12. #12
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,453
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Rolf83 View Post
    well I did that already, and it happens in the constructor... it simply doesnt get any value
    Java Code:
          backbuffer = createImage( width, height );
    So we must conclude that the createImage( ... ) method returns null for some reason. Debug time ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  13. #13
    Rolf83's Avatar
    Rolf83 is offline Member
    Join Date
    Jun 2011
    Location
    Malmö, Sweden
    Posts
    18
    Rep Power
    0

    Default

    @Jos, yeah its in the constructor, so the whole class is constructed wrong, thats why I am asking for help :(

    @Norm, well as I understand this code, from the applet I took it from, the
    Java Code:
     public void paintComponent(Graphics g) {update( g );}
    runs the update function which in turn draws an image based on the constructor and the keyevents whenever they happen, so that everything is passed through the paintComponent function.

    What is different from the applet I took it from, was that everything that I put in the constructor was in the Public void init of the applet... however it seems that the constructor doesnt work the same way as the init in the applet, and it fails to get the height and width as well as the getImage....

  14. #14
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,327
    Rep Power
    25

    Default

    update is a poor choice of method names, as it is used by some Java classes. Better to make it your method by renaming it to myUpdate for example.

    constructor doesnt work the same way as the init in the applet
    Yes, they are different.

  15. #15
    Rolf83's Avatar
    Rolf83 is offline Member
    Join Date
    Jun 2011
    Location
    Malmö, Sweden
    Posts
    18
    Rep Power
    0

    Default

    I guess I will have to construct a whole new JPanel component, and figure out how to update the drawings on keyevents

  16. #16
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,453
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Rolf83 View Post
    @Jos, yeah its in the constructor, so the whole class is constructed wrong, thats why I am asking for help :(
    We agree that it's the createImage( ... ) method that's returning null, right? You have to show us the definition of that method so we can see what's wrong there.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  17. #17
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,327
    Rep Power
    25

    Default

    The Component class has a createImage method. Its doc says:
    The return value may be null if the component is not displayable.

    What are the values for the width and height in its call?

  18. #18
    Rolf83's Avatar
    Rolf83 is offline Member
    Join Date
    Jun 2011
    Location
    Malmö, Sweden
    Posts
    18
    Rep Power
    0

    Default

    well opposite the applet the height and width returns Zero I suspect the
    Java Code:
     
          width = getSize().width;
          height = getSize().height;
    in the constructor reacts differently than it did in the applet I took it from. In the applet it manages to get the values which in turn makes the createImage method work... However here it seems like it cannot identify the height and the width at all.

  19. #19
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,327
    Rep Power
    25

    Default

    Add many versions of this statement to your code to see WHEN there is a height avaiable:
    System.out.println("4gH=" + getHeight());
    Change the '4' here to be unique for each location.
    When you run your program you should see when it gets a value.

    Here a sample of output from a test program:
    1gH=0
    2gH=300
    4gH=0
    3gH=300
    There were no values at locations 1 and 4.

  20. #20
    Rolf83's Avatar
    Rolf83 is offline Member
    Join Date
    Jun 2011
    Location
    Malmö, Sweden
    Posts
    18
    Rep Power
    0

Page 1 of 2 12 LastLast

Similar Threads

  1. Draw on JPanel?
    By PhQ in forum New To Java
    Replies: 2
    Last Post: 07-16-2010, 11:19 PM
  2. Replies: 4
    Last Post: 08-28-2009, 06:50 PM
  3. Replies: 2
    Last Post: 03-22-2009, 01:53 PM
  4. how to draw x-y graph in Jpanel.--not in APPLET.
    By vincent2001@gmail.com in forum New To Java
    Replies: 2
    Last Post: 08-24-2008, 05:01 AM
  5. Draw on JPanel, Help
    By carl in forum Java 2D
    Replies: 1
    Last Post: 07-31-2007, 06:56 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
  •