边框半径为 20 的 Javafx 标签

标签 java css javafx label cornerradius

我有 3 个标签,如下图所示。我希望第一个标签(Hello)在左上角和右上角有圆 Angular 边缘,虚拟标签在右下角和左下角有圆 Angular 边缘。

我尝试过 -fx-border-radius: 30;在 CSS 中,但它不起作用。请参阅我在 Hello 标签中定义的类。请帮忙!

package com.binaryname.view;
public class Main extends Application {

private ConversionController conversionController = new ConversionController();

private PopupWindow keyboard;

private final Rectangle2D visualBounds = Screen.getPrimary().getVisualBounds();
private final Rectangle2D bounds = Screen.getPrimary().getBounds();
private final double taskbarHeight = bounds.getHeight() - visualBounds.getHeight();

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

primaryStage.setTitle("Binary Name");

Label helloLbl = new Label("Hello");
helloLbl.setAlignment(Pos.CENTER);
helloLbl.setFont(Font.font("Comic Sans MS", FontWeight.BOLD, 68));
helloLbl.setStyle("-fx-background-color: red;padding: 20px;");
helloLbl.getStyleClass().add("hello-border-radius");
helloLbl.setTextFill(Color.web("#ffffff"));

Label myNameLbl = new Label("my name is");
myNameLbl.setAlignment(Pos.CENTER);
myNameLbl.setFont(Font.font("Comic Sans MS", 48));
myNameLbl.setStyle("-fx-background-color: red;padding: 20px;");
myNameLbl.setTextFill(Color.web("#ffffff"));

VBox logoBox = new VBox(10);
logoBox.setId("logo");
logoBox.getChildren().addAll(helloLbl, myNameLbl);
logoBox.setAlignment(Pos.CENTER);

TextArea nameTxtArea = new TextArea();
nameTxtArea.setWrapText(Boolean.TRUE);
nameTxtArea.getStyleClass().add("center-text-area");
nameTxtArea.setFont(Font.font("Comic Sans MS", 28));
nameTxtArea.setStyle("padding: 40px;");

Label dummy = new Label(" ");
dummy.setStyle("-fx-background-color: red;");
dummy.setFont(Font.font("Comic Sans MS", FontWeight.BOLD, 30));

Button printBtn = new Button("PRINT");
printBtn.setId("ipad-grey");
printBtn.setDisable(Boolean.TRUE);

Button convertBtn = new Button("Convert Now!");
convertBtn.setId("ipad-grey");
convertBtn.setOnAction(new EventHandler<ActionEvent>() {

@Override
    public void handle(ActionEvent event) {
        nameTxtArea.setText(conversionController.getBinaryName(nameTxtArea.getText()));
    convertBtn.setDisable(Boolean.TRUE);
    printBtn.setDisable(Boolean.FALSE);
    nameTxtArea.requestFocus();
    }
});

Button resetBtn = new Button("RESET");
resetBtn.setId("ipad-grey");
resetBtn.setOnAction(new EventHandler<ActionEvent>() {

    @Override
    public void handle(ActionEvent event) {
    // Reset
    nameTxtArea.setText("");
    convertBtn.setDisable(Boolean.FALSE);
    printBtn.setDisable(Boolean.TRUE);
    nameTxtArea.requestFocus();
    }
});

HBox hBox = new HBox(100);
hBox.setAlignment(Pos.CENTER);
hBox.getChildren().addAll(convertBtn, printBtn);

VBox vBox = new VBox(10);
vBox.setAlignment(Pos.TOP_CENTER);
vBox.getChildren().addAll(logoBox, nameTxtArea, dummy, hBox, resetBtn);
vBox.setStyle("-fx-background-color: red;margin: 20px;");

printBtn.setOnAction(new EventHandler<ActionEvent>() {

    @Override
    public void handle(ActionEvent event) {
    // Start printing
    print(vBox, nameTxtArea.getText());
    convertBtn.setDisable(Boolean.FALSE);
    printBtn.setDisable(Boolean.TRUE);
    nameTxtArea.setText("");
    nameTxtArea.requestFocus();
    }
});

Scene scene = new Scene(vBox);
        scene.getStylesheets().add(Main.class.getResource("/style.css").toExternalForm() );

primaryStage.setScene(scene);
primaryStage.initStyle(StageStyle.UNDECORATED);
primaryStage.setScene(scene);
primaryStage.setX(visualBounds.getMinX());
primaryStage.setY(visualBounds.getMinY());
primaryStage.setWidth(visualBounds.getWidth());
primaryStage.setHeight(visualBounds.getHeight());

adjustTextAreaLayout(nameTxtArea);

primaryStage.show();

// attach keyboard to first node on scene:
Node first = scene.getRoot().getChildrenUnmodifiable().get(0);
if (first != null) {
    FXVK.init(first);
    FXVK.attach(first);
    keyboard = getPopupWindow();
}

// Attach the on focus listener
nameTxtArea.focusedProperty().addListener((ob, b, b1) -> {
    if (keyboard == null) {
        keyboard = getPopupWindow();
    }

    keyboard.setHideOnEscape(Boolean.FALSE);
    keyboard.setAutoHide(Boolean.FALSE);
    keyboard.centerOnScreen();
    keyboard.requestFocus();

    Double y = bounds.getHeight() - taskbarHeight - keyboard.getY();
    nameTxtArea.setMaxHeight((bounds.getHeight() * 0.4));
    nameTxtArea.setMinHeight((bounds.getHeight() * 0.4));
    nameTxtArea.setPrefHeight((bounds.getHeight() * 0.4));

    /*
    * keyboard.yProperty().addListener(obs -> {
    * 
    * Platform.runLater(() -> { }); });
    */

});

}

