JavaFX TextField获取单击项

时间:2015-02-08 14:57:42

标签: java javafx javafx-2 javafx-8

我在点击它们时尝试加载(WebEngine)TextArea中的链接。但我不知道如何获得点击的项目。

这是我尝试过的:

area.setOnMouseClicked(event -> {
            WebController.getEngine().load((String) event.getSource());
        });

2 个答案:

答案 0 :(得分:1)

event.getSource()将是您案件中的TextArea

所以你的代码要么是

area.setOnMouseClicked(event -> WebController.getEngine().load(((TextArea) event.getSource()).getText()));

或更简单:

area.setOnMouseClicked(event -> WebController.getEngine().load(area.getText()));

编辑 - 简单TextFlow示例:

@Override
public void start(Stage primaryStage) {

    TextFlow textFlow = new TextFlow();
    textFlow.setOnMouseClicked(ev -> {
        if(ev.getTarget() instanceof Text) {
            Text clicked = (Text) ev.getTarget();
            System.out.println(clicked);
        }
    });

    IntStream.range(0, 500).mapToObj(Integer::toString).map(Text::new).forEach(textFlow.getChildren()::add);

    BorderPane borderpane = new BorderPane(textFlow);
    borderpane.setPadding(new Insets(20));

    Scene scene = new Scene(borderpane, 400, 400);
    primaryStage.setScene(scene);
    primaryStage.show();
}

答案 1 :(得分:0)

如果有人想知道这里发现的是我的代码我正在使用:

package com.ekko.history;

import java.net.URL;
import java.util.Objects;
import java.util.ResourceBundle;

import com.ekko.WebController;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;

public class HistoryController implements Initializable {

    @FXML
    private TextFlow textFlow;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        textFlow.getChildren().clear();
        textFlow.setOnMouseClicked(ev -> {
            if(ev.getTarget() instanceof Text) {
                Text clicked = (Text) ev.getTarget();
                WebController.getEngine().load(clicked.getText());
            }
        });
        HistoryClient.getHistory().stream().filter(Objects::nonNull).forEach(s -> {
            Text text = new Text(s + "\n");
            textFlow.getChildren().add(text);
        });
        HistoryClient.getHistory().clear();
    }
}

这是FXML文件:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<ScrollPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.ekko.history.HistoryController">
   <content>
      <TextFlow fx:id="textFlow" prefHeight="400.0" prefWidth="600.0" />
   </content>
</ScrollPane>

感谢eckig帮助我!