Reputation: 385
I have editable JCombobox and I added keylistener for combobox editor component. When user press 'Enter key' and if there is no text on the editable combobox I need to display message box using JOptinoPane. I have done necessary code in keyrelease event and it displays message as expected.
Problem is, when we get message box and if user press enter key on 'OK' button of JOptionPane, combobox editor keyevent fires again. Because of this, when user press Enter key on message box, JoptionPane displays continuously.
Any idea how to solve this?
Note that I can't use Action listener for this.
Upvotes: 6
Views: 19406
Reputation: 1
If you are using Netbeans then right click on your combobox and select customize code. add following lines of code
JTextComponent editor = (JTextComponent) Code.getEditor().getEditorComponent();
editor.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent evt) {
if(evt.getKeyCode()==10)
//do your coding here.
}
});
Upvotes: 0
Reputation: 1
Please check the event ascii code by ev.getkeycode()
and check if it is a number or character. If it is neither a number nor a character do nothing.
If it is what you want then do the process.
Upvotes: 0
Reputation: 633
We need to add a key listener on the component that the combo box is using to service the editing.
JTextComponent editor = (JTextComponent) urCombo.getEditor().getEditorComponent();
editor.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent evt) {
// your code
}
});
Hope this code helps.
Upvotes: 4
Reputation: 6782
Please check if this code helps you!!!
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);
Most people find it difficult because of this casting.
Upvotes: 16
Reputation: 608
One option would be to replace the KeySelectionManager interface with your own. You want to replace the JComboBox.KeySelectionManager as it is responsible for taking the inputted char and returns the row number (as an int) which should be selected.
Upvotes: 0
Reputation: 109823
Note that I can't use Action listener for this.
this doesn't make me any sence, then to use ItemListener
Any idea how to solve this?
never to use KeyListener for Swing JComponents
, use (Note that I can't use Action listener for this
.) KeyBindings instead,
notice ENTER key
is implemented for JComboBox
in API
by default, have to override this action from ENTER key pressed
Upvotes: 1