/**
* The main() method is use to launch the Javafx gui.
* 
* @param args
*            not used
*/
public static void main(String[] args) {
    launch(args);
}

/**
* The print() method is use to print the text with given dimension
* 
* @param node1
*            to be printed
* @param text
*            to be written
*/
private void print(Node node1, String text) {
    // Create a printer job for the default printer

    Printer printer = Printer.getDefaultPrinter();
    Paper label = PrintHelper.createPaper("4x2",  Constants.PRINT_RECEIPT_VERTICAL, Constants.PRINT_RECEIPT_HOZRIZONTAL, Units.INCH);
    PageLayout pageLayout = printer.createPageLayout(label,    PageOrientation.LANDSCAPE, Printer.MarginType.EQUAL);

    PrinterJob job = PrinterJob.createPrinterJob();

    Node node = createFullNode(text);

    double scaleX = pageLayout.getPrintableWidth() /     node1.getBoundsInParent().getWidth();
    double scaleY = pageLayout.getPrintableHeight() / node1.getBoundsInParent().getHeight();
    node.getTransforms().add(new Scale(scaleX, scaleY));

    if (job != null) {
        // Print the node
        boolean printed = job.printPage(node);

        if (printed) {
            // End the printer job
            job.endJob();
        } else {
            // Write Error Message
            System.out.println("Printing failed.");
        }
    } else {
        // Write Error Message
        System.out.println("Could not create a printer job.");
    }

    node.getTransforms().remove(node.getTransforms().size() - 1);
}

/**
 * The getPopupWindow() method is use to show keyboard on demand
 * 
 * @return the keyboard instance
 */
private PopupWindow getPopupWindow() {

    @SuppressWarnings("deprecation")
    final Iterator<Window> windows = Window.impl_getWindows();

    while (windows.hasNext()) {
        final Window window = windows.next();
        if (window instanceof PopupWindow) {
            if (window.getScene() != null && window.getScene().getRoot() != null) {
                Parent root = window.getScene().getRoot();
                if (root.getChildrenUnmodifiable().size() > 0) {
                    Node popup = root.getChildrenUnmodifiable().get(0);
                    if (popup.lookup(".fxvk") != null) {
                        FXVK vk = (FXVK) popup.lookup(".fxvk");
                        // hide the keyboard-hide key
                        vk.lookup(".hide").setVisible(false);
                        return (PopupWindow) window;
                    }
                }
            }
            return null;
        }
    }
    return null;
}

/**
 * The createFullNode() method is use to create an imaginary node that will
 * be used for printing
 * 
 * @param text
 *            that will be printed
 * @return the node to be printed
 */
private Node createFullNode(String text) {

    Label helloLbl = new Label("Hello");
    helloLbl.setAlignment(Pos.CENTER);
    helloLbl.setFont(Font.font("Comic Sans MS", FontWeight.BOLD, 68));
    helloLbl.setStyle("-fx-background-color: red;padding: 20px;");
    helloLbl.setTextFill(Color.web("#ffffff"));

    Label myNameLbl = new Label("my name is");
    myNameLbl.setAlignment(Pos.CENTER);
    myNameLbl.setFont(Font.font("Comic Sans MS", 48));
    myNameLbl.setStyle("-fx-background-color: red;padding: 20px;");
    myNameLbl.setTextFill(Color.web("#ffffff"));

    VBox logoBox = new VBox(10);
    logoBox.setId("logo");
    logoBox.getChildren().addAll(helloLbl, myNameLbl);
    logoBox.setAlignment(Pos.CENTER);

    TextArea nameTxtArea = new TextArea();
    nameTxtArea.setWrapText(Boolean.TRUE);
    nameTxtArea.setFont(Font.font("Comic Sans MS", 28));
    nameTxtArea.setStyle("padding: 20px;");
    nameTxtArea.setText("\n\n\n\n" + text);
    nameTxtArea.getStyleClass().add("center-text-area");

    Label dummy = new Label(" ");
    dummy.setStyle("-fx-background-color: red;");
    dummy.setFont(Font.font("Comic Sans MS", FontWeight.BOLD, 50));

    VBox vBox = new VBox(10);
    vBox.setAlignment(Pos.CENTER);
    vBox.getChildren().addAll(logoBox, nameTxtArea, dummy);
    vBox.setStyle("-fx-background-color: red;margin: 20px;");

     vBox.getStylesheets().add(Main.class.getResource("/style.css").toExternalForm());

    return vBox;
}

