views:

608

answers:

3

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?

+2  A: 

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.

Adeel Ansari
+4  A: 

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.

A: 

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.

Software Monkey