tags:

views:

41

answers:

3

Hello, I created a component based on a JPanel that contains a textfield and a checkbox. Since I use it as component and put it around in other panels I'd like to be able to set a KeyPressed event for the panel. Obiouvsly this doesn't work as the keyPressed events fire for the inner textfield. Is it there a way to propagate them to the JPanel as it was receiving them instead of the textfield? I tried with handleEvent but it doesn't even compile.


Let's clarify the question. I created this big element containing a textfield. Now a want to use this element in another and I want to set the OTHER ONE as the listener. So there is the JPanel between. That's the problem.

A: 

you could add the JPanel derivative to the JTextField as an event listener.

You will need to do some plumbing to get this to work, for example making your JPanel derivative implement KeyListener and implementing the required methods.

pstanton
Views.Components.FieldColorato cannot be cast to java.awt.event.KeyListener... shall I implement the interface??? See clarification
gotch4
yes, see edit...
pstanton
Yes, but if I do so, the JPanel will catch the events, not the element that contains the JPanel, isn't it?
gotch4
maybe your design is confusing you, but whatever object you want to handle the event you can have implement KeyListener and add to JTextField as a listener.
pstanton
A: 

Try adding an ActionListener to the JPanel. The actionPerformed() method in the ActionListener will get called when the user presses key in the JTextfield. You can call getSource() on the event object to determine if the event was fired due to action in JTextField and act accordingly.

sateesh
see clarification
gotch4
+1  A: 

You can use javax.swing.event.EventListenerList in the JPanel containing the JTextField, and create a addKeyListener public method.

import javax.swing.event.EventListenerList;

public static class TestPanel extends JPanel implements KeyListener{  
    private JTextField text;
    private EventListenerList listenerList = new EventListenerList();

    TestPanel(){
        text = new JTextField();
        text.addKeyListener(this);
    }

    public void keyPressed(KeyEvent e){
        //doesn't create a new array, used for performance reasons 
        Object[] listeners = listenerList.getListenerList();
        //Array of pairs listeners[i] is Class, listeners[i + 1] is EventListener
        for (int i = listeners.length - 2; i >= 0; i -= 2) {
            if (listeners[i] == KeyListener.class) {
                ((KeyListener)listeners[i+1]).keyPressed(e);
            }          
        }
    }

    public void addKeyListener(KeyListener l) {
        listenerList.add(KeyListener.class, l);
    }

    public void keyReleased(KeyEvent e){
      //idem as for keyPressed           
    }

    public void keyTyped(KeyEvent e){
      //idem as for keyPressed
    }
}
Taisin