/**
 * The adjustTextAreaLayout() method is use to adjust the textarea layout.
 * It will attach the listener when text is changed
 * 
 * @param textArea
 */
private void adjustTextAreaLayout(TextArea textArea) {
    textArea.applyCss();
    textArea.layout();

    ScrollPane textAreaScroller = (ScrollPane) textArea.lookup(".scroll-pane");
    Text text = (Text) textArea.lookup(".text");

    ChangeListener<? super Bounds> listener = (obs, oldBounds, newBounds) -> centerTextIfNecessary(textAreaScroller, text);
    textAreaScroller.viewportBoundsProperty().addListener(listener);
    text.boundsInLocalProperty().addListener(listener);

}

/**
 * The centerTextIfNecessary() method is called when each text written. This
 * method then calculate the vertical alignment
 * 
 * @param textAreaScroller
 * @param text
 */
private void centerTextIfNecessary(ScrollPane textAreaScroller, Text text) {
    double textHeight = text.getBoundsInLocal().getHeight();
    double viewportHeight = textAreaScroller.getViewportBounds().getHeight();
    double offset = Math.max(0, (viewportHeight - textHeight) / 2);
    text.setTranslateY(offset);
    Parent content = (Parent) textAreaScroller.getContent();
    for (Node n : content.getChildrenUnmodifiable()) {
        if (n instanceof Path) { // caret
            n.setTranslateY(offset);
        }
    }
}
}

这是我的界面

this is my interface

这是 style.css 中的整个 CSS 除了边框半径之外,一切正常。

.center-text-area *.text {
    -fx-text-alignment: center;
}

.helloLbl{
    -fx-border-radius: 20 20 0 0;
    -fx-background-radius: 20 20 0 0; 
}

#hello-radius{
    -fx-border-radius: 20 20 0 0;
    -fx-background-radius: 20 20 0 0;
}

#ipad-grey {
    -fx-background-color: 
        linear-gradient(#686868 0%, #232723 25%, #373837 75%, #757575 100%),
        linear-gradient(#020b02, #3a3a3a),
        linear-gradient(#b9b9b9 0%, #c2c2c2 20%, #afafaf 80%, #c8c8c8 100%),
        linear-gradient(#f5f5f5 0%, #dbdbdb 50%, #cacaca 51%, #d7d7d7 100%);
    -fx-background-insets: 0,1,4,5;
    -fx-background-radius: 9,8,5,4;
    -fx-padding: 15 30 15 30;
    -fx-font-family: "Arial Rounded MT Bold";
    -fx-font-size: 30px;
    -fx-font-weight: bold;
    -fx-text-fill: #333333;
    -fx-effect: dropshadow( three-pass-box , rgba(255,255,255,0.2) , 1, 0.0 , 0 , 1);
    margin: 100px;
    -fx-pref-width: 300px;
}

#ipad-grey Text {
    -fx-effect: dropshadow( one-pass-box , white , 0, 0.0 , 0 , 1 );
}

#logo {
    -fx-background-image: url("cmh_logo_trans.png");
    -fx-background-repeat: no-repeat;   
    -fx-background-size: 270 190;
    -fx-background-position: top left;
}

这是fxml

<?import javafx.scene.layout.BorderPane?>

<BorderPane xmlns:fx="http://javafx.com/fxml/1">
    <!-- TODO Add Nodes -->
</BorderPane>

最佳答案

我通过设置新背景并为其指定一个cornerRadius值来获得边框半径。就像这样..

    Label lbl = new Label();
    Color col = Color.rgb(205,205,205);
    CornerRadii corn = new CornerRadii(10);
    Background background = new Background(new BackgroundFill(col, corn, Insets.EMPTY));
    lbl.setBackground(background);

关于边框半径为 20 的 Javafx 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42770640/

相关文章:

填充 ListView 时出现 JavaFx NullPointer 异常

javafx-2 - JavaFX,如何卡住TableView中某些列的位置

JavaFX 和 Spring - bean 不 Autowiring

java - 是否可以在不重写的情况下将数据添加到文件中?

java - 使用WildFly模块的数据源和connectionFactory

jquery - 在一行中 Bootstrap HTML 输入字段

html - 水平显示元素而不是列

java - Eclipse 中的 setfullscreen(boolean) 用于在场景生成器中设计的 UI

java - java中将字符串分割成字符

html - 方框出现在页脚下方。以上要求