button - 一个正方形可以有两个按钮吗?
问题描述
我正在使用 javafx,我需要将一个正方形除以它的对角线,其中每一半是一个不同的按钮,我已经找到了如何塑造一个按钮,但我不知道如何编写这个新组件。这个想法是:
如上所述,每一半都必须是一个不同的按钮,任何帮助都会很棒。谢谢!
解决方案
这是您想要完成的示例(代码注释中的说明):
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;
public class Main extends Application {
/*
* You can manipulate the shape of any Region via the Region#shape property.
* The shape will, by default, be scaled to fit the size of the region (see
* Region#scaleShape property). This means you only need to set the proportions
* of the shape.
*
* You'll also want to set the Node#pickOnBounds property to false. This way
* the mouse only interacts with the shape of the Region instead of the whole
* bounds which will remain rectangular.
*/
@Override
public void start(Stage primaryStage) {
var btn1 = new Button();
// triangle with its 90° corner in the top-left
btn1.setShape(new Polygon(0, 0, 1, 0, 0, 1));
// only interact with the shape of the button (the bounds are still rectangular)
btn1.setPickOnBounds(false);
// allow the button to grow to fill available space
btn1.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
btn1.setOnAction(e -> System.out.println("button-1"));
btn1.setStyle("-fx-base: green;");
var btn2 = new Button();
// triangle with its 90° corner in the bottom-right
btn2.setShape(new Polygon(1, 1, 0, 1, 1, 0));
// only interact with the shape of the button (the bounds are still rectangular)
btn2.setPickOnBounds(false);
// allow the button to grow to fill available space
btn2.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
btn2.setOnAction(e -> System.out.println("button-2"));
btn2.setStyle("-fx-base: purple;");
// a StackPane centers its children on top of each other, but since
// we have two triangles taking up half a square the buttons will
// appear to be positioned in the corners
var container = new StackPane(btn1, btn2);
// keep container square (so the triangles take up half the area)
container.setMaxSize(150, 150);
primaryStage.setScene(new Scene(new StackPane(container), 300, 300));
primaryStage.show();
}
}
这就是它的样子:
不幸的是,我不相信您可以向按钮添加文本或图形。文本/图形仍将以按钮为中心,就好像它是一个矩形一样。当您将该如果您需要更多控制,请考虑创建自己的“控制”(例如变形);上述用途的原因shape
属性设置为非空值时,任何背景图像都会被忽略。Button
是您可以获得按钮的所有内置行为。
推荐阅读
- flutter - Flutter 重建 Consumer 的父小部件
- python - Databricks Pyspark - Java 堆空间错误
- wpf - 击中断点时鼠标冻结/滞后
- blazor - 将 Blazor Webassembly 项目包含到现有 ASP.NET Core 项目中
- javascript - 检测触摸设备捏合程度(缩放)
- visual-studio - 打开 VS 2019 社区版
- vue.js - 为什么 Vue 无法识别 v-html 属性中使用的数据成员?
- javascript - 我正在尝试用 Javascript 制作计算器。但它不工作
- java - 使用 maven-compiler-plugin 从编译中排除 src/main/java
- jenkins - ZAP 扫描:Jenkins 作业失败 (url_not_in_context)