首页 > 解决方案 > 一个正方形可以有两个按钮吗?

问题描述

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


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

标签: buttonjavafx

解决方案


这是您想要完成的示例(代码注释中的说明):

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();
  }
}

这就是它的样子:

示例应用程序的 GIF

不幸的是,我不相信您可以向按钮添加文本或图形。文本/图形仍将以按钮为中心,就好像它是一个矩形一样。当您将该shape属性设置为非空值时,任何背景图像都会被忽略。如果您需要更多控制,请考虑创建自己的“控制”(例如变形);上述用途的原因Button是您可以获得按钮的所有内置行为。


推荐阅读