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

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

6. 处理输入

你将学到: 响应触摸、按键和手势,以及读取文本输入。前置条件: 样式与主题。

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

添加任务的表单:输入框 + 带校验的按钮,在提交时读取文本并用 Hint 反馈。将任务添加到一个输出 Label 中。可直接编译运行。

package com.exemplo;

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

public class MainWindow extends Window
{
   private final TextField campo = new TextField().caption("Nova tarefa");
   private final Label saida = new Label("Nenhuma tarefa ainda");

   @Override
   public void onShow() throws Exception
   {
      super.onShow();
      setLayout(new VerticalLayout());

      add(LAY_AUTO, campo);

      Button add = new Button("Adicionar");
      add.onAction(c -> {                                 // 在 paint thread 上运行
         String texto = campo.getText().trim();
         if (texto.isEmpty()) { Hint.show("Digite algo", 2000); return; }   // 验证(2 个参数)
         adicionarTarefa(texto);
         campo.clearText();
      });
      add(LAY_AUTO, add);

      add(LAY_AUTO, saida);
   }

   private void adicionarTarefa(String texto)
   {
      saida.setText("Adicionada: " + texto);
      saida.repaint();
   }
}

下面的片段只展示核心部分(放在 onShow() 里的内容)。要运行,请把它们放进上面的 MainWindow 骨架里。

onAction 与 onActionThread

botao.onAction(c -> salvar());          // 在 paint thread 上运行(快速,操作 UI)
botao.onActionThread(c -> {             // 在后台线程运行(繁重的工作)
   var dados = baixar();
   c.onUI(() -> mostrar(dados));         // 回到 UI
});

文本输入 —— 在提交时读取

没有按键级别的事件:需要时调用 getText() 读取(例如在按钮里)。

TextField campo = new TextField().caption("Nova tarefa");
Button add = new Button("Adicionar");
add.onAction(c -> {
   String texto = campo.getText().trim();
   if (texto.isEmpty()) { Hint.show("Digite algo", 2000); return; }   // 验证
   adicionarTarefa(texto);
   campo.clearText();
});

焦点:当需要响应获得/失去焦点时,在子类中重写 onFocus()/onBlur()。

触摸手势(可重写)

在自定义组件中,重写各处理器以处理手势:

@Override public void onLongTouch(float x, float y) throws Exception { abrirDetalhe(); }
// 还有:onTouchDown/onTouchUp/onPan

回调中的异常会送往 Debug.handle(不会向上冒泡以致于让帧崩溃)。

本步骤所构建的

添加任务的表单(输入框 + 按钮 + 校验)以及打开详情的手势。

回顾

onAction(UI)/ onActionThread(后台);在提交时用 getText() 读取文本;手势通过可重写的处理器;错误送往 Debug.handle。

下一步

→ 管理状态

另见

这个页面有帮助吗?