JavaFx隐藏TextArea-VScrollbar

时间:2017-05-01 18:04:18

标签: java javafx javafx-8

查找这个问题我找到了这个片段:

  

删除垂直滚动条

ScrollBar scrollBarv = (ScrollBar)ta.lookup(".scroll-bar:vertical");
scrollBarv.setDisable(true);
  

CSS

.text-area .scroll-bar:vertical:disabled {
-fx-opacity: 0;
}

但这不适合我。 我创建了一个最小的例子:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollBar;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;


public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        BorderPane root = new BorderPane();

        TextArea textArea = new TextArea();

        root.setCenter(textArea);

        Scene scene = new Scene(root, 400, 400);
        scene.getStylesheets().add("Style.css");

        ScrollBar scrollBar = (ScrollBar) textArea.lookup(".scroll-bar:vertical");
        System.out.println(scrollBar);
        scrollBar.setDisable(true);

        primaryStage.setScene(scene);

        primaryStage.show();
    }
}

CSS:

.text-area .scroll-bar:vertical:disabled {
-fx-opacity: 0;
}

但我得到的只是一个Nullpointer-Exception。

Exception in Application start method
null
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
at    com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at Main.start(Main.java:33)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more

那么我做错了什么还是有另一种解决方案?

1 个答案:

答案 0 :(得分:1)

问题是lookup()在呈现场景之前不起作用。改变顺序。

@Override
public void start(Stage primaryStage) throws Exception {

    BorderPane root = new BorderPane();

    TextArea textArea = new TextArea();

    root.setCenter(textArea);

    Scene scene = new Scene(root, 400, 400);
    scene.getStylesheets().add("Style.css");

    primaryStage.setScene(scene);

    primaryStage.show();

    ScrollBar scrollBar = (ScrollBar) textArea.lookup(".scroll-bar:vertical");
    System.out.println(scrollBar);
    scrollBar.setDisable(true);
}