java多文本框使用右键弹出菜单复制粘贴剪切功能实现

时间:2021-04-29 16:54:32

在学习JPopupMenud的过程中,做了一个小软件。实现了多个文本框,同时使用右键弹出菜单,并实现复制、粘贴、剪切功能。

实际上在网上查的时候,网上有一个很普遍的右键复制、粘贴、剪切的功能(http://blog.csdn.net/xinem/article/details/3866904)。我抄过来发现可以实现功能,但不是很懂怎么实现复制、粘贴、和剪切功能。于是自己摸索了,写了一个。

这个小软件,主要实现了两个文本框同时可以使用右键弹出菜单的复制、粘贴、剪切功能。

小软件的界面用netbeans画出来的,包括JPopupMenu都是这样子的。

这个软件,部分代码用了网上那个流传广泛的代码。

以下是我的软件代码:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/


import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import javax.swing.JTextField;

/**
*
* @author peade
*/
public class NewJFrame extends javax.swing.JFrame {

/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
//将右键弹出菜单添加到文本框
jTextField1.setComponentPopupMenu(jPopupMenu1);
jTextField2.setComponentPopupMenu(jPopupMenu1);
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jPopupMenu1 = new javax.swing.JPopupMenu();
copyb = new javax.swing.JMenuItem();
pasteb = new javax.swing.JMenuItem();
cutb = new javax.swing.JMenuItem();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();

copyb.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
copyb.setText("复制");
copyb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
copybActionPerformed(evt);
}
});
jPopupMenu1.add(copyb);

pasteb.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
pasteb.setText("粘贴");
pasteb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pastebActionPerformed(evt);
}
});
jPopupMenu1.add(pasteb);

cutb.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
cutb.setText("剪切");
cutb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cutbActionPerformed(evt);
}
});
jPopupMenu1.add(cutb);

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jTextField1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jTextField1MousePressed(evt);
}
});

jTextField2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jTextField2MousePressed(evt);
}
});

jLabel1.setText("文本框1");

jLabel2.setText("文本框2");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(22, 22, 22)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1)
.addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE))
.addContainerGap(82, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addContainerGap(43, Short.MAX_VALUE))
);

pack();
}// </editor-fold>
// 三个按键事件添加
private void copybActionPerformed(java.awt.event.ActionEvent evt) {
// getInvoker() 判断右键菜单来源于哪个文本框
if(jPopupMenu1.getInvoker()==jTextField1)
{

copybAction(evt,jTextField1);
}

if(jPopupMenu1.getInvoker()==jTextField2)
{

copybAction(evt,jTextField2);
}

// TODO add your handling code here:
}

private void pastebActionPerformed(java.awt.event.ActionEvent evt) {

if(jPopupMenu1.getInvoker()==jTextField1)
{

pastebAction(evt,jTextField1);
}

if(jPopupMenu1.getInvoker()==jTextField2)
{

pastebAction(evt,jTextField2);
}

// TODO add your handling code here:
}

private void cutbActionPerformed(java.awt.event.ActionEvent evt) {

if(jPopupMenu1.getInvoker()==jTextField1)
{

cutbAction(evt,jTextField1);
}

if(jPopupMenu1.getInvoker()==jTextField2)
{

cutbAction(evt,jTextField2);
}
// TODO add your handling code here:
}
//在文本框中进行功能是否可用判断
private void jTextField1MousePressed(java.awt.event.MouseEvent evt) {
judge(evt,jTextField1);
// TODO add your handling code here:
}

private void jTextField2MousePressed(java.awt.event.MouseEvent evt) {
judge(evt,jTextField2);
// TODO add your handling code here:
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
//粘贴功能
private void pastebAction(ActionEvent evt, JTextField textField) {
//以下三行获取剪切板的值
Clipboard clip = this.getToolkit().getSystemClipboard();
Transferable contents=clip.getContents(this);
DataFlavor flavor=DataFlavor.stringFlavor;

String str = null;

String s=textField.getText();

if(contents.isDataFlavorSupported(flavor)){


try{
//剪切板的值转移到str中

str=(String)contents.getTransferData(flavor);
int start=textField.getSelectionStart();
int end=textField.getSelectionEnd();
if(start==end){
if(start==0){
s=str+s;
textField.setText(s);
textField.setCaretPosition(str.length());
}else if(start==s.length()){
s=s+str;
textField.setText(s);
textField.setCaretPosition(s.length());
}else{
String s1=s.substring(0,start);
String s2=s.substring(start);
s=s1+str+s2;
textField.setText(s);
textField.setCaretPosition(s1.length()+str.length());
}
}else{
String s1=s.substring(0,start);
String s2=s.substring(end);
s=s1+str+s2;
textField.setText(s);
textField.setCaretPosition(s1.length()+str.length());
}



}catch(Exception e){
e.printStackTrace();
}


}


}
//复制功能
private void copybAction(ActionEvent evt, JTextField textField) {
int start=textField.getSelectionStart();
int end=textField.getSelectionEnd();
String s=textField.getText();
String cp=s.substring(start,end);
sendtoClipboard(cp);

// TODO add your handling code here:
}
//剪切功能
private void cutbAction(java.awt.event.ActionEvent evt, JTextField TextField) {
int start=TextField.getSelectionStart();
int end=TextField.getSelectionEnd();
String s=TextField.getText();
String cs=s.substring(start,end);
sendtoClipboard(cs);
s=s.substring(0,start)+s.substring(end);
TextField.setText(s);
// TODO add your handling code here:
}
// 将文本发送到系统剪切板
protected void sendtoClipboard(String st){
Toolkit kit=Toolkit.getDefaultToolkit();
Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection ss=new StringSelection(st);
sysClip.setContents(ss, null);
}
//判断能否进行复制剪切
public boolean isCanCopy(JTextField textField) {
boolean b = false;
int start = textField.getSelectionStart();
int end = textField.getSelectionEnd();
if (start != end)
b = true;
return b;
}
//判断能否进行粘贴
public boolean isClipboardString() {
boolean b = false;
Clipboard clipboard = this.getToolkit().getSystemClipboard();
Transferable content = clipboard.getContents(this);
try {
if (content.getTransferData(DataFlavor.stringFlavor) instanceof String) {
b = true;
}
} catch (Exception e) {
}
return b;
}
// 判断复制粘贴剪切在具体文本框中,该功能是否可用
protected void judge(MouseEvent evt, JTextField TextField)
{
if (evt.getButton() == MouseEvent.BUTTON3){
copyb.setEnabled(isCanCopy(TextField));
cutb.setEnabled(isCanCopy(TextField));
pasteb.setEnabled(isClipboardString());
}
}
// Variables declaration - do not modify
private javax.swing.JMenuItem copyb;
private javax.swing.JMenuItem cutb;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPopupMenu jPopupMenu1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JMenuItem pasteb;
// End of variables declaration
}