Customize Java Event Listening


Thành viên VIP
This week I show you how to personalize an event-listening API. Working with GUI means working with events. JAVA Swing is not well equipped with Event-Listeners. In many cases you have to twist something for your listening purposes. For example, JTextField and JTextArea are places where the users interact with the app. And the interaction requires sometimes action that needs to bring a text from an external source onto the input area. Typing a short text is tolerable. Typing a long (cryptic) text is a effortful feat.

The feature Copy & Paste is a common function of GUI applications. JavaFX TextField and TextArea offer the users this feature, but Java SWING doesn't. So, we have no other choice than to customize this feature for JTextField and JTextArea.

First of all we have to analyze the Copy & Paste function which pops up when the right key of the mouse is pressed:
- Copying is a marking of a text using the mouse and then with the right key to copy the marking text.
- Pasting is the transfering of the copied text to an area where the text should be inserted (or overwritten). To do that the cursor is moved to this area (JTextField or JTextAera) by the mouse and with the right key of the mouse the "Paste" function is selected for the pasting execution.

Simple and easy: the Mouse and its "menu" of 2 functions: Copy, Paste. In Java SWING means:
- Mouse Events using the API MouseAdapter and
- Mouse Menu using the SWING JPopupMenu to produce the 2 functions Copy and Paste.

import javax.swing.*;
import java.awt.event.*;
import javax.swing.text.DefaultEditorKit;
// Joe Nartca (c)
public class CopyPasteListener extends MouseAdapter {
   Constructor A pop-up menu "Copy/Paste" with the click of the right mouse-pad
   @param jcomp any Jcomponent. Example JTextArea, JtextField
  public CopyPasteListener(JComponent jcomp) {
	this.jcomp = jcomp;
  public void mousePressed(MouseEvent e){
	if (e.isPopupTrigger()) popup(e);
  public void mouseReleased(MouseEvent e){
	if (e.isPopupTrigger())popup(e);
  private void popup(MouseEvent e){
	//JoePopup menu = new JoePopup();
	JPopupMenu menu = new JPopupMenu();
	JMenuItem copy = new JMenuItem(jcomp.getActionMap().get(DefaultEditorKit.copyAction));
	copy.setAccelerator(KeyStroke.getKeyStroke((int)'C', InputEvent.CTRL_DOWN_MASK));
	JMenuItem paste = new JMenuItem(jcomp.getActionMap().get(DefaultEditorKit.pasteAction));
	paste.setAccelerator(KeyStroke.getKeyStroke((int)'P', InputEvent.CTRL_DOWN_MASK));
	menu.add(paste);, e.getX(), e.getY());
  private JComponent jcomp;
Of course, you could implement "more" features such as Cut, Print, etc. into this API. An using example:

   JTextField jtxt = new JTextField(path, 32);
   jtxt.addMouseListener(new CopyPasteListener(jtxt)); // CopyPasteListener

Have fun with Copy&PasteListener.