Search code examples
javaswingcopypastejtextcomponent

implementing a copy/paste action in java


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


Solution

  • 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");
                   }
             }
    }