Results 21 to 23 of 23
Thread: JPanel draw graphic on key event
- 06-04-2011, 12:35 AM #21
Ok I feel mighty stupid, but now I managed to solve my problem, ofcourse it was very simple....
This does the trick for me, and I call it from my JFrame like this: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) {} }
Java Code:drawtest drawtest= new drawtest(); jContentPane.add(drawtest, BorderLayout.CENTER); drawtest.setFocusable(true);
Last edited by Rolf83; 06-04-2011 at 12:39 AM.
- 06-04-2011, 04:06 AM #22
Senior Member
- Join Date
- Jul 2009
- Posts
- 1,143
- Rep Power
- 5
I don't have the patience to read through the entire posting so I'll just make one comment and suggestion.
It is obvious you copied the code from an Applet. The code you copied is used for AWT and should not be used for Swing. Mainly, you should never override of invoke the update() method.
For standard Swing painting read the Swing tutorial Lesson: Performing Custom Painting (The Java™ Tutorials > Creating a GUI With JFC/Swing) for working examples and explanations.
- 06-04-2011, 12:26 PM #23
Similar Threads
-
Draw on JPanel?
By PhQ in forum New To JavaReplies: 2Last Post: 07-16-2010, 11:19 PM -
How to draw in a JPanel using Netbeans 6.1 GUI maker
By Gatts79 in forum New To JavaReplies: 4Last Post: 08-28-2009, 06:50 PM -
How to draw a rectangle in the JPanel by inserting the X and Y
By ngansamuel in forum New To JavaReplies: 2Last Post: 03-22-2009, 01:53 PM -
how to draw x-y graph in Jpanel.--not in APPLET.
By vincent2001@gmail.com in forum New To JavaReplies: 2Last Post: 08-24-2008, 05:01 AM -
Draw on JPanel, Help
By carl in forum Java 2DReplies: 1Last Post: 07-31-2007, 06:56 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks