Search code examples
javaswingactionlistenerjtextfieldkeylistener

How to trigger inner class event handler inside an event handler (JAVA)


I have a JTextField with a KeyListener hanging on to it. Inside the keyPressed I check to see if the key being pressed is enter. After this I would like to call a different event handler inside an inner class (inner class only contains this handler).

This is what I have, but evidently: new handler() doesn't seem to launch the inner class handler.

Key eventhandler:

public void keyPressed(KeyEvent k) {
    if(k.getKeyCode()==KeyEvent.VK_ENTER){
         new handler();
    }
}

Inner class eventhandler:

public class handler implements ActionListener{
public void actionPerformed(ActionEvent e) {
    int red = Integer.parseInt(roodT.getText());
    int groen = Integer.parseInt(groenT.getText());
    int blauw = Integer.parseInt(blauwT.getText());
    if(red>255){
        red = 255;
    } else if (red < 0){
        red = 0;
    }
    if(groen>255){
        groen = 255;
    } else if (groen < 0){
        groen = 0;
    }
    if(blauw>255){
        blauw = 255;
    } else if (blauw < 0){
        blauw = 0;
    }
    inhoud.setBackground(new Color(red, groen, blauw));
}

}

This is my first time posting here so sorry if this question isn't formatted correctly.


Solution

  • For a JTextField you can directly add your handler to it:

    JTextField someField = new JTextField(20);
    someField.addActionListener(new handler());
    

    ActionListener is automatically triggered upon ENTER-pressed.

    For all JTextComponent, instead of using KeyListener, use DocumentListener and DocumentFilter.

    For other JComponent use Swing KeyBindings.

    In all cases, stay away from KeyListener which is a low-level API.