Northener
Northener

Reputation: 873

Making cut/replace methods with JTextArea

I am to make a cut and a replace method on JTextArea. I have the code for copy and paste, and I reckon I could just use that, in addition to just deleting the marked text in the JTA.

How would the code for a code for cut and replace methods look like?

The code for copy looks like this:

public void copy(){
    int start=ta.getSelectionStart();
    int end=ta.getSelectionEnd();
    String s=ta.getText();
    aString=s.substring(start,end);
    System.out.println(aString);
}

And the paste code looks like the following:

public void paste(){
    int start=ta.getSelectionStart();
    String startText=ta.getText().substring(0, start);
    String endText=ta.getText().substring(start);
    String res=startText+clipBoard+endText;
    ta.setText(res);
}

So basically: How do I delete marked text in a JTextArea? Or is there possibly a better way to do this?

Upvotes: 0

Views: 2111

Answers (3)

L. Cornelius Dol
L. Cornelius Dol

Reputation: 64066

In addition to amit.dev's answer, you should also be able to set custom key mappings to use whatever keys you would like... but if you do, you'll loose some platform independence, since different platforms have different keys for these operations.

Upvotes: 0

amit
amit

Reputation: 10892

JTextArea supports cut/copy/paste by default using keyword combination (Ctrl+C etc). If you want to have custom invocations (like menu action), JTextComponent itself provides cut/copy/paste methods which you can re-use.

Upvotes: 4

Adeel Ansari
Adeel Ansari

Reputation: 39907

It would mixture of both methods, without clipBoard concatenation, I suppose.

public void cut(){
  int start=ta.getSelectionStart();
  int end=ta.getSelectionEnd();
  String startText=ta.getText().substring(0, start);
  String endText=ta.getText().substring(end, ta.getText.length());
  ta.setText(startText+endText);
}

However, why not use cut, copy, and paste method of JTextComponent, which are already inherited and available.

Upvotes: 2

Related Questions