跳到内容
CrossFly 是 100% 开源在 GitHub 关注我们
CrossFlyCrossFly
开始使用

本页面由葡萄牙语机器翻译,可能存在错误。葡萄牙语版本为准。

如何在执行破坏性操作前请求确认

目的。 在删除/丢弃某个内容之前,显示一个带两个按钮的 Alert(例如:“取消” 和 “删除”)。只在确认按钮的回调中执行破坏性操作。

使用的 API

  • new Alert(String title, String message, String... buttonTexts) — 创建对话框。Alert 是一个 Window;按钮遵循当前激活的 Skin。
  • Alert.buttonAction(int index, Component.Action action) — 定义某个按钮的动作(索引从 0 开始)。若不设置动作,按钮只会关闭对话框(hide())。
  • Alert.show() — 将对话框入栈(推入模态)。
  • WindowStyle.fadeBackground(int alpha) — 使下方的窗口变暗(0–255)。通过 getStyle() 获取 style。
  • Hint.show(String message, int delayMs) — 显示一个简短的反馈提示(toast)。

完整示例(复制、粘贴并运行)

package com.exemplo;

import dev.crossfly.ui.*;
import dev.crossfly.ui.layout.*;

/** 可执行主屏:一个按钮触发确认用的 Alert。 */
public class MainWindow extends Window
{
   @Override
   public void onShow() throws Exception
   {
      super.onShow();
      setLayout(new VerticalLayout());

      add(new Label("Pedido #1234"));
      add(new Button("Excluir pedido").onAction(e -> confirmarExclusao()));
   }

   private void confirmarExclusao()
   {
      Alert alert = new Alert("Excluir pedido", "Esta ação não pode ser desfeita.", "Cancelar", "Excluir");

      // 使背景变暗(0..255)。Alert 的 getStyle() 是一个 WindowStyle。
      ((WindowStyle) alert.getStyle()).fadeBackground(150);

      // 索引 0 = "Cancelar":不设 buttonAction,按钮自身即可关闭 Alert。
      // 索引 1 = "Excluir":破坏性操作 + 反馈。
      alert.buttonAction(1, e ->
      {
         excluirPedido();                 // 破坏性操作
         alert.hide();                    // 关闭对话框
         Hint.show("Pedido excluído", 1500);
      });

      alert.show();
   }

   private void excluirPedido()
   {
      // ... 你的删除逻辑 ...
   }
}

下面的片段只展示 核心部分。要运行它,请把它放进上面的 MainWindow 骨架里。

最小片段

// 已在源码核对:Alert.buttonAction(idx, Action);WindowStyle.fadeBackground(int 0-255);Hint.show(msg, ms)
Alert alert = new Alert("Excluir pedido", "Esta ação não pode ser desfeita.", "Cancelar", "Excluir");

// 使背景变暗(0..255)。Alert 的 getStyle() 是一个 WindowStyle。
((WindowStyle) alert.getStyle()).fadeBackground(150);

// 索引 0 = "Cancelar":不设 buttonAction,按钮自身即可关闭 Alert。
// 索引 1 = "Excluir":破坏性操作 + 反馈。
alert.buttonAction(1, e ->
{
   excluirPedido();                 // 破坏性操作
   alert.hide();                    // 关闭对话框
   Hint.show("Pedido excluído", 1500);
});

alert.show();

避免意外的细节:

  • 如果你 没有 为某个按钮设置 buttonAction,Alert 会为它关联 onAction(e -> hide()) —— 该按钮只会关闭对话框,不做别的事。因此 “取消” 通常无需 buttonAction。
  • 始终 把破坏性操作放在确认按钮上(这里是索引 1),绝不要作为默认行为。
  • fadeBackground 接收 0–255 的 alpha 值(不是 0xAARRGGBB)。150 能带来可察觉的变暗效果,同时不会遮住内容。

深入了解

这个页面有帮助吗?