0

Anyone knows the tricks to use the MouseListener events so that I can hover a random text in the frame and highlight the hovered text. Then, use Clipboard to copy the hovered text. My current codes:

Main Class:

package copypastefunctionality;

/**
 *
 * @author myu
 */
public class CopyPasteFunctionality {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        NewJFrame run = new NewJFrame();
        run.runProgram();
    }

}

Frame Class:

package copypastefunctionality;

import java.awt.Color;
import java.awt.datatransfer.*;
import java.awt.Toolkit;
/**
 *
 * @author myu
 */
public class NewJFrame extends javax.swing.JFrame {

/**
 * Creates new form NewJFrame
 */
public NewJFrame() {
    initComponents();
}

/**
 * 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() {

    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setText("jLabel1");
    jLabel1.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
    jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseEntered(java.awt.event.MouseEvent evt) {
            jLabel1MouseEntered(evt);
        }
        public void mouseExited(java.awt.event.MouseEvent evt) {
            jLabel1MouseExited(evt);
        }
    });

    jLabel2.setText("jLabel2");

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel1)
                .addComponent(jLabel2))
            .addContainerGap(115, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel1)
            .addGap(18, 18, 18)
            .addComponent(jLabel2)
            .addContainerGap(37, Short.MAX_VALUE))
    );

    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()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(220, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(187, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void jLabel1MouseEntered(java.awt.event.MouseEvent evt) {                                     
    jLabel1.setForeground(Color.blue);
}                                    

private void jLabel1MouseExited(java.awt.event.MouseEvent evt) {                                    
    StringSelection stringSelection = new StringSelection(jLabel1.getText());
    Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
    clpbrd.setContents(stringSelection, null);
}                                   

public void runProgram() {
    /* 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);
        }
    });


}

// Variables declaration - do not modify                     
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
// End of variables declaration                   
}

The GUI will look like this:

enter image description here

The result is not what I expecting. When I hover to the jLabel, it will change the text color and highlight the whole jLabel contents. While I only want to hover parts of the texts. And, currently I can only copy one jLabel, is there a way I can hover the whole frame's contents and copy them to the Clipboard?

Minwu Yu
  • 311
  • 1
  • 6
  • 24
  • Use undecorated, non-editable text component – MadProgrammer May 31 '17 at 23:42
  • You could use the `Clipboard` class and roll your own, have a look at [this answer](https://stackoverflow.com/questions/6710350/copying-text-to-the-clipboard-using-java) and [this answer](https://stackoverflow.com/questions/3591945/copying-to-clipboard-in-java) for more details – MadProgrammer May 31 '17 at 23:44
  • To get the "Copy" option when you right click, you can use a `JPopupMenu` - see [How to se Menus](https://docs.oracle.com/javase/tutorial/uiswing/components/menu.html) for more details – MadProgrammer May 31 '17 at 23:44
  • @MadProgrammer, `Clipboard` works just fine, but how can I use mouse hover and select the String I want and then use the `Clipboard` class? – Minwu Yu Jun 01 '17 at 17:22
  • You can't highlight a label in the normal sense, as I said, you could use a text component or popup menu – MadProgrammer Jun 01 '17 at 19:46

0 Answers0