开发者

How to propogate Swing events from a inner component to a container?

开发者 https://www.devze.com 2022-12-18 18:32 出处:网络
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 p

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 开发者_如何学Ctextfield. 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.


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
    }
}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消