如何使用 javafx 隐藏或停用 TextField 和 Label

How to hide or deactivate a TextField and a Label with javafx

我想在我的 JavaFX 应用程序中隐藏或停用 TextField 及其 Label

这是我试过的

myTextField.setVisible(false);

,但它不起作用

我在 windows 7 上使用 Eclipse V4.5.0 和 jfx8 V2.0.0

我不确定我是否正确理解了你的问题,但我会尽力回答我的理解。

如果您只想停用 TextField,您可以使用:

myTextField.setEditable(false);

这不会 "hide" TextField 它只是不可编辑。

根据您提供的代码,问题可能出在静态创建(在 FXML 中)TextField。我的建议是尝试在运行时动态创建 PaneTextField。 下面是如何在运行时创建和使用 JavaFX 组件的简单示例:

public class ButtonInPane extends Application{ 
// Override the start method in the Application class
Button btn=new Button("OK");
HBox cont;
TextField myTextField;

public void start(Stage stage1){ 


    Label myLable=new Label("Some Lable");
    myTextField=new TextField("Some text");
    cont=new HBox();
    cont.getChildren().addAll(myLable,myTextField);

    Stage stage = new Stage(); //this instead of JFrame
    FlowPane pane2 = new FlowPane(); //this instead of JPanel

    pane2.getChildren().addAll(btn,cont);  
    Scene scene2 = new Scene(pane2, 250, 50);
    stage.setTitle("Button in a FlowPane"); // Set the stage title
    stage.setScene(scene2); // Place the scene in the stage
    stage.show(); // Display the stage
    stage.setAlwaysOnTop(true);

    //set event 
    setEventActions();
}
private void handlePlayAction() {
    cont.setVisible(false);

    //OR  myTextField.setVisible(false);

}
private void setEventActions() {
    this.btn.setOnAction(event -> this.handlePlayAction());
}
public static void main(String[] args)
{ launch(args);
}
}

我知道您想 hide/show 一个文本字段 (javaFX),我通常使用与您提到的相同的方法 假设文本字段变量名称为 field 那么:

隐藏它使用

field.setVisible(false);

显示它使用

field.setVisible(true);

它对我一直有效。

在 JavaFX 中隐藏和停用 TextField 是有区别的。

隐藏:- 您需要将可见 属性 设置为 false。

它在您的情况下不起作用的可能原因是,如果您跳过了为您的 TextField 或 Label 提及 fx:id。

如果使用并设置 fx:id="myTextField" ,只需通过 fxml 即可,然后您编写的相同代码将开始工作。

同样用于隐藏任何标签。

要停用:- 有一个名为 disable 的字段,只需将 disable 属性 设置为 true 即可禁用或停用任何字段。

您也可以像这样为 .fxml 文件中的标签执行此操作:

<Label layoutX="349.0" layoutY="85.0" 
   text="Label" visible="false" fx:id="actionSuccessLabel"/>

然后稍后在您的控制器 class 中显示它,如下所示:

actionSuccessLabel.setVisible(true);

不要忘记在 setVisible 或可见 属性 绑定 after 新函数。

TextField textField = new TextField(field.getValue());
textField.visibleProperty().bind(field.getVisibleProperty());

您可以使用:

myTextField.setDisable(true);

它将禁用特定操作的字段。