ChatGUI
im using 2 JEditorPane to transfer text from one to another.
once i have transfered the data i do the following:
JEditorPane.setText(null);
JEditorPane.setCaretPosition(0);
but as you can see from the attached image the return action makes the prompt appear a row down. how can i fix this?
EDIT: does the following seem correct to you? if so then why is caret not positioning itself to chracter 0 position?
private class MyKeyAdapter extends KeyAdapter {
#Override
public void keyPressed(KeyEvent ke) {
int kc = ke.getKeyCode();
if (kc == ke.VK_ENTER) {
System.out.println(editorPaneHistory.getText());
System.out.println(editorPaneHomeText.getText());
editorPaneHistory.setText(editorPaneHomeText.getText());
//JEditorPane - editorPaneHistory
//JEditorPane - editorPaneHomeText
editorPaneHomeText.setText(null);
editorPaneHomeText.setCaretPosition(0);
}
}
}
After your code runs, the JEditorPane is reacting to the enter key in the usual way, by inserting a newline. Try calling ke.consume() to "consume" the event so that the JEditorPane itself doesn't handle it.
Don't use a KeyListener. You should be using a custom Action. This way you can replace the default Action. Read up on Key Bindings.
Related
i have a button that call a method, in this method it call another method to connect to the DB and return results, if results positive, change the labels and make a button ENABLED, and if the results is negative, the Button still disabled
the problem is, i have set in the TF a keytyped event, if someone type something new in it, disable the btnEditar:
public void keyTyped(KeyEvent e) {
btnEditar.setEnabled(false);
btnDeletar.setEnabled(false);
}
i dont want this event "capture" the enter to disable the button
there is a way to do that or i have to think i another logic way?
As others have pointed out, there are other ways to do this besides using a KeyListener. I will respond to your original attempt below. A KeyListener is a functional and easy tool to use for this job.
Use keyPressed instead of keyTyped, and then you'll have a valid key code that you can use to ignore enter presses:
public void keyPressed(KeyEvent e) { // not keyTyped!
if (e.getKeyCode() != KeyEvent.VK_ENTER) {
btnEditar.setEnabled(false);
btnDeletar.setEnabled(false);
}
}
If you insist on using keyTyped for some reason, you won't have a key code available, but you can cover most cases by checking the character for a newline or carriage return:
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() != 13 && e.getKeyChar() != 10) {
btnEditar.setEnabled(false);
btnDeletar.setEnabled(false);
}
}
Use a DocumentListener to listen for changes to the text in the Document. Read the section from the Swing tutorial on How to Write a Document Listener.
I'm working on a JTexfield which sets its own text to the name of the key pressed when it has the focus on the window. I've managed to let it have only a word with the code:
#Override
public void keyReleased(KeyEvent ev) {
if (ev.getKeyCode() != 0) {
keyTrigger = ev.getKeyCode();
txtTrigger.setText(ev.getKeyText(keyTrigger));
}
}
#Override
public void keyTyped(KeyEvent ev) {
txtTrigger.setText("");
}
However it looks horrible when you press special keys like F1--12 or Ctrl because it keeps the last typed non-special key (for example, if you press 'T' and then 'Ctrl', the text in the field keeps being 't' until you release the 'Ctrl' key).
This is the code so far for the JTextField:
txtTrigger = new JTextField();
txtTrigger.setColumns(10);
txtTrigger.addKeyListener(this);
txtTrigger.setBounds(80, 5, 64, 20);
contentPane.add(txtTrigger);
What I want is the field to be empty until you release the key. How can I get the application working this way?
I don't think a editable text field is your best choice here. What I've done in the past is basically faked it.
I've generated a custom component that "looks" like a JTextField and, using my own KeyListener, I've added elements to the view (I did my own "key" renderer, but you could simply have a list of String elements that you can render).
Basically, when keyPressed is triggered, I would add the key code to a list (taking into consideration things like its modifier state). If another key event is triggered with the same key code, then you can ignore it.
When keyReleased is triggered, you can remove that keycode from the active list.
You can add the keylistener to the jframe or many components...
Just make sure that component has the focus.
I'm making an application with java that has a JTextPane. I want to be able to execute some code when the enter key is pressed (or when the user goes to the next line). I've looked on the web and not found a solution. Would it be better to tackle this with C#? If not, how can i register the Enter key in the JTextPane's keyTyped() event? If C# is a good option, how would i do this in C#?
Here is a solution i thought would work...but did not
//Event triggered when a key is typed
private void keyTyped(java.awt.event.KeyEvent evt) {
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
Toolkit.getDefaultToolkit().beep();
System.out.println("ENTER pressed");
}
}
Why the above example does not work is because no matter which key i press, i get a keyCode of 0. I would prefer a solution to this problem in Java but C# would work just as well, maybe better. Also, please try to answer the question with examples and not links(unless you really need to). Thanks!
One solution is to add a key binding on the textpane. e.g.,
JTextPane textPane = new JTextPane();
int condition = JComponent.WHEN_FOCUSED;
InputMap iMap = textPane.getInputMap(condition);
ActionMap aMap = textPane.getActionMap();
String enter = "enter";
iMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), enter);
aMap.put(enter, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("enter pressed");
}
});
This answer is in case anyone ever views this thread I got the same things as Mr. Mohammad Adib.
So instead of using ...
(evt.getKeyCode()==evt.VK_ENTER)
I used ...
(evt.getKeyChar()=='\n')
and the solution worked.
I am looking for ENTER key in the password text field, to launch the login method when ENTER was pressed. The code below will print in the console the keycode. After running the program and typing a few tihngs in the box I discovered for ENTER key it is code 13.
txtPass = new Text(shlLogin, SWT.BORDER | SWT.PASSWORD);
txtPass.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
System.out.println(e.keyCode);
if (e.keyCode == 13) { /* ... Do your stuff ... */ }
}
});
If you are looking for a single key press, you can still be a little lazy and avoid learning new stuff about key bindings, by using this method. The fun begins when adding CTRL+[Letter] shortcuts - but this is for another discussion.
In Java, when a key is pressed such as a letter, how do I prevent the key from outputting the letter that it is assigned to a jTextPane? (Similar to how do game developers suppress the normal functions of the keyboard when a part of their application is in focus).
When KeyEvent.consume() doesn't do the job alone, is there another way?
I'm a fairly novice programmer compared to other people on this board, so please be patient with me. Any examples would be appreciated. I'm eager to learn. Thank you very much.
Assign custom DocumentFilter to the document from the JTextPane. You can intercept the insertString() and skip unnecessary input. It's better than key listener if you should also skip the same chars from pasted content.
This code is just a sample, I hope this will prevent A to Z getting entered , but does not cover all scenarios such as Shift,Ctrl and Alt presses.
JTextPane textPane = new JTextPane();
textPane.addKeyListener(new MyKeyListener());
public class MyKeyListener extends KeyAdapter
{
public void keyPressed(KeyEvent key) {
int i = key.getKeyCode();
if (i >= 65 && i <= 90)
{
((JTextPane)event.getSource()).cancelKey();
}
}
}
The JTextField is a calculator display initialized to zero and it is bad form to display a decimal number with a leading 0 like 0123 or 00123. The numeric buttons (0..9) in a NetBeans Swing JFrame use append() [below] to drop the leading zeros, but the user may prefer the keyboard to a mouse, and non-numeric characters also need to be handled.
private void append(String s) {
if (newEntry) {
newEntry = false;
calcDisplay.setText(s);
} else if (0 != Float.parseFloat(calcDisplay.getText().toString())) {
calcDisplay.setText(calcDisplay.getText().toString() + s);
}
}
You could restrict the characters input to the JTextField by adding a custom KeyListener. Here is a quick example to demonstrate the idea:
myTextField.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!Character.isDigit(c)) {
e.consume(); // Stop the event from propagating.
}
}
});
Of course, you need to consider special keys like Delete and combinations like CTRL-C, so your KeyListener should be more sophisticated. There are probably even freely available utilities to do most of the grunt work for you.
You can do this with DocumentFilter.
(Edit: This answer originally included a ling to a simple complete example program on my now defunct weblog.)