Get a Key from Jtextarea

Get a key from JTextArea

for listening changes into JTextComponent is there DocumentListener, if you have to need control over inputed Char, sings, whitespace chars or word(s) you have to implements DocumentFilter

notice for Chars reservated by programing language(s) you have to use double escapes,

\\( instead of (

or

\\{ instead of {

otherwise you get

Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: 
Illegal repetition

for example

import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

public class TextAreaTest extends JFrame {

private static final long serialVersionUID = 1L;
private JTextArea textArea;

public TextAreaTest() {
textArea = new JTextArea();
textArea.setPreferredSize(new Dimension(60, 32));
textArea.setOpaque(true);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
((AbstractDocument) textArea.getDocument()).setDocumentFilter(new DocumentFilter() {

@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
string = string.replaceAll("\\{", "\\{}");
super.insertString(fb, offset, string, attr);
}

@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
text = text.replaceAll("\\{", "\\{}");
//TODO must do something here
super.replace(fb, offset, length, text, attrs);
}
});

textArea.getDocument().addDocumentListener(new DocumentListener() {

@Override
public void changedUpdate(DocumentEvent e) {
update(e);
}

@Override
public void insertUpdate(DocumentEvent e) {
update(e);
}

@Override
public void removeUpdate(DocumentEvent e) {
update(e);
}

private void update(DocumentEvent e) {
List<String> lines = getLines(textArea);
String lastLine = lines.get(lines.size() - 1);
int tabbedTextWidth = Utilities.getTabbedTextWidth(new Segment(
lastLine.toCharArray(), 0, lastLine.length()), textArea.getFontMetrics(textArea.getFont()), 0, null, 0);
int lineHeight = getLineHeight(textArea);
if (lines.size() * lineHeight > textArea.getHeight() || tabbedTextWidth > textArea.getWidth()) {
System.out.println("Too big! Should refuse the update!");
}
}
});

getContentPane().add(textArea);
}

private static List<String> getLines(JTextArea textArea) {
int lineHeight = getLineHeight(textArea);
List<String> list = new ArrayList<String>();
for (int num = 0;; num++) {
int i = textArea.viewToModel(new Point(0, num * lineHeight));
int j = textArea.viewToModel(new Point(0, (num + 1) * lineHeight));
if (i == 0 && j == 0) {
continue;
}
if (textArea.getDocument().getLength() == i && i == j) {
break;
}
String s = removeTrailingNewLine(textArea.getText().substring(i, j));
list.add(s);
//System.out.println(i + " " + j + " = " + s);
}
return list;
}

private static int getLineHeight(JTextArea textArea) {
return textArea.getFontMetrics(textArea.getFont()).getHeight();
}

private static String removeTrailingNewLine(String s) {
if (s.endsWith("\n")) {
return s.substring(0, s.length() - 1);
} else {
return s;
}
}

public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
TextAreaTest test = new TextAreaTest();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.pack();
test.setVisible(true);
}
});
}
}

How can I get a JTextArea to consume its key events?

The JTextArea listens for keyTyped events. You are adding a binding for keyPressed.

If you instead create the binding for keyTyped event then the text area will handle the event:

//button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "key");
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("typed a"), "key");

Adding a Key Listener to a JtextArea

you should override void keypressed instead of keytyped

