如何使用JavaFX创建弹出框



下面的代码创建了一个用按钮填充的网格。我想知道如何添加一个方法,弹出另一个带有数字的网格框。当在第二个弹出的网格框上选择数字时,它会更改单击的原始按钮上的标签。以下面的例子为例,有人点击了文本为"1"的按钮。弹出一个带有标记为1到5的按钮的网格。单击按钮5。弹出的网格框消失,上面有文本"1"的按钮现在变为"5"。

import javafx.application.*;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
    public class GUI extends Application {
        public static void main(String[] args) {
            Application.launch(args);
    }

    @Override public void start(Stage primaryStage)
    {
        final int HGAP = 2;
        final int VGAP = 2;
        final int BUTTONSIZE = 50;
        final int INSET = 5;
        final int SIZE = 4;
        GridPane root = new GridPane();
        root.setPadding(new Insets(INSET));
        root.setHgap(HGAP);
        root.setVgap(VGAP);
        root.setAlignment(Pos.CENTER);
        final Button[][] btn = new Button[SIZE][SIZE];
        final Paint background = Color.TURQUOISE;
        int index = 0;
        for ( int theCol = 0; theCol < SIZE; theCol++) {
            for ( int theRow = 0; theRow < SIZE; theRow++) {
                btn[theRow][theCol] = new Button(""+ index);
                btn[theRow][theCol].setPrefSize(BUTTONSIZE, BUTTONSIZE);
                root.add(btn[theRow][theCol], theRow, theCol);
                index++;
                btn[theRow][theCol].setOnMouseClicked(new EventHandler<MouseEvent>()
                {
                    @Override
                    public void handle(MouseEvent arg0) 
                    {
                        Button b= (Button)arg0.getSource();
                        System.out.println(b.getText());
                    }
                });
            }
        }
        Scene scene = new Scene(root,background);
        primaryStage.setTitle("Grid");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

您可以使用PopupControl:

  PopupControl popup = new PopupControl();
  popup.getScene().setRoot(yourGridPane);
  popup.show(yourGridPane.getScene().getWindow());

在按钮监听器中,您可以调用popup.hide()来关闭弹出窗口并更新按钮文本

Yoy也可以用这种方式尝试

        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        final Text infoText = new Text();
        grid.setPadding(new Insets(10, 10, 10, 10));
        grid.add(infoText, 0, 4, 2, 1);
        final Dialog dlg = new Dialog(null, "dialog");
        dlg.setContent(grid);
        dlg.show();

最新更新