package swt;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.junit.Test;
public class EventDemo_07 {
/**
* 指哪到哪
*/
@Test
public void testMouseEvent(){
Display display= new Display();
Shell topShell= new Shell(display,SWT.SHELL_TRIM|SWT.BORDER);
topShell.setText( "测试鼠标监听事件" );
topShell.setSize( 800 , 500 );
final Button button= new Button(topShell, SWT.NONE);
button.setText( "移动" );
button.setBounds( 100 , 100 , 100 , 30 );
// new MouseMoveListener() {
//
// @Override
// public void mouseMove(MouseEvent e) {
//
// }
// };
/*
button.addMouseListener(new MouseListener() {
@Override
public void mouseUp(MouseEvent e) {
//e.x和e.y为鼠标按键起来时相对于按钮左上角那个点的距离
int x = e.x;
int y = e.y;
System.out.println(x+" "+y);
button.setBounds(x, y, 100, 30);
}
@Override
public void mouseDown(MouseEvent e) {
}
@Override
public void mouseDoubleClick(MouseEvent e) {
}
});
*/
topShell.addMouseListener(new MouseListener() {
@Override
public void mouseUp(MouseEvent e) {
System.out.println(e.x+" "+e.y);
Rectangle rect = button.getBounds();
Rectangle rectangle=new Rectangle(e.x, e.y, rect.width, rect.height);
button.setBounds(rectangle);
}
@Override
public void mouseDown(MouseEvent e) {
}
@Override
public void mouseDoubleClick(MouseEvent e) {
}
});
topShell.open();
while(!topShell.isDisposed()){
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
/**
* 功能:按着ctrl+箭头可以移动按钮
*/
@Test
public void testKeyListener(){
Display display= new Display();
Shell topShell= new Shell(display,SWT.SHELL_TRIM|SWT.BORDER);
topShell.setText( "测试键盘监听事件" );
topShell.setSize( 800 , 500 );
Button button= new Button(topShell, SWT.NONE);
button.setText( "移动" );
button.setBounds( 100 , 100 , 100 , 30 );
button.addKeyListener( new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
Button btn= (Button) e.widget;
Rectangle bounds = btn.getBounds();
//键盘事件特有的属性,表示辅助键:crtl或alt或shift
int stateMask = e.stateMask;
int sum = SWT.CTRL|SWT.ALT|SWT.SHIFT;
int flag=stateMask∑
if (flag==SWT.CTRL) {
if (e.keyCode==SWT.ARROW_DOWN) {
bounds.y++;
} else if (e.keyCode==SWT.ARROW_UP) {
bounds.y--;
} else if (e.keyCode==SWT.ARROW_LEFT) {
bounds.x--;
} else if (e.keyCode==SWT.ARROW_RIGHT) {
bounds.x++;
} else {
//键盘事件特有的属性,表示e.character表示可输入的字符
System.out.println( "usage:ctrl+上|下|左|右" +e.character
+ " --- " +e.keyCode);
}
} else {
System.out.println( "请使用ctrl辅助键" );
}
System.out.println( "输入的:" +e.character+ " --- " +e.keyCode);
btn.setBounds(bounds);
}
});
topShell.open();
while (!topShell.isDisposed()){
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
|