下面列出了怎么用javafx.scene.control.Hyperlink的API类实例代码及写法,或者点击链接到github查看源代码。
public static void activateTextInputControl(final Hyperlink hyperlink, final TooltipPane tooltipPane) {
final TooltipNode[] tooltipNode = new TooltipNode[1];
hyperlink.setOnMouseEntered(event -> {
if (tooltipPane.isEnabled()) {
List<TooltipProvider.TooltipDefinition> definitions = TooltipProvider.getAllTooltips(hyperlink.getText());
hyperlink.requestFocus();
if (!definitions.isEmpty()) {
tooltipNode[0] = new TooltipNode();
tooltipNode[0].setTooltips(definitions);
Point2D location = hyperlink.localToScene(event.getX(), event.getY() + hyperlink.getHeight() + HYPERLINK_TOOLTIP_VERTICAL_GAP);
tooltipPane.showTooltip(tooltipNode[0], location.getX(), location.getY());
}
}
});
hyperlink.setOnMouseExited(event -> {
if (tooltipPane.isEnabled()) {
tooltipPane.hideTooltip();
}
});
}
public void show()
{
final Hyperlink hyperlink = new Hyperlink("Google Cloud SDK");
hyperlink.setOnAction(e -> Paintera.getApplication().getHostServices().showDocument(googleCloudSdkLink));
final TextArea area = new TextArea(googleCloudAuthCmd);
area.setFont(Font.font("monospace"));
area.setEditable(false);
area.setMaxHeight(24);
final TextFlow textFlow = new TextFlow(
new Text("Please install "),
hyperlink,
new Text(" and then run this command to initialize the credentials:"),
new Text(System.lineSeparator() + System.lineSeparator()),
area);
final Alert alert = PainteraAlerts.alert(Alert.AlertType.INFORMATION);
alert.setHeaderText("Could not find Google Cloud credentials.");
alert.getDialogPane().contentProperty().set(textFlow);
alert.show();
}
@Test
public void click() {
Hyperlink button = (Hyperlink) getPrimaryStage().getScene().getRoot().lookup(".hyperlink");
LoggingRecorder lr = new LoggingRecorder();
Platform.runLater(new Runnable() {
@Override
public void run() {
RFXButtonBase rfxButtonBase = new RFXButtonBase(button, null, null, lr);
Point2D sceneXY = button.localToScene(new Point2D(3, 3));
PickResult pickResult = new PickResult(button, sceneXY.getX(), sceneXY.getY());
Point2D screenXY = button.localToScreen(new Point2D(3, 3));
MouseEvent me = new MouseEvent(button, button, MouseEvent.MOUSE_PRESSED, 3, 3, sceneXY.getX(), screenXY.getY(),
MouseButton.PRIMARY, 1, false, false, false, false, true, false, false, false, false, false, pickResult);
rfxButtonBase.mouseButton1Pressed(me);
}
});
List<Recording> recordings = lr.waitAndGetRecordings(1);
Recording select = recordings.get(0);
AssertJUnit.assertEquals("click", select.getCall());
AssertJUnit.assertEquals("", select.getParameters()[0]);
}
private void showOpenFileButton() {
Hyperlink link = new Hyperlink(Util.text("create-file-open"));
TextFlow flow = new TextFlow(new WikiLabel("create-file-success"), link);
flow.setTextAlignment(TextAlignment.CENTER);
addElement(flow);
link.setOnAction(ev -> {
try {
Desktop.getDesktop().open(Session.FILE);
} catch (IOException ex) {
Session.LOGGER.log(Level.WARNING,
"Cannot open file: {0}",
new String[]{ex.getLocalizedMessage()}
);
}
});
nextButton.linkTo("StartPane", stage, true).setText(Util.text("create-file-back-to-start"));
nextButton.setVisible(true);
}
public LanguageSelectionPane(@Nullable Language defaultPreviewLanguage) {
super(10, 10);
this.defaultLanguage = defaultPreviewLanguage;
setToKey(null);
chosenLanguageObserver.addListener(new ValueListener<Language>() {
@Override
public void valueUpdated(@NotNull ValueObserver<Language> observer, @Nullable Language oldValue, @Nullable Language newValue) {
for (Hyperlink hyperlink : links.values()) {
if (hyperlink.getUserData().equals(newValue)) {
hyperlink.setStyle(LanguageSelectionPane.SELECTED_LINK_STYLE);
} else {
hyperlink.setStyle("");
}
}
}
});
}
public StartUpView( HostServices hostServices,
Stage stage,
Consumer<File> openFile ) {
VBox box = new AboutLogFXView( hostServices ).createNode();
String metaKey = FxUtils.isMac() ? "⌘" : "Ctrl+";
Hyperlink link = new Hyperlink( String.format( "Open file (%sO)", metaKey ) );
link.getStyleClass().add( "large-background-text" );
link.setOnAction( ( event ) -> new FileOpener( stage, openFile ) );
Text dropText = new Text( "Or drop files here" );
dropText.getStyleClass().add( "large-background-text" );
StackPane fileDropPane = new StackPane( dropText );
fileDropPane.getStyleClass().add("drop-file-pane");
FileDragAndDrop.install( fileDropPane, openFile );
box.getChildren().addAll( link, fileDropPane );
getChildren().addAll( box );
}
public HelpfulPlaceholder(String initialMessage,
FontIcon leftColumn,
List<Hyperlink> actions) {
getStyleClass().addAll("helpful-placeholder");
this.message.setValue(initialMessage);
VBox messageVBox = new VBox();
Label messageLabel = new Label();
messageLabel.textProperty().bind(message);
messageLabel.setWrapText(true);
messageVBox.getChildren().addAll(messageLabel);
messageVBox.getChildren().addAll(actions);
if (leftColumn != null) {
getChildren().add(leftColumn);
}
getChildren().add(messageVBox);
// TODO move to css
setSpacing(15);
setFillHeight(true);
setAlignment(CENTER);
messageVBox.setAlignment(CENTER);
}
public AboutDialogDialogFxml(AboutDialog controller){
setHeading(label("About Milkman"));
var vbox = new VboxExt();
vbox.setAlignment(Pos.CENTER);
vbox.add(new ImageView(new Image(getClass().getResourceAsStream("/images/icon.png"), 100, 100, true, true)));
vbox.add(label("Version " + VersionLoader.loadCurrentVersion()));
var hyperlink = controller.link = new Hyperlink("http://github.com/warmuuh/milkman");
vbox.add(hyperlink);
setBody(vbox);
setActions(cancel(controller::onClose, "Close"));
}
public DependencyPane(Dependency dependency) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("dependency.fxml"));
loader.setRoot(this);
loader.setController(this);
loader.load();
name.setText(dependency.name);
dependency.version.ifPresentOrElse(v -> version.setText("v." + v), () -> version.setVisible(false));
{
Label l = new Label(dependency.dependency);
l.getStyleClass().add("dependency-gradle");
getChildren().add(l);
}
dependency.description.ifPresent(d -> getChildren().add(new Label(String.valueOf(d).replace("\\n", "\n").replace("\\t", "\t"))));
/* If there is a year or a set of developers, combine them to a string */
if (dependency.year.isPresent() || dependency.developers.length > 0)
getChildren().add(new Label(Streams.concat(dependency.year.stream(), Stream.of(String.join(", ", dependency.developers))).collect(Collectors
.joining(" ", "© ", ""))));
dependency.url.ifPresent(url -> getChildren().add(new Hyperlink(url)));
Separator separator = new Separator();
separator.setMaxWidth(150);
getChildren().add(separator);
for (License license : dependency.licenses) {
getChildren().add(new Label(license.name));
getChildren().add(new Hyperlink(license.url));
}
}
private void handleCheckUpdate(String applicationVersion, Consumer<Node> resultUIHandler) {
Label checking = UIFactory.label(Translation.DIALOG_ABOUT_VERSION_CHECKING);
checking.getStyleClass().add("label-hint");
resultUIHandler.accept(checking);
// needs to run in separate thread so we can see the "checking..." label
Thread lookup = new Thread(() -> {
VersionChecker checker = new VersionChecker("Querz", "mcaselector");
try {
VersionChecker.VersionData version = checker.fetchLatestVersion();
if (version != null && version.isNewerThan(applicationVersion)) {
HBox box = new HBox();
String hyperlinkText = version.getTag() + (version.isPrerelease() ? " (pre)" : "");
Hyperlink download = createHyperlink(hyperlinkText, version.getLink(), null);
download.getStyleClass().add("hyperlink-update");
Label arrow = new Label("\u2192");
arrow.getStyleClass().add("label-hint");
box.getChildren().addAll(arrow, download);
persistentVersionCheckResult = box;
Platform.runLater(() -> resultUIHandler.accept(box));
} else {
Label upToDate = UIFactory.label(Translation.DIALOG_ABOUT_VERSION_UP_TO_DATE);
upToDate.getStyleClass().add("label-hint");
persistentVersionCheckResult = upToDate;
Platform.runLater(() -> resultUIHandler.accept(upToDate));
}
} catch (Exception ex) {
Debug.dumpException("failed to check for latest version", ex);
Label error = UIFactory.label(Translation.DIALOG_ABOUT_VERSION_ERROR);
error.getStyleClass().add("label-hint");
Platform.runLater(() -> resultUIHandler.accept(error));
}
});
lookup.setDaemon(true);
lookup.start();
}
@Override
public Node action() {
Hyperlink link = new Hyperlink();
link.textProperty().bind(super.textProperty());
link.setMinHeight(30);
link.setOnMouseClicked(event -> popOver.show(link, 0));
return link;
}
@FXML private void openLink(ActionEvent e) {
if(e.getSource() instanceof Hyperlink) {
Hyperlink object = (Hyperlink)e.getSource();
try {
new ProcessBuilder("x-www-browser", object.getUserData().toString()).start();
} catch (IOException ex) {
logger.log(Level.SEVERE, ex.getMessage());
}
}
}
public static void activateHyperlink(Hyperlink link) {
link.setOnAction((ActionEvent event) -> {
Hyperlink h = (Hyperlink) event.getTarget();
String s = h.getTooltip().getText();
Main.main.getHostServices().showDocument(s);
event.consume();
});
}
public HyperlinkSample() {
super(400,100);
ImageView iv = new ImageView(ICON_48);
VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setAlignment(Pos.CENTER_LEFT);
Hyperlink h1 = new Hyperlink("Hyperlink");
Hyperlink h2 = new Hyperlink("Hyperlink with Image");
h2.setGraphic(iv);
vbox.getChildren().add(h1);
vbox.getChildren().add(h2);
getChildren().add(vbox);
}
public HyperlinkSample() {
super(400,100);
ImageView iv = new ImageView(ICON_48);
VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setAlignment(Pos.CENTER_LEFT);
Hyperlink h1 = new Hyperlink("Hyperlink");
Hyperlink h2 = new Hyperlink("Hyperlink with Image");
h2.setGraphic(iv);
vbox.getChildren().add(h1);
vbox.getChildren().add(h2);
getChildren().add(vbox);
}
/**
* Create contact pane.
*/
public ContactInfoPane() {
// Grid config
setVgap(4);
setHgap(5);
setPadding(new Insets(15));
setAlignment(Pos.CENTER);
// System
addRow(0, new Label("GitHub"), link("https://github.com/Col-E/Recaf", "icons/github.png"));
addRow(1, new Label("Discord"), new Hyperlink("https://discord.gg/Bya5HaA", new IconView("icons/discord.png")));
}
private void setContent() {
addElement("check-intro", 40);
Session.FILES_TO_UPLOAD.stream().map(uploadElement -> {
String name = Util.getNormalizedName(uploadElement.getData("name"));
Hyperlink label = new Hyperlink(name);
label.setTooltip(new Tooltip(name));
label.setOnAction(event -> {
setDetails(uploadElement, label);
});
return label;
}).forEach(label -> {
fileListContainer.getChildren().add(label);
});
addElementRow(10,
new Node[]{
new WikiScrollPane(fileListContainer).setWidth(250),
new WikiScrollPane(detailsContainer)
},
new Priority[]{Priority.SOMETIMES, Priority.SOMETIMES}
);
setDetails(
Session.FILES_TO_UPLOAD.get(0),
(Hyperlink) fileListContainer.getChildren().get(0)
);
prevButton.linkTo("LoadPane", stage);
nextButton.linkTo("LoginPane", stage);
}
/**
* Shows details of selected file
*
* @param ue
*/
private void setDetails(UploadElement ue, Hyperlink label) {
String name = Util.getNormalizedName(ue.getData("name"));
WikiLabel title = new WikiLabel(name).setClass("header").setAlign("left");
WikiLabel path = new WikiLabel(ue.getData("path")).setAlign("left");
Hyperlink pathURL = new Hyperlink(ue.getData("path"));
Hyperlink preview = new Hyperlink(Util.text("check-preview"));
WikiLabel wikitext = new WikiLabel(ue.getWikicode()).setClass("monospace").setAlign("left");
prevLabel.getStyleClass().remove("bold");
prevLabel = label;
prevLabel.getStyleClass().add("bold");
preview.setOnAction(event -> {
try {
Util.openUrl(Session.WIKI.getProtocol() + Session.WIKI.getDomain()
+ "/wiki/Special:ExpandTemplates"
+ "?wpRemoveComments=true"
+ "&wpInput=" + URLEncoder.encode(ue.getWikicode(), "UTF-8")
+ "&wpContextTitle=" + URLEncoder.encode(name, "UTF-8"));
} catch (UnsupportedEncodingException ex) {
Session.LOGGER.log(Level.SEVERE, null, ex);
}
});
pathURL.setOnAction(event -> {
Util.openUrl(ue.getData("path"));
});
detailsContainer.getChildren().clear();
if (ue.getData("path").startsWith("https://") || ue.getData("path").startsWith("http://")) {
detailsContainer.getChildren().addAll(title, pathURL, preview, wikitext);
} else {
detailsContainer.getChildren().addAll(title, path, getScaledThumbnail(ue.getFile()), preview, wikitext);
}
}
private void addLanguage(@NotNull Language language) {
if (links.containsKey(language)) {
return;
}
Hyperlink hyperlinkLanguage = new Hyperlink(language.getName());
hyperlinkLanguage.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
hyperlinkLanguage.setVisited(false);
chosenLanguageObserver.updateValue(language);
}
});
getChildren().add(hyperlinkLanguage);
}
private void removeLanguage(@NotNull Language language) {
Hyperlink removedHyperlink = links.get(language);
if (removedHyperlink != null) {
links.remove(language);
getChildren().remove(removedHyperlink);
}
}
@FXML
protected void openLink(ActionEvent fxevent) {
Hyperlink hyperlink = (Hyperlink)fxevent.getSource();
String link = hyperlink.getText();
if (link.contains("(")) {
link = link.replaceFirst("^.+\\(", "").replaceFirst("\\).*$", "");
}
System.out.println("Hyperlink pressed: " + link);
Pikatimer.getInstance().getHostServices().showDocument(link);
}
@FXML
protected void openLink(ActionEvent fxevent) {
Hyperlink hyperlink = (Hyperlink)fxevent.getSource();
String link = hyperlink.getText();
if (link.contains("(")) {
link = link.replaceFirst("^.+\\(", "").replaceFirst("\\).*$", "");
}
System.out.println("Hyperlink pressed: " + link);
Pikatimer.getInstance().getHostServices().showDocument(link);
}
public Hyperlink createHyperlink(final String text, final String value) {
Hyperlink hyperLink = new Hyperlink(text);
hyperLink.setPadding(new Insets(0));
hyperLink.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
JFXLinkLabel.this.fireEvent(value);
}
});
if( this.getFont() != null ) {
hyperLink.setFont(((JFXFont) this.getFont()).getHandle());
}
return hyperLink;
}
/**
* Creates the {@link Hyperlink} leading to the git revision on github
*
* @return The {@link Hyperlink} leading to the git revision on github
*/
private Hyperlink createGitRevisionHyperlink() {
final StringBinding revisionText = Bindings.createStringBinding(
() -> Optional.ofNullable(getControl().getBuildInformation())
.map(ApplicationBuildInformation::getApplicationGitRevision).orElse(null),
getControl().buildInformationProperty());
final BooleanBinding disableProperty = Bindings.when(Bindings
.and(Bindings.isNotNull(revisionText), Bindings.notEqual(revisionText, "unknown")))
.then(false).otherwise(true);
final Hyperlink gitRevisionHyperlink = new Hyperlink();
gitRevisionHyperlink.textProperty().bind(revisionText);
// if the git revision equals "unknown" disable the hyperlink
gitRevisionHyperlink.disableProperty().bind(disableProperty);
gitRevisionHyperlink.visitedProperty().bind(disableProperty);
gitRevisionHyperlink.underlineProperty().bind(disableProperty);
// if the git revision has been clicked on open the corresponding commit page on github
gitRevisionHyperlink.setOnAction(event -> {
try {
final URI uri = new URI("https://github.com/PhoenicisOrg/phoenicis/commit/"
+ getControl().getBuildInformation().getApplicationGitRevision());
getControl().getOpener().open(uri);
} catch (URISyntaxException e) {
LOGGER.error("Could not open GitHub URL.", e);
}
});
return gitRevisionHyperlink;
}
VBox createNode() {
VBox contents = new VBox( 25 );
contents.setPrefSize( 500, 300 );
contents.setAlignment( Pos.CENTER );
contents.getStylesheets().add( "css/about.css" );
HBox textBox = new HBox( 0 );
textBox.setPrefWidth( 500 );
textBox.setAlignment( Pos.CENTER );
Text logText = new Text( "Log" );
logText.setId( "logfx-text-log" );
Text fxText = new Text( "FX" );
fxText.setId( "logfx-text-fx" );
textBox.getChildren().addAll( logText, fxText );
VBox smallText = new VBox( 10 );
smallText.setPrefWidth( 500 );
smallText.setAlignment( Pos.CENTER );
Text version = new Text( "Version " + Constants.LOGFX_VERSION );
Text byRenato = new Text( "Copyright Renato Athaydes, 2017. All rights reserved." );
Text license = new Text( "Licensed under the GPLv3 License." );
Hyperlink link = new Hyperlink( "https://github.com/renatoathaydes/LogFX" );
link.setOnAction( ( event ) -> hostServices.showDocument( link.getText() ) );
smallText.getChildren().addAll( version, byRenato, link, license );
contents.getChildren().addAll( textBox, smallText );
return contents;
}
@FXML
private void onAbout(Event evt) {
// TEXT //
Text text1 = new Text("Conway's Game of Life\n");
text1.setFont(Font.font(30));
Text text2 = new Text(
"\nThe Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.\n"
+ "The game is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with the Game of Life by creating an initial configuration and observing how it evolves or, for advanced players, by creating patterns with particular properties."
);
Text text3 = new Text("\n\nRules\n");
text3.setFont(Font.font(20));
Text text4 = new Text(
"\nThe universe of the Game of Life is a two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive or dead. Every cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:\n"
+"\n1) Any live cell with fewer than two live neighbours dies, as if caused by under-population.\n"
+"2) Any live cell with two or three live neighbours lives on to the next generation.\n"
+"3) Any live cell with more than three live neighbours dies, as if by overcrowding.\n"
+"4) Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.\n\nMore on Wikipedia:\n"
);
Hyperlink link = new Hyperlink("http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life <-------not working");
TextFlow tf = new TextFlow(text1,text2,text3,text4,link);
tf.setPadding(new Insets(10, 10, 10, 10));
tf.setTextAlignment(TextAlignment.JUSTIFY);
// END TEXT, START WINDOW //
final Stage dialog = new Stage();
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.initOwner(new Stage());
VBox dialogVbox = new VBox(20);
dialogVbox.getChildren().add(tf);
Scene dialogScene = new Scene(dialogVbox, 450, 500);
dialog.setScene(dialogScene);
dialog.show();
// END WINDOW //
}
private GridPane createBisqDAOOnTestnetContent() {
GridPane gridPane = new GridPane();
gridPane.setMaxWidth(370);
int rowIndex = 0;
TitledGroupBg titledGroupBg = addTitledGroupBg(gridPane, rowIndex, 14, Res.get("dao.news.DAOOnTestnet.title"));
titledGroupBg.getStyleClass().addAll("last", "dao-news-titled-group");
Label daoTestnetDescription = addMultilineLabel(gridPane, ++rowIndex, Res.get("dao.news.DAOOnTestnet.description"), 0, 370);
GridPane.setMargin(daoTestnetDescription, new Insets(Layout.FLOATING_LABEL_DISTANCE, 0, 8, 0));
daoTestnetDescription.getStyleClass().add("dao-news-content");
rowIndex = addInfoSection(gridPane, rowIndex, Res.get("dao.news.DAOOnTestnet.firstSection.title"),
Res.get("dao.news.DAOOnTestnet.firstSection.content"),
"https://docs.bisq.network/getting-started-dao.html#switch-to-testnet-mode");
rowIndex = addInfoSection(gridPane, rowIndex, Res.get("dao.news.DAOOnTestnet.secondSection.title"),
Res.get("dao.news.DAOOnTestnet.secondSection.content"),
"https://docs.bisq.network/getting-started-dao.html#acquire-some-bsq");
rowIndex = addInfoSection(gridPane, rowIndex, Res.get("dao.news.DAOOnTestnet.thirdSection.title"),
Res.get("dao.news.DAOOnTestnet.thirdSection.content"),
"https://docs.bisq.network/getting-started-dao.html#participate-in-a-voting-cycle");
rowIndex = addInfoSection(gridPane, rowIndex, Res.get("dao.news.DAOOnTestnet.fourthSection.title"),
Res.get("dao.news.DAOOnTestnet.fourthSection.content"),
"https://docs.bisq.network/getting-started-dao.html#explore-a-bsq-block-explorer");
Hyperlink hyperlink = addHyperlinkWithIcon(gridPane, ++rowIndex, Res.get("dao.news.DAOOnTestnet.readMoreLink"),
"https://bisq.network/docs/dao");
hyperlink.getStyleClass().add("dao-news-link");
return gridPane;
}
private int addInfoSection(GridPane gridPane, int rowIndex, String title, String content, String linkURL) {
Label titleLabel = addLabel(gridPane, ++rowIndex, title);
GridPane.setMargin(titleLabel, new Insets(6, 0, 0, 0));
titleLabel.getStyleClass().add("dao-news-section-header");
Label contentLabel = addMultilineLabel(gridPane, ++rowIndex, content, -Layout.FLOATING_LABEL_DISTANCE, 370);
contentLabel.getStyleClass().add("dao-news-section-content");
Hyperlink link = addHyperlinkWithIcon(gridPane, ++rowIndex, "Read More", linkURL);
link.getStyleClass().add("dao-news-section-link");
GridPane.setMargin(link, new Insets(0, 0, 29, 0));
return rowIndex;
}
private static Hyperlink createHomeLink() {
String homeUrl = "https://github.com/zxh0/classpy";
Hyperlink link = new Hyperlink(homeUrl);
link.setOnAction(e -> {
try {
Desktop.getDesktop().browse(URI.create(homeUrl));
} catch (IOException x) {
x.printStackTrace(System.err);
}
});
BorderPane.setAlignment(link, Pos.CENTER);
BorderPane.setMargin(link, new Insets(8));
return link;
}
@Test
public void testClickHyperlink() {
final Hyperlink link = find("#link");
Cmds.of(CmdFXVoid.of(() -> {
link.setText("gridGapProp");
link.setVisible(true);
}), () -> clickOn(link)).execute();
Mockito.verify(injector.getInstance(HostServices.class), Mockito.times(1)).showDocument("gridGapProp");
}