swing 文本域的undo和右键开始菜单

1,让文本域可以undo,比如支持Ctrl+Z,Ctrl+Y,Ctrl+S(联想windows的notepad)

下面是一个可以undo的文本域:

package com.swing.component;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.Document;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;

public class UndoTextArea extends JTextArea {
	private static final long serialVersionUID = 2622113838910292609L;
	private UndoManager undo = new UndoManager();
	private Document doc = getDocument();
	private StringBuffer stringbuf = null;

	public void stopUndo() {
		// undo.die();
		undo.discardAllEdits();
	}

	public UndoManager getUndo() {
		return undo;
	}

	public void setUndo(UndoManager undo) {
		this.undo = undo;
	}

	public Document getDoc() {
		return doc;
	}

	public void setDoc(Document doc) {
		this.doc = doc;
	}

	/**
	 * @autho : whuang dicate original content of the area
	 * @return
	 */
	public StringBuffer getStringbuf() {
		return stringbuf;
	}

	/***
	 * dicate original content of the area
	 * 
	 * @param stringbuf
	 */
	public void setStringbuf(StringBuffer stringbuf) {
		this.stringbuf = stringbuf;
	}

	private void initlize() {
		doc.addUndoableEditListener(new UndoableEditListener() {
			public void undoableEditHappened(UndoableEditEvent e) {
				undo.addEdit(e.getEdit());
			}
		});
		addActionMap();
	}

	public UndoTextArea() {
		initlize();

	}

	public UndoTextArea(int rows, int columns) {
		super(rows, columns);
		initlize();

	}

	public void addActionMap() {
		getActionMap().put("Undo", new AbstractAction("Undo11") {
			private static final long serialVersionUID = 2434402629308759912L;

			public void actionPerformed(ActionEvent evt) {
				try {
					boolean b = undo.canUndo();
					// System.out.println("whether undo : "+b);
					if (b) {
						undo.undo();
					}
				} catch (CannotUndoException e) {
				}
			}
		});
		getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");

		getActionMap().put("Redo", new AbstractAction("Redo1111") {
			private static final long serialVersionUID = 5348330289578410517L;

			public void actionPerformed(ActionEvent evt) {
				try {
					if (undo.canRedo()) {
						undo.redo();
					}
				} catch (CannotRedoException e) {
				}
			}
		});
		getInputMap().put(KeyStroke.getKeyStroke("control R"), "Redo");

		getActionMap().put("Copy", new AbstractAction("Copy111") {
			private static final long serialVersionUID = -5151480809625853288L;

			public void actionPerformed(ActionEvent evt) {
				copy();
			}

		});
		getInputMap().put(KeyStroke.getKeyStroke("control C"), "Copy");

		getActionMap().put("Cut", new AbstractAction("Cut") {

			private static final long serialVersionUID = 7316612864835857713L;

			public void actionPerformed(ActionEvent evt) {
				cut();
			}

		});

		getInputMap().put(KeyStroke.getKeyStroke("control X"), "Cut");

		getActionMap().put("Paste", new AbstractAction("Paste111") {
			private static final long serialVersionUID = -3548620001691220571L;

			public void actionPerformed(ActionEvent evt) {
				paste();
			}
		});

		getInputMap().put(KeyStroke.getKeyStroke("control V"), "Paste");

		// redo Ctrl + Y
		getActionMap().put("Redo", new AbstractAction("reDo111") {
			private static final long serialVersionUID = -3548620001691220571L;

			public void actionPerformed(ActionEvent evt) {
				if (undo.canRedo()) {
					undo.redo();
				}
			}
		});

		getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");

	}

}

 示例:

inputTextArea = new UndoTextArea();
		inputTextArea.setLineWrap(true);
		inputTextArea.setWrapStyleWord(true);

 

(2)增加右键菜单

效果如下:



 
 代码如下:

package com.swing.menu;

import java.awt.event.MouseEvent;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.event.MouseInputListener;
import javax.swing.text.JTextComponent;

public class MenuUtil2
{
    public static final String ACTION_STR_OPEN               = "open";
    public static final String ACTION_STR_DELETE_FILE        = "delete file";
    public static final String ACTION_STR_EXIT               = "exit";
    public static final String ACTION_STR_BROWSER            = "browser";
    public static final String ACTION_STR_COPY               = "copy";
    public static final String ACTION_STR_COPY_ALL           = "copy all";
    public static final String ACTION_STR_PASTE              = "paste";
    public static final String ACTION_STR_REPLACE_ALL              = "replace all";
    public static final String ACTION_STR_DELETE_CONTENT     = "delete";
    public static final String ACTION_STR_DELETE_ALL_CONTENT = "delete all";
    public static final String ACTION_STR_SELECT_ALL_CONTENT = "select all";
    public static final String ACTION_STR_REFRESH            = "refresh";
    public static final String ACTION_STR_COPY_FILEPATH      = "copy file path";
    public static final String ACTION_STR_FILE_RENAME        = "rename";
    public static final String ACTION_STR_CLOSE              = "close";
    public static final String ACTION_STR_NEW                = "new";
    public static final String ACTION_STR_ADD                = "add";
    public static final String ACTION_STR_SAVE               = "save";
    public static final String ACTION_STR_EDIT               = "edit";
    public static final String ACTION_STR_VIEW               = "view";
    public static final String ACTION_STR_UPDATE             = "update";
    public static final String ACTION_STR_INSERT             = "insert";
    
