Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

java - How to copy JList element text to clipboard

I am having an issue where I am trying to copy the contents of a JList element (the text that is displayed in the element) and then paste that content to another JList element. The problem is that for some reason, regardless of what I make the actual clipboard contents when I go to actually paste the text it instead pastes what I am assuming is the element's toString() method. See here:

package listtest;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;

public class main extends JPanel {
    JList<Test> list;

    DefaultListModel<Test> model;

    int counter = 15;

    public main() {
    setLayout(new BorderLayout());
    model = new DefaultListModel<Test>();
    list = new JList<Test>(model);
    Test[] elements = new Test[] {new Test("Test 1"), new Test("Test 2"), new Test("Test 3")};
    for (int i = 0; i < elements.length; i++) {
        model.addElement(elements[i]);
    }

    add(list, BorderLayout.NORTH);
    list.setCellRenderer((ListCellRenderer<? super Test>) getRenderer());

    list.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_V && e.isControlDown()) {
            Clipboard c = getSystemClipboard();
            try {
            String clip = (String) c.getData(DataFlavor.stringFlavor);
            System.out.println("Clipboard contents when pasting: " + clip);
            } catch (UnsupportedFlavorException | IOException e1) {   }     
        }else if(e.getKeyCode() == KeyEvent.VK_C && e.isControlDown()) {
            Clipboard c = getSystemClipboard();
            StringSelection a = new StringSelection("Hello");
            try {
            System.out.println("StringSelection I just made: " + a.getTransferData(DataFlavor.stringFlavor));
            c.setContents(a, null);
            String clip = (String) c.getData(DataFlavor.stringFlavor);
            System.out.println("Clipboard contents right after copying: " + clip);
            } catch (UnsupportedFlavorException | IOException e1) {}
        }
        }
    });

    }

    private ListCellRenderer<? super String> getRenderer() {
    return new DefaultListCellRenderer(){
        private static final long serialVersionUID = 17990901717809235L;
        @Override
        public Component getListCellRendererComponent(JList<?> list,
            Object value, int index, boolean isSelected,
            boolean cellHasFocus) {
        JLabel listCellRendererComponent = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected,cellHasFocus);
        listCellRendererComponent.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0,Color.BLACK));
        setText(((Test)value).testStr);
        return listCellRendererComponent;
        }
    };
    }

    private Clipboard getSystemClipboard(){
    Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
    Clipboard systemClipboard = defaultToolkit.getSystemClipboard();

    return systemClipboard;
    }

    public static void main(String s[]) {
    JFrame frame = new JFrame("List Model Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new main());
    frame.setSize(260, 200);
    frame.setVisible(true);
    }
}

class Test{

    public String testStr;

    public Test(String test) {
    testStr = test;
    }
}

In this program whenever you press ctrl+C with an element selected it adds "Hello" to the clipboard then checks the clipboard and prints that out. When you press ctrl+V (anywhere actually. You can try this in notepad too) it pastes the object name of the element you pressed ctrl+c over instead of the actual clipboard contents (in this case "Hello"). In short, the output is:

StringSelection I just made: Hello
Clipboard contents right after copying: Hello
Clipboard contents when pasting: listtest.Test@12ffd81

Am I doing something wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It looks like windows still tries to copy when you press ctrl+c while an element is selected and it apparently gets the toString() representation of whatever is selected. I moved the copy code to keyReleased() instead of keyPressed() and now it's working as intended


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...