@Override
public void keyPressed(KeyEvent e) {
System.out.println("test");
if(e.getKeyCode() == KeyEvent.VK_UP) {
input.setText(inputValue);
System.out.println("up is pressed");

}

because it's not a caracter

Listen to a JTextArea pressed keys

Wrap your code called in the listener method in SwingUtilities.invokeLater()

Output on keyPressed in JTextArea

As already mentioned in comments, you can use a DocumentListener, for example:

javax.swing.event.DocumentListener myDocumentListener = new javax.swing.event.DocumentListener() {
@Override
public void changedUpdate(javax.swing.event.DocumentEvent documentEvent) {
output(documentEvent);
}
@Override
public void insertUpdate(javax.swing.event.DocumentEvent documentEvent) {
output(documentEvent);
}
@Override
public void removeUpdate(javax.swing.event.DocumentEvent documentEvent) {
output(documentEvent);
}
private void output(javax.swing.event.DocumentEvent documentEvent) {
Document source = documentEvent.getDocument();
int length = source.getLength();
try {
System.out.println(source.getText(0, length));
}
catch (javax.swing.text.BadLocationException ex) {
System.err.println("Invalid Index Supplied!");
}
}
};
jTextArea1.getDocument().addDocumentListener(myDocumentListener);

Keybindings in JtextArea to get typed text

Is there any way using keybindings in java to get the text i type in
JTextArea in a string variable??

e.g If i type "Stack overflow" in JtextArea , using keybindings i need
to get "stack overflow" in a string variable.

I can able to do it using keyListeners(by keypressed event) how can i
achieve it in keybindings?

  • use DocumentListener for JTextComponents

  • KeyBindings are designated for Keys commands/short_cuts, output from KeyBindings should be Swing Action / ActionListener, not to fills some variable

Get JTextArea current row text on Enter Key

Hhehe, solved it by myself:

Here's the correct code for what I'm looking for:

if (evt.getKeyCode() == 10) {
try {
int offset=ta.getLineOfOffset(ta.getCaretPosition());
int start=ta.getLineStartOffset(offset);
int end=ta.getLineEndOffset(offset);

System.out.println("Text: "+ta.getText(start, (end-start)));
} catch (BadLocationException ex) {
System.out.println(ex.getMessage());
}
}

Maybe it's useful to another guy out there :)

KeyEvent issue on JTextArea

Actually I want one row in textarea I don't want two line in textarea, How to resolve this problem?

then why are you using textarea?, use JTextField

EDIT after asker's comments:

The additional new line is coming as you are providing your logic in keyPressed method. When you release the key, the ENTER makes it effect on the text area (by adding new line for ENTER).

You can try your logic in public void keyReleased(java.awt.event.KeyEvent evt) method instead and it should work.

Other way could be to consume the released event in pressed event after your logic, but I'm not sure how.

How to clear a JTextArea by pressing enter and remain on the same line

Never add a KeyListener to a JTextComponent such as a JTextArea as this can ruin the underlying function of the text component. Instead use what the Swing library uses when it wants to trap key strokes on a component: use Key Bindings.

For example if you bound the enter key stroke to an Action that cleared the JTextArea, your code would work. In the code below we get the InputMap for the JTextArea for when it has focus:

int condition = JComponent.WHEN_FOCUSED;
InputMap inputMap = textArea.getInputMap(condition);

and also get the JTextArea's ActionMap

ActionMap actionMap = textArea.getActionMap();

then we tie the two maps together, we bind them using the same String constant, here I use the .toString() for my KeyStroke, but any unique (one not also used in the current InputMap) String will do. The action simply clears the JTextArea that caused the action to occur (the source of the Action):

KeyStroke enterKey = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);   
inputMap.put(enterKey, enterKey.toString());
actionMap.put(enterKey.toString(), new AbstractAction() {

@Override
public void actionPerformed(ActionEvent e) {
JTextArea txtArea = (JTextArea) e.getSource();
txtArea.setText("");
}
});

My full MCVE example of the above in action:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;

public class ClearTextAreaEg extends JPanel {
private JTextArea textArea = new JTextArea(10, 20);

public ClearTextAreaEg() {
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);

int condition = JComponent.WHEN_FOCUSED;
InputMap inputMap = textArea.getInputMap(condition);
ActionMap actionMap = textArea.getActionMap();

KeyStroke enterKey = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);

inputMap.put(enterKey, enterKey.toString());
actionMap.put(enterKey.toString(), new AbstractAction() {

@Override
public void actionPerformed(ActionEvent e) {
JTextArea txtArea = (JTextArea) e.getSource();
txtArea.setText("");
}
});

setLayout(new BorderLayout());
add(new JScrollPane(textArea));
}

private static void createAndShowGui() {
ClearTextAreaEg mainPanel = new ClearTextAreaEg();

JFrame frame = new JFrame("ClearTextAreaEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}


Related Topics



Leave a reply



Submit