java swing 文本框双击Ctrl,触发删除全部并黏贴
tc.addKeyListener(new KeyListener() {
private long lastTimeMillSencond;
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if (EventHWUtil.isJustCtrlDown(e)) {
if (lastTimeMillSencond == 0) {
lastTimeMillSencond = System.currentTimeMillis();
} else {
long currentTime = System.currentTimeMillis();
if (MenuUtil2.isDoubleClick(currentTime - lastTimeMillSencond)) {
System.out.println("双击Ctrl");
String content = WindowUtil.getSysClipboardText();
if (ValueWidget.isNullOrEmpty(content)) {
return;
}
tc.setText(content);
tc.requestFocus();
lastTimeMillSencond = 0;
} else {
lastTimeMillSencond = System.currentTimeMillis();
}
}
}
}
});
见类: com/swing/component/TextCompUtil2.java
如何判断是否点击了Ctrl 呢?
public static boolean isJustCtrlDown(KeyEvent e) {
int keyCode = e.getKeyCode();
return e.isControlDown() && keyCode != KeyEvent.VK_TAB
&& keyCode != KeyEvent.VK_QUOTE/*双引号*/
&& keyCode != KeyEvent.VK_OPEN_BRACKET/*{*/
&& keyCode != KeyEvent.VK_CLOSE_BRACKET/*}*/
&& keyCode != KeyEvent.VK_COLON/*分号*/
&& keyCode != KeyEvent.VK_PERIOD/*句号*/
&& keyCode != KeyEvent.VK_COMMA/*逗号*/
&& keyCode != KeyEvent.VK_AT/*@*/
&& keyCode != KeyEvent.VK_2/*@*/
&& keyCode == KeyEvent.VK_CONTROL;
}
见类:com/swing/event/EventHWUtil.java
鼠标中间也是:删除全部并黏贴
/***
* 给文本框增加右键菜单.
*
* @param field2
*/
public static JPopupMenu setPopupMenu(final JTextComponent field2,JPopupMenu textMenu1)
{
final JPopupMenu textMenu;
if(ValueWidget.isNullOrEmpty(textMenu1)){
textMenu = new JPopupMenu();
}else{
textMenu=textMenu1;
}
field2.addMouseListener(new MouseInputListener()
{
@Override
public void mouseMoved(MouseEvent e)
{
}
@Override
public void mouseDragged(MouseEvent e)
{
}
@Override
public void mouseReleased(MouseEvent e)
{
// super.mousePressed(e);
if (e.getButton() == MouseEvent.BUTTON3)
{
// addPopupMenuItem(field2,textMenu);
textMenu.show(e.getComponent(), e.getX(), e.getY());
}else if (e.getButton() == MouseEvent.BUTTON2){//鼠标中键
//按下鼠标中键,把剪切板内容黏贴到文本框中
String text=WindowUtil.getSysClipboardText();
if(!ValueWidget.isNullOrEmpty(text)
&&!ValueWidget.isNullOrEmpty(field2)){
field2.setText(text);
field2.setForeground(TextCompUtil2.DEFAULT_TF_FOREGROUND);//防止placeholder
field2.requestFocus();
}
}
}
@Override
public void mousePressed(MouseEvent e)
{
}
@Override
public void mouseExited(MouseEvent e)
{
}
@Override
public void mouseEntered(MouseEvent e)
{
}
@Override
public void mouseClicked(MouseEvent e)
{
}
});
return textMenu;
}
见类:com/swing/menu/MenuUtil2.java