here is the scenario. I've a jtextArea in my project. On keypressed event of jtextArea I check whether pressed key is valid or not by using getKeyChar() method of KeyEvent. If character is valid character(according to my conditions) then it should be inserted otherwise it shouldn't be. I've searched but I couldn't find a way to cancel the event in case character is invalid. In C# this is possible but in java is there any way to cancel the event so that character isn't inserted in jtextarea?
here is some simple code using evt.consume() but it's not working
private void txtArea1KeyPressed(java.awt.event.KeyEvent evt) {
evt.consume();
return;
}
Don't use KeyListeners with text components, There is no guarantee in what order the events may be triggered, so the key may already have updated the underlying Document by the time your listener is notified.
It also doesn't deal with what happens when the user pastes text into the field or the field is update by the program
Instead, use a DocumentFilter, which is doesn't to allow to filter out content been pushed to the components underlying Document model
See Implementing a Document Filter and DocumentFilter Examples
End your event handler with
event.consume()
event.consume() docs
Related
im trying to validate a jtextfield from the keypress and would like it to throw an error message in a jLabel. I am trying to do this with in the code below.
private void jTextField2KeyPressed(java.awt.event.KeyEvent evt) {
}
Can't comment, so i'll answer instead. If you are looking to validate the input of the user as he/she type, you might wanna have a look at javax.swing.text.DocumentFilter.
If you are simply looking to update a JLabel when the user types something, you should add a KeyboardListener to the JTextField. You have to be a bit careful with that tho, as swing doesn't guarantee the order in which listeners are called, meaning that the text may not have updated when the KeyboardListener is invoked.
I know there are many questions on how to focus on a certain text field and so on, but it seems that the issue I am facing is a bit different. So, I have a JTextField which has functionality to autocomplete the text if something that is currently in it has been typed before by the user. I also have a set of buttons that perform insertion of some predefined portion of text into the text field when pressed. The problem is that every time any new text appears in the text field, the autocomplete can trigger and append the text that was used by the user previously. In order to it more friendly, I decided to select the part appended by the autocomplete. All the code is executed in the ED thread. Consider the case when the text field was not in focus :
Both code samples are in the actionPerformed method of the button.
// does not work
if (textField.requestFocusInWindow()) {
textField.getDocument().insertString(...);
}
The insertString() is overriden and has all the logic to select appended string by the autocomplete. So, the only thing I need is that the text field is selected before the string is inserted.
I tried :
// does work
textField.requestFocusInWindow();
SwingUtilities.invokeLater(() -> {
textField.getDocument().insertString(...);
});
The official doc says :
The call to the requestFocusInWindow method initiates the focus transfer, but it does not immediately move the focus ...
This sort of makes sense, since to acquire the focus, a call must be made to the window manager of the clients operating system (that's how I understand that, correct me if I am wrong).
Is the second example working mainly because both events (getting focus and inserting the string) are added to the event queue and the insertion appears after the focus request (actually at the end of the queue) or am I missing something? Is it a valid solution? Can it be done better?
Note: simply adding a listener to the text field ( to react when it is in focus) is not a solution, since the logic I described here is only a part of the whole functionality used.
I'm working on a text editor, and I want to be able to detect the difference between two distinct types of key events: the ones that result in a visible change to the text in my JTextArea (ie, alphanumeric characters, the enter key, symbols), and the ones that don't result in a visible change (directional keys, control keys, shortcuts). I know I can do this with a very verbose switch statement, but is there a less verbose way to do the following?
private void checkKey (java.awt.event.KeyEvent evt) {
if (saved && /*some way to check if the text in the box has changed */) {
editorTitle.setText(currentedit + " (Edited)");
saved = false;
}
}
Don't use a KeyListener. There are better API's to handle these situation.
If you want to know if the data in the text component has changed then you should be using a DocumentListener. It will generate an event whenever text is added or removed.
Read the section from the Swing tutorial on How to Write a DocumentListener for more information.
If you want to know when an arrow key is pressed to invoke some kind of Action then you should be using Key Bindings. This is how all Swing components work. A KeyStroke is bound to an Action.
See Key Bindings for more information and a complete list of the default key bindings of each component.
Shortcuts are also implemented in Swing by using Key Bindings.
We currently have a focus problem with a JTable/JTextEditor in java swing. The JTable has a custom cell editor which is a JTextField.
The issue is when a cell is being edited and contains invalid data, and the user clicks on a JButton, the text field will stop editing and the JButton actionPerformed (clicked) is called. The JTable#setValueAt handles validation so if the data in the JTextField is invalid, the underlying TableModel is not updated.
Ideally, we do not want to let the JButton click occur. Focus should remain with the JTable or the JTextField.
Clicking the button will perform a submit action and close the frame the table is in. As the validation in the TableModel#setValueAt does not update the value, it submits the old value.
Can this be done? I am still fairly new to Swing so I am not aware what to check.
Unfortunately, our code is not straight forward. The UI is constructed from XML in such a way that the button knows nothing about anything else on a form (this is code I have inherited).
In .net you could stop a control losing focus by handling a Validating event and setting a cancel flag. Is there a similar mechanism with Java.
Validating the input after editing has concluded, in setValueAt(), may be inconveniently late. The editor itself can preclude navigation for invalid values, as shown in this example that links to the corresponding tutorial section.
For valid values, you can make the table commit when losing focus:
table.putClientProperty("terminateEditOnFocusLost", true);
Can you try using inputverifier on the editor component, i.e. text field?
When the focus is lost from a component, the lost focus method is called (more reference in http://docs.oracle.com/javase/tutorial/uiswing/events/focuslistener.html). Therefore, you may call the validation method when you lose the focus.
If you do not need to be aware of the specific field being edited, you can also perform validation inside your button and prevent the submission if it is not sucessful.
I'd achieved a similar functionality by overriding the stopCellEditing method in my JTable's CellEditor.
#Override
public boolean stopCellEditing() {
String s = (String) getCellEditorValue();
if (s != null) {
if (!testYourValue()) {
Toolkit.getDefaultToolkit().beep();
return false;
}
}
return super.stopCellEditing();
}
I need to write an arrow listener for my JTextField. if a try with:
public void keyTyped(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
......
}
}
...
This is not good.( I think that JTextField is not responding to a special key listener.)
I know the accepted answer given above will work, but this is not the way it SHOULD be done in Swing. KeyListeners should generally only be used in AWT applications because they don't support a more abstract API.
When using Swing you SHOULD be using Key Bindings. All Swing components use Key Bindings. The Key Bindings blog entry gives some basics on how to use them and contains a link to the Swing tutorial on "How to Use Key Bindings" for more detailed information.
You have to use keyPressed or keyReleased here.
Quoting from SUN's API javadoc:
"Key typed" events are higher-level and generally do not depend on the platform or keyboard layout. They are generated when a Unicode character is entered
Therefore, the keyTyped method will not be called for the arrow keys, as they do not generate Unicode characters.
You can add your own KeyListener via addKeyListener method provided for every java.awt.Component. In your Listener, use keyPressed.
Arrow keys are action keys, you can verify this event via isActionKey:
Returns true if the key firing the event is an action key. Examples of action keys include Cut, Copy, Paste, Page Up, Caps Lock, the arrow and function keys. This information is valid only for key-pressed and key-released events.
See also: http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html