Results 1 to 17 of 17
- 07-26-2011, 05:29 PM #1
Member
- Join Date
- Jul 2011
- Location
- Bloomington, IN
- Posts
- 9
- Rep Power
- 0
Help: adding keylistener to a thread
Hi everyone, I'm working on a simple Java applet program. By default, the program will let a rectangle move from left to right in a continuous process. I implemented this feature by using a thread. What I want to do is: when the rectangle is moving from left to right, the program can receive the keyboard input and change the variable "active" and then let the rectangle change its moving direction to from up to down. My problem is I don't know how to add the keylistener to the program. Below (also attachment) is the existing code. Thanks in advance for your help!
Java Code:/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package test; import java.awt.*; import javax.swing.*; import java.awt.event.*; /** * * */ public class TestJPanel extends JPanel implements Runnable{ private boolean active; private Rectangle rect; public TestJPanel() { super(); this.rect = new Rectangle( 100, 100, 50, 100); this.active = false; this.setFocusable( true); return; } @Override public void paint( Graphics g) { super.paint(g); g.drawRect( this.rect.x, this.rect.y, this.rect.width, this.rect.height); return; } public void start() { Thread thread = new Thread( this); thread.start(); } @Override public void run() { for (int i = 0; i < 100; i++) { this.move(); this.repaint(); try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } } } public void move() { if( this.active == false) this.rect.setLocation( this.rect.x + 2, this.rect.y); else this.rect.setLocation( this.rect.x, this.rect.y + 2); return; } }Last edited by Hooiser; 07-26-2011 at 06:01 PM. Reason: change code format
- 07-26-2011, 05:51 PM #2
Please post your code in the forum. Be sure to wrap it in code tags. Use the # icon above the input box.
You add a listener to a component by creating a class that implements the listener, creating an instance of that class and calling the components add....Listener method with that instance as an argument.
Do a Search here on the forum for the type of listener you are working with for code samples.
- 07-26-2011, 06:03 PM #3
Member
- Join Date
- Jul 2011
- Location
- Bloomington, IN
- Posts
- 9
- Rep Power
- 0
Thanks for your reply! I have changed the code format.
- 07-26-2011, 06:24 PM #4
Next you are you going to try adding the listener?
- 07-26-2011, 06:41 PM #5
Member
- Join Date
- Jul 2011
- Location
- Bloomington, IN
- Posts
- 9
- Rep Power
- 0
I tried the KeyListener, here are the codes I wrote:
KeyListener:
Java Code:/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package test; import java.awt.event.*; /** * * */ public class InputListener implements KeyListener{ TestJPanel testJPanel; public InputListener( TestJPanel testJPanel) { super(); this.testJPanel = testJPanel; return; } @Override public void keyPressed( KeyEvent e) { System.out.println("pressed"); this.testJPanel.setActive( true); return; } @Override public void keyReleased( KeyEvent e) { System.out.println("released"); } @Override public void keyTyped( KeyEvent e) { } }
Now, add the InputListener to TestJPanel, and TestJPanel becomes:
When I ran the code, when the rectangle was moving from left to right, I input from the keyboard, then, there was nothing happened. I even didn't get the message "pressed" from InputListener.keyPressed( KeyEvent e). Which part do you think I was missing? Thanks!Java Code:/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package test; import java.awt.*; import javax.swing.*; /** * * */ public class TestJPanel extends JPanel implements Runnable{ public boolean active; private Rectangle rect; public TestJPanel() { super(); this.rect = new Rectangle( 100, 100, 50, 100); this.active = false; this.setFocusable( true); InputListener listener = new InputListener( this); this.addKeyListener( listener); return; } @Override public void paint( Graphics g) { super.paint(g); g.drawRect( this.rect.x, this.rect.y, this.rect.width, this.rect.height); return; } public void start() { Thread thread = new Thread( this); thread.start(); } @Override public void run() { for (int i = 0; i < 100; i++) { this.move(); this.repaint(); try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } } } public void move() { if( this.active == false) this.rect.setLocation( this.rect.x + 2, this.rect.y); else this.rect.setLocation( this.rect.x, this.rect.y + 2); return; } public void setActive( boolean active) { this.active = active; return; } }
- 07-26-2011, 06:50 PM #6
You haven't posted the code that tests your classes.
How are you testing them?
-
You set the JPanel as focusable, but you may need to request focus in window, though I'm not 100% sure on this. Also, don't override the JPanel's paint method but rather it's paintComponent method. And call super.paintComponent as the first method call of your override.
- 07-26-2011, 07:02 PM #8
Member
- Join Date
- Jul 2011
- Location
- Bloomington, IN
- Posts
- 9
- Rep Power
- 0
I'm using NetBeans. Most of the codes are generated by NetBeans to create a user interface. I add a line in function "void jButton1ActionPerformed()" to call "TestJPanel.start()"
Java Code:/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * TestJApplet.java * * Created on Jul 26, 2011, 12:56:12 PM */ package test; /** * * @author */ public class TestJApplet extends javax.swing.JApplet { /** Initializes the applet TestJApplet */ public void init() { try { java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() { initComponents(); } }); } catch (Exception ex) { ex.printStackTrace(); } } //below is generated by NetBeans /** This method is called from within the init() method to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jPanel1 = new TestJPanel(); jPanel2 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Paint Panel", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 638, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 452, Short.MAX_VALUE) ); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Control Panel", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N jButton1.setText("Start"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jButton1) .addContainerGap(104, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jButton1) .addContainerGap(418, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); }// </editor-fold> //here I called TestJPanel.start() to start the thread private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: this.jPanel1.start(); return; } // Variables declaration - do not modify private javax.swing.JButton jButton1; private TestJPanel jPanel1; private javax.swing.JPanel jPanel2; // End of variables declaration }
- 07-26-2011, 07:06 PM #9
Member
- Join Date
- Jul 2011
- Location
- Bloomington, IN
- Posts
- 9
- Rep Power
- 0
Thanks for your reply, Fubarable! If I need to request focus in window, what should I do? In the thread I replied to Norm, I posted the code for JFrame. Please let me know which code should I add to the JFrame.
- 07-26-2011, 07:26 PM #10
I get messages printed and the box moving when I execute it in AppletViewer.
- 07-26-2011, 07:44 PM #11
Member
- Join Date
- Jul 2011
- Location
- Bloomington, IN
- Posts
- 9
- Rep Power
- 0
Did you input from keyboard before pressing the "start" button? Or you pressed the "start" button and then input from the keyboard? My situation is: before pressing the "start" button, I can get messages printed and the keylistener works properly. But If I press the "start" button firstly, then the keylistener cannot listen any input from keyboard.
- 07-26-2011, 08:16 PM #12
Try adding a FocusListener to the panel and see what happens.
- 07-26-2011, 09:23 PM #13
Member
- Join Date
- Jul 2011
- Location
- Bloomington, IN
- Posts
- 9
- Rep Power
- 0
Hi Norm, I tried adding a FocusListener to TestJPanel. The FocusListener looks like this:
When I start the applet, "focus gained" will be shown on the console. The keylistener works fine at that time. However, if I pressed the start button, the "focus lost" will be shown and the keylistener will not work anymore.Java Code:package test; import java.awt.event.*; /** * * */ public class InputFocusListener implements FocusListener{ @Override public void focusGained( FocusEvent e) { System.out.println("focus gained"); } @Override public void focusLost( FocusEvent e) { System.out.println("focus lost"); } }
- 07-26-2011, 09:26 PM #14
If a component loses focus, how can you give it back?the "focus lost" will be shown and the keylistener will not work anymore.
Who has focus when you press the button? The display shows it.
You can Press the Tab key to move the focus.
- 07-26-2011, 09:34 PM #15
Member
- Join Date
- Jul 2011
- Location
- Bloomington, IN
- Posts
- 9
- Rep Power
- 0
- 07-26-2011, 10:06 PM #16
Another way could be to request focus. See post#7
- 07-26-2011, 10:17 PM #17
Member
- Join Date
- Jul 2011
- Location
- Bloomington, IN
- Posts
- 9
- Rep Power
- 0
Similar Threads
-
Adding keyListener to a 2D object.
By Guy in forum New To JavaReplies: 2Last Post: 07-24-2011, 08:20 PM -
adding keylistener
By natdizzle in forum AWT / SwingReplies: 2Last Post: 02-02-2011, 01:22 AM -
Help adding a keylistener to a paint class
By Phill Phan in forum New To JavaReplies: 3Last Post: 01-20-2011, 09:28 PM -
Adding a KeyListener to a JFrame with buttons.
By jamhead in forum AWT / SwingReplies: 1Last Post: 12-11-2010, 07:29 PM -
Help me in adding keylistener
By kumarv75 in forum CLDC and MIDPReplies: 0Last Post: 06-22-2010, 07:10 AM


LinkBack URL
About LinkBacks
Reply With Quote


Bookmarks