Domanda

I have a JFrame that has custom swing component and JTextfield and JButton. JButton has set to default button. When I hit enter in the moment that textfield in focus, button will trigger. but when I hit enter in the moment that custom component in focus button will not trigger.

package org.laki.test;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.FlowLayout;
import javax.swing.JComboBox;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

public class TestFrame extends JFrame {
private JTextField textField;
public TestFrame() {
    getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

    textField = new JTextField();
    getContentPane().add(textField);
    textField.setColumns(10);

    ComboBox comboBox = new ComboBox();
    comboBox.addItem("lakshman");
    comboBox.addItem("tharindu");
    comboBox.addItem("Ishara");
    getContentPane().add(comboBox);

    JButton btnNewButton = new JButton("Test");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            System.out.println("enter is hitting...!!!");
        }
    });
    getContentPane().add(btnNewButton);
    this.rootPane.setDefaultButton(btnNewButton);
}

private class ComboBox extends JComboBox<String>
{
  private static final long serialVersionUID = 10000012219553L;

  @Override
  public void processKeyEvent(final KeyEvent event)
  {
    if ((event.getKeyCode() == KeyEvent.VK_DOWN) ||
        (event.getKeyCode() == KeyEvent.VK_SPACE))
    {
             doSomthing();
    }
    else if(event.getKeyCode() == KeyEvent.VK_ENTER)
    {
        //I added this to capture the enter event
    }
  }
}
public static void main(String[] args) {
    TestFrame testframe = new TestFrame();
    testframe.setSize(300, 400);
    testframe.setVisible(true);
}

 }

I can't remove processKeyEvent method, because it does special event in custom component. what should I do to fire the button when I hit enter in the moment of focus in custom component?

È stato utile?

Soluzione

Your custom component might have overridden JComponent.processKeyEvent() and not let to call it's parents implementation. Check and if not then pass key event to parent using

super.processKeyEvent(event);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top