    private MenuUtil2()
    {
        throw new Error("Don't let anyone instantiate this class.");
    }
    /***
     * 给文本框增加右键菜单.
     * 
     * @param field2
     */
    public static void setPopupMenu(final JTextComponent field2)
    {
        field2.addMouseListener(new MouseInputListener()
        {
            @Override
            public void mouseMoved(MouseEvent e)
            {

            }

            @Override
            public void mouseDragged(MouseEvent e)
            {

            }

            @Override
            public void mouseReleased(MouseEvent e)
            {
                //                super.mousePressed(e);
                if (e.getButton() == MouseEvent.BUTTON3)
                {
                    JPopupMenu textMenu = new JPopupMenu();
                    JMenuItem copyM = new JMenuItem(MenuUtil2.ACTION_STR_COPY);
                    JMenuItem copyAllM = new JMenuItem(
                        MenuUtil2.ACTION_STR_COPY_ALL);
                    JMenuItem pasteM = new JMenuItem(MenuUtil2.ACTION_STR_PASTE);
                    JMenuItem replaceAllM = new JMenuItem(MenuUtil2.ACTION_STR_REPLACE_ALL);
                    JMenuItem deleteM = new JMenuItem(
                        MenuUtil2.ACTION_STR_DELETE_CONTENT);
                    JMenuItem deleteAllM = new JMenuItem(
                        MenuUtil2.ACTION_STR_DELETE_ALL_CONTENT);
                    JMenuItem selAllM = new JMenuItem(
                        MenuUtil2.ACTION_STR_SELECT_ALL_CONTENT);
                    Menu2ActionListener myMenuListener=new Menu2ActionListener(field2);
                    copyM.addActionListener(myMenuListener);
                    copyAllM.addActionListener(myMenuListener);
                    pasteM.addActionListener(myMenuListener);
                    replaceAllM.addActionListener(myMenuListener);
                    deleteM.addActionListener(myMenuListener);
                    deleteAllM.addActionListener(myMenuListener);
                    selAllM.addActionListener(myMenuListener);
                    textMenu.add(copyM);
                    textMenu.add(copyAllM);
                    if(!(field2 instanceof JTextField)){
                    	/*因为JTextField 没有 ta2.insert(content, caret) 方法 .*/
                    	 textMenu.add(pasteM);
                    }
                   
                    textMenu.add(replaceAllM);
                    textMenu.add(deleteM);
                    textMenu.add(deleteAllM);
                    textMenu.add(selAllM);
                    textMenu.show(e.getComponent(), e.getX(), e.getY());
                }
            }

            @Override
            public void mousePressed(MouseEvent e)
            {
            }

            @Override
            public void mouseExited(MouseEvent e)
            {
            }

            @Override
            public void mouseEntered(MouseEvent e)
            {
            }

            @Override
            public void mouseClicked(MouseEvent e)
            {
            }
        });

    }

}

package com.swing.menu;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;

import com.common.util.WindowUtil;

/***
 * 文本域的右键菜单响应事件.
 * 
 * @author huangwei
 *
 */
public class Menu2ActionListener implements ActionListener {
	private JTextComponent area2;

	public Menu2ActionListener(JTextComponent area2) {
		super();
		this.area2 = area2;
	}


	@Override
	public void actionPerformed(ActionEvent event) {
		String command = event.getActionCommand();
		if (command.equals(MenuUtil2.ACTION_STR_DELETE_CONTENT)) {
			// System.out.println("delete word");
			area2.replaceSelection("");
		} else if (command.equals(MenuUtil2.ACTION_STR_DELETE_ALL_CONTENT)) {
			area2.selectAll();
			area2.replaceSelection("");
		} else if (command.equals(MenuUtil2.ACTION_STR_SELECT_ALL_CONTENT)) {
			if (area2 != null) {
				area2.selectAll();
				// System.out.println("select all");
			}
		} else if (command.equals(MenuUtil2.ACTION_STR_COPY)) {
			String selectContent = area2.getSelectedText();
			if (selectContent == null || selectContent.equals("")) {
				return;
			}
			WindowUtil.setSysClipboardText(selectContent);
		} else if (command.equals(MenuUtil2.ACTION_STR_COPY_ALL)) {
			String selectContent = area2.getText();
			if (selectContent == null || selectContent.equals("")) {
				return;
			}
			WindowUtil.setSysClipboardText(selectContent);
		} else if (command.equals(MenuUtil2.ACTION_STR_PASTE)) {
			String content = WindowUtil.getSysClipboardText();
			if (content == null || content.equals("")) {
				return;
			}
			int caret = area2.getCaretPosition();
			if(area2 instanceof JTextArea){
				JTextArea ta2=(JTextArea)area2;
				ta2.insert(content, caret);
			}
		} else if (command.equals(MenuUtil2.ACTION_STR_REPLACE_ALL)) {
			String content = WindowUtil.getSysClipboardText();
			if (content == null || content.equals("")) {
				return;
			}
			area2.setText(content);
		}

	}

}

 示例项目见附件

可以直接运行 java -jar base64Demo-0.0.1-SNAPSHOT.jar

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值