Textfield CSS styling using JavaFx

旧时模样 提交于 2019-11-29 15:46:13

问题


I'm trying to style some textfields using JavaFX, but I'm not getting desired results. My goal is to have the textfield be represented by a singular underline. Here's my CSS:

.text-field{
   -fx-font-family: "Quicksand";
   -fx-font-size: 18;
   -fx-padding: 1,1,1,1;
   -fx-border-color: grey;
   -fx-border-width: 2;
   -fx-border-radius: 1;
   -fx-border: gone;
   -fx-background-color: transparent;
   -fx-text-fill: grey;
}

I have researched this question, but the answers I find to similar ones don't really contain enough information to reproduce and apply properly to my program. It doesn't help that I'm not very knowledgeable about CSS styling. I've tried to use insets with minimal results. Thank you for any answers provided!


回答1:


The following works for me:

/* File style.css */

.text-field {
    -fx-background-color: -fx-text-box-border, -fx-background ;
    -fx-background-insets: 0, 0 0 1 0 ;
    -fx-background-radius: 0 ;
}
.text-field:focused {
    -fx-background-color: -fx-focus-color, -fx-background ;
}

The following test harness for this

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class TextFieldStyleTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        GridPane root = new GridPane();
        root.setHgap(10);
        root.setVgap(5);
        for (int row = 0 ; row < 4; row++) {
            for (int col = 0 ; col < 2; col++) {
                root.add(new TextField(), col, row);
            }
        }
        root.setPadding(new Insets(5));
        Scene scene = new Scene(root);
        scene.getStylesheets().add("style.css");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

produces




回答2:


Since you only want an underline, the minimum things you will need are

.text-field {
  -fx-border-color: grey;
  -fx-border width: 0 0 1 0; // top, right, bottom, left
  -fx-background-color: transparent;
}

This will change the border color to grey, set the border width to 0 for everything but the bottom border, and back the textfield's background transparent so it is not white.



来源:https://stackoverflow.com/questions/46812588/textfield-css-styling-using-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!