首页>代码>java swing开发的socket远程控制开关机服务>/shutdown-client/src/cn/verp/swing/JPopupMenuJFrame.java
package cn.verp.swing;
/*
 * 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 JPopupMenuJFrame extends javax.swing.JFrame {

    /**
	 * 
	 */
	private static final long serialVersionUID = 3793445170758316259L;
	/**
     * Creates new form NewJFrame
     */
    public JPopupMenuJFrame() {
        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.
     */
    // <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(JPopupMenuJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JPopupMenuJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JPopupMenuJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JPopupMenuJFrame.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 JPopupMenuJFrame().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                   
}
最近下载更多
微笑刺客  LV21 2023年1月13日
ewan007  LV30 2022年4月24日
露无畏  LV13 2022年4月18日
tangjj7260  LV18 2021年12月10日
一个好人520  LV10 2021年9月29日
675104182  LV14 2020年9月22日
huzh035  LV3 2020年2月19日
子不语103  LV7 2020年1月19日
pipulu  LV1 2019年9月24日
adminroot777  LV8 2019年9月23日
最近浏览更多
3334004690  LV11 2024年5月28日
uid0901  LV2 2024年4月2日
痴汉hug个人民 2023年2月21日
暂无贡献等级
微笑刺客  LV21 2023年1月13日
taoyi123  LV17 2022年12月29日
aixiao5213  LV1 2022年12月28日
炫瓶百事可乐  LV1 2022年12月1日
ewan007  LV30 2022年4月24日
1265260263  LV4 2022年4月8日
17842711  LV1 2022年3月27日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友