Ярлык Javafx с радиусом границы 20
У меня есть 3 метки, как показано на рисунке ниже. Я хотел бы, чтобы первая метка (Hello) имела закругленные края в верхнем левом и верхнем правом углу, а фиктивная метка имела закругленные края в правом нижнем и нижнем левом углу.
Я пробовал -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);
}
}
}
}
Это мой интерфейс
Это весь CSS в style.css Все работает отлично, за исключением border-radius.
.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>
2 ответа
Я получил радиус границы, установив новый фон и присвоив ему значение 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);
Вы можете округлить любой край, который вы хотите, как это
.helloLbl{//hello label id
-fx-border-radius: 20 20 0 0;
-fx-background-radius: 20 20 0 0;
/* top-left, top-right, bottom-right, and bottom-left corners, in that order. */
}