Question

Im having some issues getting the copy and paste methods from JTextComponent working

for my program i have an array of strings that will be the menu choices. "Copy" and "Paste" are two of these.

 else if (e.getActionCommand().equalsIgnoreCase("Copy"))
            {
                JTextArea a = new JTextArea();
                a.setEditable(true);
                a.copy();
            }
            else if (e.getActionCommand().equalsIgnoreCase("Paste"))
            {
               JTextArea a = new JTextArea();
                a.setEditable(true);
                 a.getSelectedText();
                 a.paste();
            }

im getting no error messages but its not working. any help would be appreciated

Was it helpful?

Solution 2

You are declaring a local object whose scope is limited only in an if condition:

            else if (e.getActionCommand().equalsIgnoreCase("Copy"))
            {
                JTextArea a = new JTextArea();    // CREATING A NEW OBJECT
                a.setEditable(true);
                a.copy();
            }                // AS Soon as the code comes HERE THE Instance IS LOST with the data

Declare;

 JTextArea a = new JTextArea();  outside the if condition, maybe in the class before main(){}
 Create an private instance variable of the same.

Hope this helps. Let me know, if you have any questions.

class TEST{
         public JTextArea a = new JTextArea();   

          TEST objectOfTEST = new TEST():
          publis static String someText = "";

         public static void main(String[] args){

               if(e.getActionCommand().equalsIgnoreCase("Copy")){
                   someText = objectOfTEST.a.getText();
               }
               else if(e.getActionCommand().equalsIgnoreCase("Paste")){
                   // PERFORM SOME OPERATION
                   someText = "Paste this";
                   objectOfTEST.a.setText("Some TEXT that you want to set here");
               }
         }
}

OTHER TIPS

You're creating a new instance of JTextArea each time your want to perform an action.

These won't represent what is actually on the screen. Instead, interact with a instance variable or pass the instance of the JTextArea that is on the screen in as a parameter

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top