[英]Is there a way to select a text field in code without clicking on it (javafx)?
我不確定如何甚至是否可以在代碼中選擇文本字段。 我在這個問題上找不到任何東西。 如果確實是這樣做的方法,那么我有一個可以修改的模板,以演示如何實現。
這是模板/示例代碼:
主班:
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/fxml/Main.fxml"));
Scene scene = new Scene(root,600,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.setTitle("Test");
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
MainControl類:
package application;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
public class MainControl implements Initializable {
@FXML
Button button;
@FXML
TextField field1;
@FXML
TextField field2;
boolean field1selected=true;
public void initialize(URL arg0, ResourceBundle arg1) {
}
public void switchTextFeild(ActionEvent event){
/*
The code for switch on witch TextField is selected would go here
*/
}
}
Main.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<AnchorPane 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="application.MainControl">
<children>
<TextField fx:id="field1" layoutX="6.0" layoutY="2.0" prefHeight="394.0" prefWidth="149.0" />
<TextField fx:id="field2" layoutX="445.0" layoutY="2.0" prefHeight="394.0" prefWidth="149.0" />
<Button fx:id="button" layoutX="177.0" layoutY="14.0" mnemonicParsing="false" onAction="#switchTextFeild" prefHeight="95.0" prefWidth="239.0" text="Switch" textAlignment="CENTER" wrapText="true">
<font>
<Font size="24.0" />
</font>
</Button>
</children>
</AnchorPane>
您可以使用
field1.requestFocus();
在您的initialize()
方法中,因此在您的應用啟動后,您的TextField
field1將被聚焦。 但請注意,您必須將requestFocus()
調用包裝在
Platform.runLater(new Runnable() {
@Override
public void run() {
field1.requestFocus();
}
});
因為這應該在JavaFX Application線程而不是Launcher線程上完成,所以如果只調用field1.requestFocus()
則不會對我們的TextField
產生任何影響。
這很簡單
filedname.requestFocus();
fieldname.selectAll();
您必須首先獲得焦點,然后使用selectAll()function。 如果您不使用requestFocus()函數,則selectAll()將不起作用
對於經典Java,該解決方案很簡單。 您可以使用下面的代碼在textField中選擇文本,而無需雙擊它(對javafx不了解)。
field1.requestFocus();
field1.setSelectionStart(0);
field1.setSelectionEnd(field1.getText().length());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.