Activate JTextArea Right Click Mouse
This is the Java code example how to activated right click in JTextArea.
package myjavaexample; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import javax.swing.Action; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.border.EmptyBorder; import javax.swing.text.DefaultEditorKit; import javax.swing.text.JTextComponent; import javax.swing.text.TextAction; public class MyJavaExample extends JFrame { public void setup() { this.setSize(800,600); this.setLocation(200,200); this.setTitle("JTextArea Right Click"); this.setLayout(new BorderLayout()); JPanel panel=new JPanel(); panel.setBorder(new EmptyBorder(5, 10, 5, 10)); JTextArea textArea=new JTextArea(); textArea.setLineWrap(true); JScrollPane areaScrollPane = new JScrollPane(textArea); areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); areaScrollPane.setPreferredSize(new Dimension(300,300)); panel.add(areaScrollPane); JPopupMenu menu = new JPopupMenu(); Action cut = new DefaultEditorKit.CutAction(); cut.putValue(Action.NAME, "Cut"); cut.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control X")); menu.add( cut ); Action copy = new DefaultEditorKit.CopyAction(); copy.putValue(Action.NAME, "Copy"); copy.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control C")); menu.add( copy ); Action paste = new DefaultEditorKit.PasteAction(); paste.putValue(Action.NAME, "Paste"); paste.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control V")); menu.add( paste ); Action selectAll = new SelectAll(); menu.add( selectAll ); textArea.setComponentPopupMenu( menu ); this.add(panel,BorderLayout.PAGE_END); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.pack(); this.setVisible(true); } private class SelectAll extends TextAction { public SelectAll() { super("Select All"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control S")); } public void actionPerformed(ActionEvent e) { JTextComponent component = getFocusedComponent(); component.selectAll(); component.requestFocusInWindow(); } } public static void main(String[] args) { MyJavaExample mainwin=new MyJavaExample(); mainwin.setup(); mainwin.setVisible(true); } }



Comments
Post a Comment