# 处理输入

> onAction 与 onActionThread、焦点、TextField/TextArea 以及触摸/手势处理器。

Source: https://crossfly.dev/zh/docs/learn/handling-input — CrossFly documentation. Full docs as one file: https://crossfly.dev/llms-full.txt

# 6. 处理输入

> **你将学到:** 响应触摸、按键和手势,以及读取文本输入。**前置条件:** [样式与主题](/docs/learn/styling-and-themes)。

## 完整示例(复制、粘贴、运行)
添加任务的表单:输入框 + 带校验的按钮,在提交时读取文本并用 `Hint` 反馈。将任务添加到一个输出 `Label` 中。可直接编译运行。
```java
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`
```java
botao.onAction(c -> salvar());          // 在 paint thread 上运行（快速，操作 UI）
botao.onActionThread(c -> {             // 在后台线程运行（繁重的工作）
   var dados = baixar();
   c.onUI(() -> mostrar(dados));         // 回到 UI
});
```

## 文本输入 —— 在提交时读取
没有按键级别的事件:需要时调用 `getText()` 读取(例如在按钮里)。
```java
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()`。

## 触摸手势(可重写)
在自定义组件中,重写各处理器以处理手势:
```java
@Override public void onLongTouch(float x, float y) throws Exception { abrirDetalhe(); }
// 还有：onTouchDown/onTouchUp/onPan
```
> 回调中的异常会送往 `Debug.handle`(不会向上冒泡以致于让帧崩溃)。

## 本步骤所构建的
**添加任务的表单**(输入框 + 按钮 + 校验)以及打开详情的**手势**。

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

## 下一步
→ [管理状态](/docs/learn/managing-state)

## 另见
- [表单与输入(ui)](/docs/ui/forms-and-input) · 权威来源:第 6 章 · 第 14 章
