跳到正文
cccskills
免费在 GitHub 公开中文介绍

kotlin-ui-swing-component-architecture

用于设计或评审 IntelliJ 产品中的 Swing 界面结构,明确视图、控制器、状态、异步任务和生命周期职责,并关注 EDT 安全更新与精简设计。

原文查看原文说明

Design IntelliJ Swing UI components, state flow, and EDT work.

JetBrains/intellij-community星标 20,685(GitHub 20,685 + cccskills 0)

实测评分 未实测

查看安装方法

适用场景

  • 梳理 Swing 界面的职责
  • 检查 EDT 与异步任务
  • 设计界面状态和释放流程
  • 评审 IntelliJ 插件界面

中文介绍

功能

本技能帮助整理 IntelliJ 产品中 Swing 界面的功能边界和职责,并提出与功能规模相称的组件结构。视图负责构建和绘制控件,控制器负责验证输入并调用服务,服务则处理不依赖界面的应用逻辑。状态较复杂时,可采用不可变状态和单向数据流。资料还涵盖异步任务的取消、过期结果的处理、在事件调度线程(EDT)上安全更新界面,以及销毁时的清理。整体上优先组合现有控件,避免没有必要的抽象或大规模重写。

适用场景

创建、修改或评审 IntelliJ 插件等 Swing 界面时适用。如果界面类同时承担服务调用或异步工作,或者状态、线程和销毁处理的职责不清,也可用它考虑必要且精简的拆分。

使用示例

  • “请整理这个 Swing 界面中视图和控制器的职责。”
  • “请检查是否有阻塞 EDT 的操作或遗漏的销毁清理。”
  • “请为这个异步搜索设计精简的状态管理。”

注意事项

如果要新增可复用的 Swing 控件或自定义绘制,资料要求说明这样做的理由及标准控件无法替代的原因,并取得用户明确批准。

本介绍由 AI(OpenAI Codex)根据公开的 SKILL.md 撰写。准确的规格请查看下方原文。

文档检查

AI 根据 SKILL.md 的内容检查了需要注意的操作和使用前提。评分只依据实际运行的结果(实测对比)。

安全性发送数据、删除文件、执行命令等是否有说明
A良好新增可复用控件或自定义绘制前,要求说明理由并取得明确批准。
安装难易度所需工具和 API 密钥是否少且有说明
A良好资料以设计和评审流程为主,未要求额外工具或凭据。

不计入评分。 由 AI(OpenAI Codex)于 2026年10月28日 评估。仅供参考,安装前请同时查看原文。

如果您认为评估有误,请申请复核

请写明哪一项有误以及原因。无需登录。我们会对照 SKILL.md 重新评估,并在此处更新结果。

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

包含的文件(1)

  • SKILL.md16.8 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

<!-- Generated by community/.ai/render-guides.mjs; edit community/.agents/skills/kotlin-ui-swing-component-architecture/SKILL.md -->

Swing feature component architecture

Design Swing UI as isolated feature components with unidirectional data flow, explicit state, and clear EDT and lifecycle ownership. Introduce the smallest architecture that cleanly separates responsibilities; do not enforce MVC, MVP, MVVM, or MVI by name.

Workflow

  1. Read the local module instructions and inspect the whole feature boundary, including callers, services, listeners, asynchronous work, and disposal.

  2. Map ownership of rendering, user intent, UI state, application logic, asynchronous work, navigation, and lifecycle.

  3. Choose the lowest architecture level that makes those responsibilities clear.

  4. Keep Swing in the View, coordinate behavior in the Controller when one is needed, and keep application services independent of Swing.

  5. Make data flow one-way where state or workflows are non-trivial:

    user -> View --Intent--> Controller --calls--> Services
              ^                  |
              '--- render(State)-'
    
  6. Verify EDT safety, cancellation, disposal, state transitions, and the minimal public API.

  7. Apply the UI accessibility skill when creating, changing, or reviewing the UI itself.

