Button 一个正方形中有两个按钮吗?

Button 一个正方形中有两个按钮吗?,button,javafx,Button,Javafx,我正在使用javafx,我需要一个正方形除以它的对角线,其中每一半是一个不同的按钮,我已经找到了如何塑造一个按钮,但我不知道如何编码这个新组件。 想法是: 如上所述,每一半都必须是一个不同的按钮,任何帮助都会很好。谢谢大家! 下面是一个您想要实现的示例(代码注释中的解释): 这就是它看起来的样子: 不幸的是,我不相信你可以添加文本或图形按钮。文本/图形仍将居中于按钮上,就像它是一个矩形一样。当您将shape属性设置为非空值时,将忽略任何背景图像。如果你需要更多的控制,那么考虑创建你自己的“控制

我正在使用javafx,我需要一个正方形除以它的对角线,其中每一半是一个不同的按钮,我已经找到了如何塑造一个按钮,但我不知道如何编码这个新组件。 想法是:



如上所述,每一半都必须是一个不同的按钮,任何帮助都会很好。谢谢大家!

下面是一个您想要实现的示例(代码注释中的解释):

这就是它看起来的样子:


不幸的是,我不相信你可以添加文本或图形按钮。文本/图形仍将居中于按钮上,就像它是一个矩形一样。当您将
shape
属性设置为非空值时,将忽略任何背景图像。如果你需要更多的控制,那么考虑创建你自己的“控制”(例如,形状之外);上面使用
按钮的原因是,您可以获得按钮的所有内置行为。

从技术上讲,您可以将文本/标签节点设置为图形,并根据需要应用转换,而无需更好地描述OP想要实现的功能(事实上,s/他没有提供任何东西,除了一张似乎足以吸引潜在的假日无聊开发人员采取行动的图片)没有什么进一步的。
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();
  }
}