Java Code Examples for javafx.event.EventHandler

The following examples show how to use javafx.event.EventHandler. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: paintera   Source File: OpenDialogMenu.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static EventHandler<KeyEvent> keyPressedHandler(
		final PainteraGateway gateway,
		final Node target,
		Consumer<Exception> exceptionHandler,
		Predicate<KeyEvent> check,
		final String menuText,
		final PainteraBaseView viewer,
		final Supplier<String> projectDirectory,
		final DoubleSupplier x,
		final DoubleSupplier y)
{

	return event -> {
		if (check.test(event))
		{
			event.consume();
			OpenDialogMenu m = gateway.openDialogMenu();
			Optional<ContextMenu> cm = m.getContextMenu(menuText, viewer, projectDirectory, exceptionHandler);
			Bounds bounds = target.localToScreen(target.getBoundsInLocal());
			cm.ifPresent(menu -> menu.show(target, x.getAsDouble() + bounds.getMinX(), y.getAsDouble() + bounds.getMinY()));
		}
	};

}
 
Example 2
Source Project: games_oop_javafx   Source File: TicTacToe.java    License: Apache License 2.0 6 votes vote down vote up
private EventHandler<MouseEvent> buildMouseEvent(Group panel) {
    return event -> {
        Figure3T rect = (Figure3T) event.getTarget();
        if (this.checkState()) {
            if (event.getButton() == MouseButton.PRIMARY) {
                rect.take(true);
                panel.getChildren().add(
                        this.buildMarkX(rect.getX(), rect.getY(), 50)
                );
            } else {
                rect.take(false);
                panel.getChildren().add(
                        this.buildMarkO(rect.getX(), rect.getY(), 50)
                );
            }
            this.checkWinner();
            this.checkState();
        }
    };
}
 
Example 3
Source Project: netbeans   Source File: ChartAdvancedStockLine.java    License: Apache License 2.0 6 votes vote down vote up
private void init(Stage primaryStage) {
    Group root = new Group();
    primaryStage.setScene(new Scene(root));
    root.getChildren().add(createChart());
    // create timeline to add new data every 60th of second
    animation = new Timeline();
    animation.getKeyFrames().add(new KeyFrame(Duration.millis(1000/60), new EventHandler<ActionEvent>() {
        @Override public void handle(ActionEvent actionEvent) {
            // 6 minutes data per frame
            for(int count=0; count < 6; count++) {
                nextTime();
                plotTime();
            }
        }
    }));
    animation.setCycleCount(Animation.INDEFINITE);
}
 
Example 4
public EditorTreeViewEditContextMenu(@NotNull EditorComponentTreeView<? extends UINodeTreeItemData> treeView,
									 @NotNull FolderTreeItemEntry entryClicked) {
	ResourceBundle bundle = Lang.ApplicationBundle();

	MenuItem miRename = new MenuItem(bundle.getString("ContextMenu.DefaultComponent.rename"));
	miRename.setOnAction(new EventHandler<ActionEvent>() {
		@Override
		public void handle(ActionEvent event) {
			NameInputFieldDialog<StringChecker, String> dialog = new NameInputFieldDialog<>(
					miRename.getText(), miRename.getText(),
					new StringChecker()
			);
			dialog.getInputField().getValueObserver().updateValue(entryClicked.getText());
			dialog.getInputField().selectAll();
			dialog.show();
			String value = dialog.getInputField().getValue();
			if (dialog.wasCancelled() || value == null) {
				return;
			}
			entryClicked.setText(value);
		}
	});
	getItems().add(miRename);

	addCommon(treeView, entryClicked, bundle);
}
 