Choose the architecture level

Treat line counts as prompts to inspect complexity, not hard thresholds.

  • Level 1 — one View or component class: Start here for a small feature, roughly under 200 LOC, containing only layout and local presentation behavior. Extract a Controller if it invokes services, owns workflows, or becomes hard to test or reason about.
  • Level 2 — View + Controller: Start here around 200-600 LOC when validation, services, navigation, or non-trivial interactions are present. Add immutable State when several visual modes or concurrent operations make implicit state ambiguous.
  • Level 3 — State + explicit Intent, optionally Reducer and Effects: Consider this for several asynchronous operations or a complex multi-step workflow, and only when the added types reduce branching and clarify transitions.

Never add an interface, presenter, reducer, effect layer, event bus, global UI store, or framework merely to satisfy a pattern. Require every abstraction to remove concrete duplication, isolate a dependency, make ownership clear, or make important behavior testable.

Prefer composition and platform components

Prefer existing IntelliJ Platform, JB UI, Kotlin UI DSL, or standard Swing components. Configure and compose them into a feature View instead of subclassing JComponent, JPanel, or another widget merely to provide layout, defaults, borders, or event wiring. A feature wrapper can own a root JComponent without being a Swing component itself. Subclass a Swing component only when the subtype has a genuine reusable widget contract or a platform integration point requires it.

Before implementing a new reusable Swing widget or any custom painting, stop and ask the user for explicit approval. This gate covers reusable JComponent subclasses, overrides of paint, paintComponent, or paintChildren, Painter implementations, and direct Graphics2D rendering. Explain why existing platform or standard components, composition, icons, borders, renderers, or UI DSL are insufficient, propose the closest standard alternative, and wait for approval. Existing custom components may be reviewed or refactored without retrospective approval; ask when the change introduces a new custom widget or new custom painting.

When a reusable custom widget is approved, give it a proper ComponentUI delegate. Keep reusable rendering, look-and-feel defaults, scaling and theme behavior, and UI-installed listeners in the delegate with symmetric installUI and uninstallUI lifecycle. Keep the widget's semantic state and public behavior in the JComponent subclass; do not put ad hoc painting into a feature View.

Define the feature boundary

Keep Swing types out of public or external APIs wherever possible. Exchange immutable state, domain values, stable IDs, and semantic callbacks. When Swing embedding is unavoidable, expose only the root JComponent at that integration seam and keep child widgets, models, renderers, painters, and raw Swing events private.

Prefer a concrete feature wrapper over a Swing subclass or an interface that consumers do not need:

internal class SearchComponent {
  private val searchField = JBTextField()

  val component: JComponent = JPanel(BorderLayout()).apply {
    add(searchField)
  }

  fun focusSearch() = searchField.requestFocusInWindow()

  fun clear() {
    searchField.text = ""
  }
}

If an API must be public, keep UI construction behind an internal integration point and expose domain-oriented operations. Do not expose buttons, lists, trees, text fields, models, or other internal widgets for outside manipulation.

Use the component or a nearby composition root to construct the View, Controller, services, and navigator. Prefer constructor injection. Restrict ApplicationManager.getApplication().getService(...) and similar lookups to composition roots or established platform integration points, never arbitrary View code.

Assign responsibilities

View

Make the View own Swing:

  • Construct widgets and layouts.
  • Render labels, icons, selection, visibility, enabled state, validation presentation, and animations.
  • Emit semantic user intents such as onSaveRequested, onRetryRequested, onSearchRequested(query), or onItemActivated(id).
  • Keep widgets private and provide render(state) when the feature has meaningful state.
  • Keep purely presentational transient details, such as focus, hover, caret position, or an uncommitted editor interaction, local when no application decision depends on them.

Do not let the View call repositories or services, start network or filesystem work, decide navigation, mutate domain objects, contain business rules, or block the EDT. Do not attach listeners to View widgets from outside the View.

