英文:
JavaFx : Is it possible to align the Box above the Text content in a checkbox?
问题
我想要实现类似于以下的效果:
答案1
得分: 5
以下是一个简单的示例,实现您想要的功能。更专业的方式是实现一个自定义的皮肤。也许其他人会分享它。
App:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.Pane;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
public class App extends Application {
@Override
public void start(Stage stage) {
// 首先创建一个分离的标签:
Label label = new Label("Am efectuat toate");
// 创建一个没有文本的复选框
CheckBox checkBox = new CheckBox();
// 将复选框放置为标签的图形节点:
label.setGraphic(checkBox);
// 将框放在标签的顶部显示:
label.setContentDisplay(ContentDisplay.TOP);
// 在标签的主鼠标按钮单击时切换复选框的选择属性:
label.setOnMouseClicked(mouseEvent -> {
if (mouseEvent.getButton() == MouseButton.PRIMARY)
checkBox.setSelected(!checkBox.isSelected());
});
// 如果您想要在第二行中有最后一个词“toate”:
label.setWrapText(true);
label.setMaxWidth(80);
label.setTextAlignment(TextAlignment.CENTER);
// 创建场景并显示:
Pane root = new Pane();
root.getChildren().add(label);
stage.setScene(new Scene(root, 120, 60));
stage.show();
}
public static void main(String[] args) {
launch();
}
}
预览:
英文:
Below is one simple example of achieving what you want. The more professional way would be to implement a custom skin. Maybe someone else will share it.
App:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.Pane;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
public class App extends Application {
@Override
public void start(Stage stage) {
// Create a separated label at first:
Label label = new Label("Am efectuat toate");
// Create a check box without a text
CheckBox checkBox = new CheckBox();
// Put the check box as the graphic node of the label:
label.setGraphic(checkBox);
// Put the box on top of the label:
label.setContentDisplay(ContentDisplay.TOP);
// Toggle selected property of checkbox on label primary mouse button click:
label.setOnMouseClicked(mouseEvent -> {
if (mouseEvent.getButton() == MouseButton.PRIMARY)
checkBox.setSelected(!checkBox.isSelected());
});
// If you want to have the last word "toate" in a second line:
label.setWrapText(true);
label.setMaxWidth(80);
label.setTextAlignment(TextAlignment.CENTER);
// Create scene and show:
Pane root = new Pane();
root.getChildren().add(label);
stage.setScene(new Scene(root, 120, 60));
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Preview:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论