Example 5
Source Project: OEE-Designer   Source File: Section.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public void fireSectionEvent(final SectionEvent EVENT) {
       final EventHandler<SectionEvent> HANDLER;
       final EventType                  TYPE = EVENT.getEventType();
       if (SectionEvent.TILES_FX_SECTION_ENTERED == TYPE) {
           HANDLER = getOnSectionEntered();
       } else if (SectionEvent.TILES_FX_SECTION_LEFT == TYPE) {
           HANDLER = getOnSectionLeft();
       } else if (SectionEvent.TILES_FX_SECTION_UPDATE == TYPE) {
           HANDLER = getOnSectionUpdate();
       } else {
           HANDLER = null;
       }

       if (null == HANDLER) return;

       HANDLER.handle(EVENT);
   }
 
Example 6
Source Project: dctb-utfpr-2018-1   Source File: TestarComponentes.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void start(Stage primaryStage) {
    Button btn = new Button();
    btn.setText("Say 'Hello World'");
    btn.setOnAction(new EventHandler<ActionEvent>() {
        
        @Override
        public void handle(ActionEvent event) {
            System.out.println("Hello World!");
        }
    });
    
    StackPane root = new StackPane();
    root.getChildren().add(btn);
    
    Scene scene = new Scene(root, 300, 250);
    
    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();
}
 
Example 7
Source Project: gef   Source File: HoverGesture.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates an {@link EventHandler} for hover {@link MouseEvent}s. The
 * handler will search for a target part within the given {@link IViewer}
 * and notify all hover policies of that target part about hover changes.
 * <p>
 * If no target part can be identified, then the root part of the given
 * {@link IViewer} is used as the target part.
 *
 * @return The {@link EventHandler} that handles hover changes for the given
 *         {@link IViewer}.
 */
protected EventHandler<MouseEvent> createHoverFilter() {
	return new EventHandler<MouseEvent>() {
		@Override
		public void handle(MouseEvent event) {
			updateHoverIntentPosition(event);
			if (!isHoverEvent(event)) {
				return;
			}
			EventTarget eventTarget = event.getTarget();
			if (eventTarget instanceof Node) {
				IViewer viewer = PartUtils.retrieveViewer(getDomain(),
						(Node) eventTarget);
				if (viewer != null) {
					notifyHover(viewer, event, (Node) eventTarget);
				}
				updateHoverIntent(event, (Node) eventTarget);
			}
		}
	};
}
 
Example 8
Source Project: OEE-Designer   Source File: CronTrendController.java    License: MIT License 6 votes vote down vote up
private void handleCronEvent(JobExecutionContext context) {
	ResolutionService service = new ResolutionService();

	service.setOnFailed(new EventHandler<WorkerStateEvent>() {
		@Override
		public void handle(WorkerStateEvent event) {
			Throwable t = event.getSource().getException();

			if (t != null) {
				// connection failed
				AppUtils.showErrorDialog(t.getMessage());
			}
		}
	});

	// run on application thread
	service.start();
}
 
Example 9
Source Project: mars-sim   Source File: DatePicker.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void initPicker(WebView webView) {
  // attach a handler for an alert function call which will set the DatePicker's date property.
  webView.getEngine().setOnAlert(new EventHandler<WebEvent<String>>() {
    @Override public void handle(WebEvent<String> event) {
      try { date.set(jQueryUiDateFormat.parse(event.getData())); } catch (ParseException e) { /* no action required */ }
    }
  });

  // place the webView holding the jQuery date picker inside this node.
  this.getChildren().add(webView);

  // monitor the date for changes and update the formatted date string to keep it in sync.
  date.addListener(new ChangeListener<Date>() {
    @Override public void changed(ObservableValue<? extends Date> observableValue, Date oldDate, Date newDate) {
      dateString.set(dateFormat.format(newDate));
    }
  });

  // workaround as I don't know how to size the stack to the size of the enclosed WebPane's html content.
  this.setMaxSize(330, 280);//307, 241);
}
 