Controller

Introduce a Controller when behavior no longer remains simple and local. Make it:

  • Subscribe to semantic View intents.
  • Validate and normalize user input.
  • Invoke services and navigation.
  • Own explicit UI state and state transitions.
  • Coordinate asynchronous work, stale-result protection, cancellation, errors, and retries.
  • Render the resulting state.
  • Own and release subscriptions and tasks.

Do not construct Swing layouts or reach into View widgets from the Controller.

Services

Keep application services independent of Swing, JComponent, widget models, and EDT assumptions. Pass domain values or dedicated data objects across the boundary. Inject navigation separately when it is a UI concern.

Model and render state

Introduce immutable state when the feature has multiple visual modes, asynchronous work, or decisions that would otherwise be inferred from widgets:

data class SearchState(
  val query: String,
  val loading: Boolean,
  val results: List<SearchResult>,
  val error: String?,
)

Use a sealed state hierarchy instead of combinations of booleans when modes are mutually exclusive. Do not mirror every widget property into state; model values that drive behavior or rendering.

Make render(state) deterministic, idempotent, and complete for the modeled state. Keep listener installation, service calls, navigation, and other effects out of rendering. Prefer one render operation over a sequence such as showSpinner(), hideRetry(), setItems(), and enableButton() that can leave the UI partially updated.

Never use widget properties as application state:

// Wrong: application decisions depend on the current rendering.
if (progressBar.isVisible) return
if (statusLabel.text == "Loading") return

Keep a single source of truth. Update it through one controller path, then render it:

private fun updateState(transform: (SearchState) -> SearchState) {
  state = transform(state)
  view.render(state)
}

Treat intents as semantic events

Translate raw Swing events inside the View. Emit domain-relevant values or stable IDs rather than widgets, indices whose meaning can change, or ActionEvent unless the Swing event itself is genuinely required.

Prefer:

view.onSearchRequested { query -> controller.search(query) }

over exposing searchButton, searchField, or resultList. Avoid a new event abstraction when a callback is enough.

Enforce EDT ownership

Treat the View and its widgets as EDT-confined unless a Swing API explicitly documents otherwise. Construct, read, and mutate Swing state on the EDT.

Inspect every listener and callback for blocking operations, including:

  • Future.get() or equivalent waits
  • Thread.sleep() and runBlocking
  • Network requests and process execution
  • Filesystem scans
  • Database queries
  • Expensive parsing or computation

Capture required input on the EDT, run expensive work away from it, then return to the EDT before updating state or rendering. Follow the surrounding module's platform coroutine, modality, read/write-action, and dispatcher conventions. Prefer a coroutine scope tied to the feature lifecycle; never use GlobalScope. If using SwingUtilities.invokeLater, verify that platform modality and disposal semantics do not require an IntelliJ scheduling API instead.

Modality rides in the coroutine context and defers on the EDT: capture a ModalityState per operation on the submitting thread (ModalityState.defaultModalityState()) and pass it to the work — launch(modality.asContextElement()) or invokeLater(runnable, modality) — rather than freezing one modality onto a long-lived scope. Work submitted with a modality lower than the currently open modal dialog is deferred until that dialog closes, which reads as a hang; completing with the modality captured at submit time dispatches it inside the originating modal state. ModalityState.any() is the opposite trap — it never defers, so a non-trivial callback can run inside an unrelated modal dialog while your model is mid-transition (reentrancy / inconsistent state); reserve any() for trivial, state-independent bookkeeping.

For concurrent requests, cancel obsolete work or tag requests and ignore stale completion. Preserve coroutine cancellation rather than converting it into a user-visible failure. Re-check lifecycle before applying results.

Own lifecycle

