我在写一个类似于word的文本编辑程序,文字选中后拖拽该怎么实现,请教高手?
如何用java实现选中文字后拖动(类似于在word中一样)
- 提问者网友:送舟行
- 2021-05-03 21:12
- 五星知识达人网友:三千妖杀
- 2021-05-03 22:47
java dnd 技术来实现
package dnd;
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.TransferHandler;
public final class LabelDND {
private JFrame mainFrame = null;
private JPanel panel = null;
private JLabel label = null;
private JTextField textField = null;
private JColorChooser colorChooser = null;
public LabelDND() {
mainFrame = new JFrame();
panel = new JPanel(new BorderLayout());
colorChooser = new JColorChooser();
colorChooser.setDragEnabled(true);
label = new JLabel("可以拖到txt框");
// 这里调用了TransferHandler的第二个构造函数,参数是一个Java Bean 属性
label.setTransferHandler(new TransferHandler("text"));
// label.setTransferHandler(new TransferHandler("foreground"));
label.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);// 调用了exportAsDrag
}
});
textField = new JTextField(20);
// 打开textField自带的拖放功能
textField.setDragEnabled(true);
panel.add(label, BorderLayout.PAGE_START);
panel.add(colorChooser, BorderLayout.CENTER);
panel.add(textField, BorderLayout.PAGE_END);
mainFrame.getContentPane().add(panel);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
new LabelDND();
}
}
这是以前写的一个例子,可以把label上的文字拖到text框里,改下TransferHandler可以拖颜色过去