Example 10
Source Project: gef   Source File: CreationMenuOnClickHandler.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private Node createArrow(final boolean left) {
	// shape
	final Polygon arrow = new Polygon();
	arrow.getPoints().addAll(left ? LEFT_ARROW_POINTS : RIGHT_ARROW_POINTS);
	// style
	arrow.setStrokeWidth(ARROW_STROKE_WIDTH);
	arrow.setStroke(ARROW_STROKE);
	arrow.setFill(ARROW_FILL);
	// effect
	effectOnHover(arrow, new DropShadow(DROP_SHADOW_RADIUS, getHighlightColor()));
	// action
	arrow.setOnMouseClicked(new EventHandler<MouseEvent>() {
		@Override
		public void handle(MouseEvent event) {
			traverse(left);
		}
	});
	return arrow;
}
 
Example 11
Source Project: oim-fx   Source File: ChoosePane.java    License: MIT License 6 votes vote down vote up
private void initialize() {
	getStyleClass().setAll(DEFAULT_STYLE_CLASS);
	setAccessibleRole(AccessibleRole.TOGGLE_BUTTON);
	// alignment is styleable through css. Calling setAlignment
	// makes it look to css like the user set the value and css will not
	// override. Initializing alignment by calling set on the
	// CssMetaData ensures that css will be able to override the value.
	((StyleableProperty<Pos>) (WritableValue<Pos>) alignmentProperty()).applyStyle(null, Pos.CENTER);

	this.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {

		@Override
		public void handle(MouseEvent event) {
			doSelected();
		}
	});
}
 
Example 12
Source Project: oim-fx   Source File: ListNodePanel.java    License: MIT License 6 votes vote down vote up
private void iniEvent() {
    topBox.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
        	if(event.getButton()==MouseButton.PRIMARY) {
        		if (isShow) {
                    isShow = false;
                    imageView.setImage(closed);
                    ListNodePanel.this.getChildren().remove(box);
                } else {
                    isShow = true;
                    imageView.setImage(open);
                    ListNodePanel.this.getChildren().add(box);
                }
        	}
        }
    });
}
 
Example 13
Source Project: desktoppanefx   Source File: InternalWindow.java    License: Apache License 2.0 6 votes vote down vote up
public final ObjectProperty<EventHandler<InternalWindowEvent>> onDetachingProperty() {
    if (onDetaching == null) {
        onDetaching = new ObjectPropertyBase<EventHandler<InternalWindowEvent>>() {
            @Override
            protected void invalidated() {
                setEventHandler(InternalWindowEvent.WINDOW_DETACHING, get());
            }

            @Override
            public Object getBean() {
                return InternalWindow.this;
            }

            @Override
            public String getName() {
                return "onDetaching";
            }
        };
    }
    return onDetaching;
}
 
Example 14
Source Project: arma-dialog-creator   Source File: WizardStageDialog.java    License: MIT License 6 votes vote down vote up
public WizardStageDialog(@Nullable Stage primaryStage, @Nullable String title, boolean hasHelp, @NotNull WizardStep... wizardSteps) {
	super(primaryStage, new StackPane(), title, true, true, hasHelp);


	wizardStepsReadOnly = new ReadOnlyList<>(wizardSteps);

	btnPrevious = new Button(Lang.ApplicationBundle().getString("Wizards.previous"));
	btnPrevious.setOnAction(new EventHandler<ActionEvent>() {
		@Override
		public void handle(ActionEvent event) {
			goBackwardStep();
		}
	});

	btnPrevious.setPrefWidth(GenericResponseFooter.PREFFERED_BUTTON_OK_WIDTH);
	footer.getRightContainer().getChildren().add(1, btnPrevious);
	footer.btnOk.setText(Lang.ApplicationBundle().getString("Wizards.next"));

	Collections.addAll(this.wizardSteps, wizardSteps);

	for (WizardStep step : wizardSteps) {
		addWizardStep(step);
	}
	btnPrevious.setDisable(true);
}
 
Example 15
Source Project: oim-fx   Source File: ChatPanel.java    License: MIT License 6 votes vote down vote up
/**
 * 初始化中间工具按钮
 */