Prefer a CoroutineScope tied to the feature lifetime as the primary lifecycle mechanism: take a child scope of the enclosing project or service scope, or the scope the platform hands in, rather than constructing a standalone one. Launch asynchronous work, flow subscriptions, and retries in that scope so cancelling it tears everything down in one place.

For event, message-bus, RPC, or Flow subscriptions, use the shortest lifecycle that consumes the updates. Prefer a caller/client scope owned by the UI content, dialog, popup, tool-window panel, or explicit operation over an application- or project-level service scope. Use an app/project service scope only when the collected state is intentionally app/project-owned for that full lifecycle and retaining everything reachable from the stream for that lifetime is acceptable.

Avoid API methods that both start a subscription and expose a synchronous snapshot without an explicit owner. Split them into an owner-taking subscription method, for example one accepting CoroutineScope, and a snapshot accessor that only reads already-collected state. Action update paths and menu builders should read snapshots and must not implicitly start long-lived subscriptions. If a service caches per-project mirrors keyed by ProjectId, remove entries when the owning client scope completes.

Implement Disposable, AutoCloseable, or the lifecycle type already used by the module when a platform integration point requires it, and bridge it to the scope by cancelling the scope on disposal. Ensure teardown:

  • Removes listeners and subscriptions.
  • Stops timers and animations.
  • Cancels background work and pending retries.
  • Clears callbacks that could retain the View or Controller.
  • Prevents late results from rendering into a disposed UI.

Register child lifetimes with the IntelliJ Disposer where appropriate. Make repeated disposal safe.

Use IntelliJ Platform facilities deliberately

  • Prefer Kotlin UI DSL and JB UI components for new IntelliJ UI when they improve consistency or maintenance.
  • Prefer Kotlin UI DSL's listCellRenderer or textListCellRenderer over renderers based on SimpleColoredComponent when the DSL supports the required presentation.
  • Do not rewrite working Swing into Kotlin UI DSL unless requested or the migration materially improves the change.
  • Use the Action System for IDE actions and MessageBus for appropriate platform-wide communication, not for private button-to-controller events.
  • Use localized message bundles for user-visible text.
  • Follow platform coroutine, threading, and lifecycle conventions already established in the owning module.

Refactor incrementally

  1. Identify one feature boundary and preserve its current external behavior.
  2. Encapsulate widgets behind the View or component API.
  3. Translate raw listeners into semantic intents.
  4. Move validation, service calls, navigation, and workflows into the Controller.
  5. Introduce immutable state only when it replaces ambiguous or duplicated widget-derived state.
  6. Consolidate rendering into render(state) when several methods can diverge.
  7. Move expensive work off the EDT and guard against stale or late results.
  8. Add lifecycle cleanup.
  9. Split further only when a remaining class still owns unrelated responsibilities.

Do not perform a large architectural rewrite when a small extraction resolves the ownership problem.

Test at the right boundary

  • Test controller state transitions, validation, service interactions, errors, cancellation, and stale-result handling without requiring real network or filesystem work.
  • Test View rendering and semantic event translation on the EDT.
  • Test disposal when listeners, timers, or background tasks exist.
  • Prefer observable behavior over tests that reach into private widgets.
  • Do not introduce a View interface solely to satisfy a mocking framework; add a narrow test seam only when it has a concrete design benefit.

Classify architecture findings

Treat these as severity defaults and adjust for actual impact.

  • Critical: Blocking the EDT; accessing Swing from background threads; network, filesystem, database, or domain mutations in the View; domain layers depending on Swing.
  • Major: Exposed internal widgets or unnecessary Swing types in public APIs; avoidable Swing inheritance; unnecessary custom widgets or painting; a reusable custom widget without a proper ComponentUI; application state inferred from widgets; Controller-built layouts; uncancelled or stale async results; missing lifecycle cleanup; a god panel mixing UI, services, and workflows.
  • Minor: Large anonymous listeners; unnecessary widget getters or interfaces; mixed construction and behavior that remains understandable; small duplication in imperative rendering.

