本页面由葡萄牙语机器翻译,可能存在错误。葡萄牙语版本为准。
如何用 Alert 请求确认
目的。 显示一个带标题、消息和一个或多个按钮的模态对话框,并 根据被按下的按钮执行操作。用于破坏性确认 (「删除?」)、需要用户知晓的提示,或简单的选择。
所用 API
new Alert(String title, String message, String... buttonTexts)— 创建警告框。按钮文本在构造函数中传入(索引 0、1、2……)。如果未提供任何按钮,则使用"OK"。alert.buttonAction(int index, Component.Action action)— 注册该索引按钮的回调。不存在addButton;按钮已在构造函数中声明。alert.show()— 显示对话框(继承自Window)。alert.getStyle().fadeBackground(int alpha)— 使警告框背后的背景变暗(0–255)。getStyle()返回警告框的WindowStyle。alert.getButton(int index)— 返回该索引的Button(在show()之后可用)。
不易察觉的行为:如果你没有为某个按钮注册
buttonAction, 它在被点击时只会关闭警告框(hide())。因此对于「取消」,很多时候 你甚至不需要回调。
完整示例(复制、粘贴即可运行)
package com.exemplo;
import dev.crossfly.ui.*;
import dev.crossfly.ui.layout.*;
/** 可执行的主界面。将 launcher 指向此类(classname)并运行:gradlew :lwjgl3:run */
public class MainWindow extends Window
{
@Override
public void onShow() throws Exception
{
super.onShow();
setLayout(new VerticalLayout());
// 触发按钮:点击时打开 Alert
Button btn = new Button("Excluir registro");
btn.onAction(origin ->
{
Alert alert = new Alert(
"Excluir registro",
"Esta ação não pode ser desfeita. Deseja continuar?",
"Cancelar", // 索引 0
"Excluir"); // 索引 1
// 使背景变暗(可选,但破坏性模态框推荐使用)
alert.getStyle().fadeBackground(150);
// 按钮 0(Cancelar)无回调 → 只关闭。
// 按钮 1(Excluir)执行动作并关闭:
alert.buttonAction(1, o ->
{
excluirRegistro();
alert.hide();
});
alert.show();
});
add(LAY_FILL, btn);
}
private void excluirRegistro()
{
// ... 你的删除逻辑 ...
}
}
下面的片段只展示核心部分。要运行它,请把它放进上面的
MainWindow骨架中。
最小片段
Alert alert = new Alert(
"Excluir registro",
"Esta ação não pode ser desfeita. Deseja continuar?",
"Cancelar", // 索引 0
"Excluir"); // 索引 1
// 使背景变暗(可选,但破坏性模态框推荐使用)
alert.getStyle().fadeBackground(150);
// 按钮 0(Cancelar)无回调 → 只关闭。
// 按钮 1(Excluir)执行动作并关闭:
alert.buttonAction(1, origin ->
{
excluirRegistro();
alert.hide();
});
alert.show();
验证说明(2026 代码)。 已在源码中确认:构造函数
Alert(title, message, String... buttonTexts)+buttonAction(int, Action)。 按钮布局(iOS/Material/Flutter)由当前Skin的AlertStyle决定—— 更换Skin(或使用alert.skin(new IOSSkin()))即可改变外观 而无需改动逻辑代码。警告框的宽度/高度会根据 标题、消息和按钮自动计算。
深入了解
- 控件页面:Alert · 权威来源:第 16 章
- 姊妹配方:操作菜单(ActionSheet) · 显示 Hint
这个页面有帮助吗?感谢你的反馈!