private void initMiddleToolBar() {
	// 字体设置按钮
	Image normalImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_font.png");
	Image hoverImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_font_hover.png");
	Image pressedImage = ImageBox.getImageClassPath("/resources/chat/images/middletoolbar/aio_quickbar_font_hover.png");

	IconPane iconButton = new IconPane(normalImage, hoverImage, pressedImage);
	iconButton.setOnMouseClicked(new EventHandler<MouseEvent>() {

		@Override
		public void handle(MouseEvent event) {
			showFontBox = !showFontBox;
			showFontBox(showFontBox);
		}
	});
	this.addMiddleTool(iconButton);
}
 
Example 16
public void addMenuItem(final String iconPath,
    final EventHandler<MouseEvent> eventHandler) {

final RadialGradient backGradient = new RadialGradient(0, 0, 0, 0,
	radius.get(), false, CycleMethod.NO_CYCLE, new Stop(0,
		BACK_GRADIENT_COLOR), new Stop(1, Color.TRANSPARENT));

final RadialGradient backSelectGradient = new RadialGradient(0, 0, 0,
	0, radius.get(), false, CycleMethod.NO_CYCLE, new Stop(0,
		BACK_SELECT_GRADIENT_COLOR), new Stop(1,
		Color.TRANSPARENT));

final RadialMenuItem item = RadialMenuItemBuilder.create()
	.length(length).graphic(new Group(getImageView(iconPath)))
	.backgroundFill(backGradient)
	.backgroundMouseOnFill(backSelectGradient)
	.innerRadius(innerRadius).radius(radius).offset(offset)
	.clockwise(true).backgroundVisible(true).strokeVisible(false)
	.build();

item.setOnMouseClicked(eventHandler);

items.add(item);
itemsContainer.getChildren().addAll(item);
   }
 
Example 17
Source Project: marathonv5   Source File: ComboBoxTreeTableSample.java    License: Apache License 2.0 5 votes vote down vote up
private void updateObservableListProperties(TreeTableColumn<Employee, String> empColumn) {
    empColumn.setOnEditCommit(new EventHandler<TreeTableColumn.CellEditEvent<Employee, String>>() {

        @Override
        public void handle(CellEditEvent<Employee, String> t) {
            TreeItem<Employee> treeItem = t.getTreeTableView().getTreeItem(t.getTreeTablePosition().getRow());
            treeItem.getValue().setName(t.getNewValue());
        }
    });
}
 
Example 18
Source Project: oim-fx   Source File: FaceFrame.java    License: MIT License 5 votes vote down vote up
private void initEvent() {
	button.setOnAction(new EventHandler<ActionEvent>() {

		@Override
		public void handle(ActionEvent event) {
			// po.show(button4,1d,2d);
			facePopup.show(button);

		}
	});
}
 
Example 19
Source Project: marathonv5   Source File: StageSample.java    License: Apache License 2.0 5 votes vote down vote up
public StageSample() {
    //create a button for initializing our new stage
    Button button = new Button("Create a Stage");
    button.setStyle("-fx-font-size: 24;");
    button.setDefaultButton(true);
    button.setOnAction(new EventHandler<ActionEvent>() {
        @Override public void handle(ActionEvent t) {
            final Stage stage = new Stage();
            //create root node of scene, i.e. group
            Group rootGroup = new Group();
            //create scene with set width, height and color
            Scene scene = new Scene(rootGroup, 200, 200, Color.WHITESMOKE);
            //set scene to stage
            stage.setScene(scene);
            //center stage on screen
            stage.centerOnScreen();
            //show the stage
            stage.show();
            //add some node to scene
            Text text = new Text(20, 110, "JavaFX");
            text.setFill(Color.DODGERBLUE);
            text.setEffect(new Lighting());
            text.setFont(Font.font(Font.getDefault().getFamily(), 50));
            //add text to the main root group
            rootGroup.getChildren().add(text);
        }
    });
    getChildren().add(button);
}
 