A panel over roughly 500 lines is a review signal, not an automatic defect. Judge responsibility count, coupling, asynchronous behavior, and change risk.

Produce architecture reviews

When reviewing code, use these exact headings. Cite concrete symbols or file locations, distinguish observed facts from recommendations, and write None when a section has no findings.

Architecture Assessment

State the feature boundary, current complexity, selected architecture level, and whether a refactor is justified.

Current Responsibilities

Map rendering, intents, state, application logic, asynchronous work, navigation, and lifecycle to their current owners.

Architecture Problems

List Critical, Major, and Minor findings with evidence and impact.

Critical Issues

Call out EDT violations, blocking, domain/Swing dependency inversion, unsafe late results, or other correctness risks that require priority.

Suggested Component Structure

Show the smallest useful target structure and its public boundary.

Minimal Refactoring Plan

Give ordered, behavior-preserving steps. Separate necessary work from optional cleanup.

Example Code

Provide a focused example or patch shape for the highest-value change; do not rewrite the whole feature unless requested.

Trade-offs

Explain added types or state, rejected heavier patterns, testing impact, migration risk, and any manual verification still needed.

Guiding principle

Make Views know how the UI looks, Controllers know what the user wants, services know how the application works, and state describe what should be visible. Never let Swing widgets become the application's state or business layer.

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

actions

免费有简介

实现或修改 IntelliJ `AnAction`,并在 `plugin.xml` 中注册。将显示名称和说明写入消息资源文件,按需设置图标,并通过事件协程作用域启动挂起任务,避免同步处理阻塞 IDE。

  • 为 IDE 菜单添加操作
  • 修改操作注册或图标
  • 整理操作名称和说明
JetBrains/intellij-community2.1万2026年10月29日 更新

bazel-test-migration

免费有简介

将 IntelliJ JPS 测试模块迁移到 Bazel,并排查仅在 Bazel 中出现的失败。根据症状检查依赖、插件、测试数据和 runfiles,重新生成并验证目标。

  • 将 JPS 测试模块迁移到 Bazel
  • 排查仅在 Bazel 中失败的测试
  • 检查测试依赖和数据配置
JetBrains/intellij-community2.1万2026年10月29日 更新

code-style

免费有简介

按 IntelliJ 项目规范编写或审查 Kotlin 和 Java 代码,涵盖语言选择、格式、密封类型、线程注解及控制流异常处理。

  • 按 IntelliJ 规范编写 Kotlin
  • 审查 Java 代码
  • 检查异常处理和密封类型分支
JetBrains/intellij-community2.1万2026年10月29日 更新

commits

免费有简介

本指南帮助您按 IntelliJ 项目规则拆分更改并撰写提交信息:有工单时使用编号和变更说明,无工单时使用标签与子系统名,并在需要时说明原因和决定。

  • 按项目格式编写带工单号的提交信息
  • 整理测试或文档提交并选择合适标签
  • 按规则修改已有提交信息
JetBrains/intellij-community2.1万2026年10月29日 更新

使用多个 Python 类型检查器比较代码片段或文件的类型推断和报错判断,并汇总各工具的结论、耗时与诊断信息,可保存为 Markdown 报告。

  • 比较不同检查器的类型推断
  • 确认代码是否会被判为类型错误
  • 查看多个工具的诊断差异
JetBrains/intellij-community2.1万2026年10月29日 更新

整理 Compose Desktop 界面中的状态和副作用,让可组合函数负责绘制,由展示器或协调器处理应用决策。了解状态归属、Effect、可复用组件接口、延迟列表键、动画和性能,适用于单项界面修改。

  • 分离界面绘制与展示器决策
  • 整理界面状态的归属
  • 检查 Effect 键和协程用法
JetBrains/intellij-community2.1万2026年10月29日 更新

查看 JetBrains 的全部技能

报告此技能的问题