JavaFX小知识

一、添加鼠标点击监听

//鼠标右键监听
		whiteListView.setOnMouseClicked(new EventHandler() {

			@Override
			public void handle(MouseEvent event) {
				if(event.getButton() == MouseButton.SECONDARY) {
					System.out.println("鼠标右击");
				}
				if(event.getButton() == MouseButton.PRIMARY) {
					System.out.println("鼠标单击");
				}
				if(event.getClickCount() == 2) {
					System.out.println("鼠标双击");
				}
			}
		});
//其中whiteListView是一个控件,可以根据自己需要替换,我这里用的是TableView

二、鼠标右键菜单

private final static ContextMenu contextMenu = new ContextMenu();
//初始化
public void initialize(URL location, ResourceBundle resources) {
	menuSetUp();
}

public void menuSetUp(){
    //添加菜单
    MenuItem activation = new MenuItem("激活");
    activation.setOnAction(new EventHandler() {
        @Override
        public void handle(ActionEvent event) {
            System.out.println("123123");
        }
    });
    contextMenu.getItems().add(activation);
}

//鼠标调用
if(event.getButton() == MouseButton.PRIMARY) {
    System.out.println("鼠标单击");
    contextMenu.hide();//隐藏右键菜单
}
if(event.getButton() == MouseButton.SECONDARY) {
    System.out.println("鼠标右击");
    //位置是TOP和LEFT的时候菜单会在鼠标旁边,但是位置是BOTTON和RIGHT的时候就会跑到很远
    //有知道的同学还请赐教
    contextMenu.show(whiteListView,Side.TOP,event.getX(),event.getY());
}
//结合文章第一点看

效果图:

JavaFX小知识_第1张图片

你可能感兴趣的:(JAVAFX)