Example 20
Source Project: Path-of-Leveling   Source File: PlaceholderStageGameMode.java    License: MIT License 5 votes vote down vote up
public void loadSettings(){
    FXMLLoader loader = new FXMLLoader(getClass().getResource("/poe/level/fx/preferences.fxml"));
    AnchorPane ap = null;
    try {
        ap = loader.load();
    } catch (IOException ex) {
        Logger.getLogger(ZoneOverlay_Stage.class.getName()).log(Level.SEVERE, null, ex);
    }
    controller = loader.<Preferences_Controller>getController();
    controller.hookGameModeOn(parent_gameModeOn);
    Scene scene = new Scene(ap);
    scene.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent event) {
            if (event.getCode() == KeyCode.ESCAPE) {
                close();
            }
        }
    });
    scene.getStylesheets().add(getClass().getResource("/styles/style.css").toExternalForm());

    this.setScene(scene);
    //this.setAlwaysOnTop(true);
    this.setOnCloseRequest(event -> {
        this.hide();
    });

    this.show();
}
 
Example 21
/**
 * Create the context menu for the date.
 *
 * @return the context menu.
 */
private ContextMenu createDateContextMenu() {
	ContextMenu menu = new ContextMenu();

	MenuItem menuItemRemove = new MenuItem();
	menuItemRemove.setText(ResourceUtil.getString(ResourceConstants.MENU_DELETE_IMAGES));

	menuItemRemove.setOnAction(new EventHandler<ActionEvent>() {
		@Override
		public void handle(final ActionEvent event) {
			DialogUtil.displayConfirmationMessage(new ConfirmDialogListener() {

				@Override
				public void onDialogPositiveClick() {
					mParentController.removeItem(EyePhotoPairNode.this);
					mPair.delete();
				}

				@Override
				public void onDialogNegativeClick() {
					// do nothing
				}
			}, ResourceConstants.BUTTON_DELETE,
					ResourceConstants.MESSAGE_DIALOG_CONFIRM_DELETE_DATE, mPair.getPersonName(), mLabelDate.getText());
		}
	});
	menu.getItems().add(menuItemRemove);

	return menu;
}
 
Example 22
Source Project: constellation   Source File: DateTimeRangeInputPane.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param period A Period containing either months or days.
 *
 * @param group
 */
public TimeRangeToggleButton(final Period period, final ToggleGroup group, final EventHandler<ActionEvent> toggleHandler) {
    this.period = period;

    final String label = String.valueOf(period.getMonths() != 0 ? period.getMonths() : period.getDays());
    setText(label);
    setToggleGroup(group);
    getStyleClass().add("time-range-toggle");

    setOnAction(event -> {
        toggleHandler.handle(event);
    });
}
 
Example 23
Source Project: oim-fx   Source File: TextAreaFrameTest.java    License: MIT License 5 votes vote down vote up
private void initEvent() {
	button.setOnAction(new EventHandler<ActionEvent>() {

		@Override
		public void handle(ActionEvent event) {
			textFlow.appendText("ff");
		}
	});
}
 
Example 24
Source Project: marathonv5   Source File: SamplePage.java    License: Apache License 2.0 5 votes vote down vote up
public Node createTile() {
    Button tile = new Button(getName().trim(),getIcon());
    tile.setMinSize(140,145);
    tile.setPrefSize(140,145);
    tile.setMaxSize(140,145);
    tile.setContentDisplay(ContentDisplay.TOP);
    tile.getStyleClass().clear();
    tile.getStyleClass().add("sample-tile");
    tile.setOnAction(new EventHandler() {
        public void handle(Event event) {
            Ensemble2.getEnsemble2().goToPage(SamplePage.this);
        }
    });
    return tile;
}
 
Example 25
Source Project: Solitaire   Source File: CardPileView.java    License: GNU General Public License v2.0 5 votes vote down vote up
private EventHandler<DragEvent> createDragExitedHandler(final ImageView pImageView, final Card pCard)
{
	return new EventHandler<DragEvent>()
	{
		@Override
		public void handle(DragEvent pEvent)
		{
			pImageView.setEffect(null);
			pEvent.consume();
		}
	};
}
 
