Sunday, June 16, 2013

Casting JComboBox to JTextComponent to get Key Release event


JFrame frame = new JFrame("Welcome!!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JComboBox cmb = new JComboBox();
cmb.setEditable(true);
cmb.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {

    @Override
    public void keyReleased(KeyEvent event) {
        if (event.getKeyChar() == KeyEvent.VK_ENTER) {
            if (((JTextComponent) ((JComboBox) ((Component) event
                    .getSource()).getParent()).getEditor()
                    .getEditorComponent()).getText().isEmpty())
                System.out.println("please dont make me blank");
        }
    }
});
frame.add(cmb);

frame.setLocationRelativeTo(null);
frame.setSize(300, 50);
frame.setVisible(true);

No comments:

Post a Comment