hasherr
hasherr

Reputation: 709

I need a way to manipulate the last character in a JTextArea (by deleting it)

I have a JTextArea that I can fill with text using JButtons. I want a JButton that I can use a backspace without using the Robot class or the backspace key, but just by clicking the button on the screen with my mouse. How do I manipulate the text using public void actionPerformed(ActionEvent e) { of a JTextArea using this button, by using a self-created backspace key? Let me know if you have any questions or are confused on what I'm asking.

Upvotes: 1

Views: 2906

Answers (3)

Ksish Isjaj
Ksish Isjaj

Reputation: 1

Remove last line from JtextArea

JtextArea.setText(JtextArea.getText().substring(0,JtextArea.getText().lastIndexOf("\n")));

Upvotes: 0

Mahmoud Habib
Mahmoud Habib

Reputation: 23

You can substring method from string

String text = textArea.getText();
textArea.setText(text.subString(0, text.length() - 1);

Upvotes: 2

MadProgrammer
MadProgrammer

Reputation: 347184

Take a look at Document.

Every text component in Swing has a Document model which controls the state of the text (and where applicable, the attributes and structure).

You can use the JTextArea's Document to remove characters directly.

Something like...

Document doc = textArea.getDocument();
doc.remove(doc.getLength() - 2, 1);

Upvotes: 3

Related Questions