Example 26
Source Project: JFoenix   Source File: TextFieldEditorBase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Region createNode(T value, EventHandler<KeyEvent> keyEventsHandler, ChangeListener<Boolean> focusChangeListener) {
    textField = value == null ? new JFXTextField() : new JFXTextField(String.valueOf(value));
    textField.setOnKeyPressed(keyEventsHandler);
    textField.getValidators().addAll(validators);
    textField.focusedProperty().addListener(focusChangeListener);
    return textField;
}
 
Example 27
Source Project: PreferencesFX   Source File: PreferencesFxModel.java    License: Apache License 2.0 5 votes vote down vote up
private void fireEvent(PreferencesFxEvent event) {
  List<EventHandler<? super PreferencesFxEvent>> list =
      this.eventHandlers.get(event.getEventType());
  if (list == null) {
    return;
  }
  for (EventHandler<? super PreferencesFxEvent> eventHandler : list) {
    if (!event.isConsumed()) {
      eventHandler.handle(event);
    }
  }
}
 
Example 28
Source Project: trex-stateless-gui   Source File: PacketTableView.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Add menu item to table rightclickMenu
 *
 * @param action
 */
private void addMenuItem(StreamTableAction action) {
    MenuItem item = new MenuItem(action.getTitle());
    item.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            handleStreamTableAction(action);
        }
    });
    rightClickMenu.getItems().add(item);
}
 
Example 29
Source Project: arma-dialog-creator   Source File: ADCPreloader.java    License: MIT License 5 votes vote down vote up
@Override
public void start(Stage preloaderStage) throws Exception {
	this.preloaderStage = preloaderStage;
	preloaderStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
		@Override
		public void handle(WindowEvent event) {
			System.exit(0);
		}
	});

	preloaderStage.setTitle(Lang.Application.APPLICATION_TITLE);
	preloaderStage.getIcons().add(ADCIcons.ICON_ADC);
	progressIndicator.setMaxWidth(48d);
	progressIndicator.setMaxHeight(progressIndicator.getMaxWidth());

	VBox vBox = new VBox(5, progressIndicator, lblProgressText);
	vBox.setAlignment(Pos.CENTER);
	VBox.setVgrow(progressIndicator, Priority.ALWAYS);

	Label lblBuild = new Label("Build: " + ArmaDialogCreator.getManifest().getMainAttributes().getValue("Build-Number"));
	Label lblVersion = new Label("Version: " + ArmaDialogCreator.getManifest().getMainAttributes().getValue("Specification-Version"));
	BorderPane borderPane = new BorderPane(vBox, null, null, new HBox(10, lblBuild, lblVersion), null);
	borderPane.setPadding(new Insets(5));

	StackPane.setMargin(borderPane, new Insets(248, 0, 0, 0));
	StackPane stackpane = new StackPane(new ImageView(ADCImagePaths.PRELOAD_SCREEN), borderPane);
	Scene scene = new Scene(stackpane);
	preloaderStage.initStyle(StageStyle.UNDECORATED);
	preloaderStage.setScene(scene);
	preloaderStage.sizeToScene();
	preloaderStage.show();
}
 
Example 30
Source Project: marathonv5   Source File: AdvancedStockLineChartSample.java    License: Apache License 2.0 5 votes vote down vote up
public AdvancedStockLineChartSample() {
    getChildren().add(createChart());
    // create timeline to add new data every 60th of second
    animation = new Timeline();
    animation.getKeyFrames().add(new KeyFrame(Duration.millis(1000/60), new EventHandler<ActionEvent>() {
        @Override public void handle(ActionEvent actionEvent) {
            // 6 minutes data per frame
            for(int count=0; count < 6; count++) {
                nextTime();
                plotTime();
            }
        }
    }));
    animation.setCycleCount(Animation.INDEFINITE);
}