Question

I have a very simple code that creates a frame object from the class MyJFrame accepts the first string which is used as a title. Place the second string is the text to be displayed in a JScrollPane. You can see the code below. What I need is to use copy and paste of text highlighted. I need help implementing it. So that if copy selected from a menubar it copies the highlighted portion and if paste is pastes it.

import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import java.awt.Container;
import javax.swing.JOptionPane;

public class DisplayText
{
private static JTextArea text;

public DisplayText(String title, String info)
{  
    MyJFrame f = new MyJFrame(title);
    Container c = f.getContentPane();

  //default text
    text = new JTextArea(info);

  //Scrollpane
    JScrollPane sp = new JScrollPane(text);
    c.add( sp );

    f.setBounds(100,200, 500, 400 );
    f.setVisible(true);
}
Was it helpful?

Solution

Use the Actions that are available in the DefaultEditorKit including DefaultEditorKit.CopyAction, DefaultEditorKit.CutAction, and DefaultEditorKit.PasteAction.

For example:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.*;
import javax.swing.text.*;

public class TestActions {
   private String[] texts = {
         "Hello", "Goodbye", "What the f***?", "Heck if I know", "Peace out man!"
   };
   private JTextArea textArea = new JTextArea(10, 30);
   private Action[] textActions = { new DefaultEditorKit.CutAction(),
         new DefaultEditorKit.CopyAction(), new DefaultEditorKit.PasteAction(), };
   private JPanel mainPanel = new JPanel();
   private JMenuBar menubar = new JMenuBar();
   private JPopupMenu popup = new JPopupMenu();
   private PopupListener popupListener = new PopupListener();

   public TestActions() {
      JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 5));
      JMenu menu = new JMenu("Edit");
      for (Action textAction : textActions) {
         btnPanel.add(new JButton(textAction));
         menu.add(new JMenuItem(textAction));
         popup.add(new JMenuItem(textAction));
      }
      menubar.add(menu);

      JPanel textFieldPanel = new JPanel(new GridLayout(0, 1, 5, 5));
      for (String text: texts) {
         JTextField textField = new JTextField(text, 15);
         textField.addMouseListener(popupListener);
         textFieldPanel.add(textField);
         textField.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
               ((JTextComponent)e.getSource()).selectAll();
            }
         });
      }
      textArea.addMouseListener(popupListener);
      JScrollPane scrollPane = new JScrollPane(textArea);

      JPanel textFieldPanelWrapper = new JPanel(new BorderLayout());
      textFieldPanelWrapper.add(textFieldPanel, BorderLayout.NORTH);

      mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
      mainPanel.setLayout(new BorderLayout(5, 5));
      mainPanel.add(btnPanel, BorderLayout.NORTH);
      mainPanel.add(scrollPane, BorderLayout.CENTER);
      mainPanel.add(textFieldPanelWrapper, BorderLayout.EAST);
   }

   public JComponent getMainPanel() {
      return mainPanel;
   }

   private JMenuBar getMenuBar() {
      return menubar;
   }

   private class PopupListener extends MouseAdapter {
      public void mousePressed(MouseEvent e) {
         maybeShowPopup(e);
     }

     public void mouseReleased(MouseEvent e) {
         maybeShowPopup(e);
     }

     private void maybeShowPopup(MouseEvent e) {
         if (e.isPopupTrigger()) {
             popup.show(e.getComponent(),
                        e.getX(), e.getY());
         }
     }
   }

   private static void createAndShowGui() {
      TestActions testActions = new TestActions();

      JFrame frame = new JFrame("Test Actions");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(testActions.getMainPanel());
      frame.setJMenuBar(testActions.getMenuBar());
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

code borrowed from my answer here.


Edit
You ask in comment:

I appreciate the answer. However, could you make it a bit simpler to understand, I am fairly new to Java.

Sure, here is a simple JMenuBar that holds an edit JMenu that holds JMenuItems for copy, cut, and paste with just that code borrowed from my example. Note that as an aside, you should not setBounds on anything, you should instead set the rows and columns of your JTextArea, and that you should not use a static JTextArea, and in fact no Swing components should ever be static.

import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;

import java.awt.Container;

import javax.swing.JOptionPane;
import javax.swing.text.DefaultEditorKit;

public class DisplayText {
   private JTextArea text;
   private Action[] textActions = { new DefaultEditorKit.CutAction(),
         new DefaultEditorKit.CopyAction(), new DefaultEditorKit.PasteAction(), };

   public DisplayText(String title, String info) {
      JMenu menu = new JMenu("Edit");
      for (Action textAction : textActions) {
         menu.add(new JMenuItem(textAction));
      }
      JMenuBar menuBar = new JMenuBar();
      menuBar.add(menu);

      JFrame f = new JFrame(title);
      f.setJMenuBar(menuBar);

      Container c = f.getContentPane();

      text = new JTextArea(info, 20, 50);

      JScrollPane sp = new JScrollPane(text);
      c.add(sp);

      // f.setBounds(100,200, 500, 400 );
      f.pack();
      f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
   }

   public static void main(String[] args) {
      new DisplayText("Title", "This is info text");
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top