You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala Swing中点击按钮后如何重置或移除表格?

在Scala Swing中重置/移除表格的解决方案

你的问题核心是每次点击按钮都在旧表格下方新增新表格,原因是每次点击都创建了全新的ScrollPane和Table,而且试图移除的是刚创建的还未加入容器的组件,所以移除操作根本没生效。

下面是修改后的代码,实现点击按钮时替换旧表格(或清空)的效果:

// 定义主容器
contents = new BoxPanel(Orientation.Vertical) {
  // 提前声明用于存放表格的容器,初始为空
  var tableContainer: ScrollPane = new ScrollPane()
  contents += new Label("Hello, you're welcome")
  contents += Button("Query") {
    // 先移除已存在的表格容器(如果有的话)
    if (contents.contains(tableContainer)) {
      contents -= tableContainer
    }

    Try {
      // 获取新表格
      val newTable = changeCountry()
      // 更新表格容器的内容
      tableContainer = new ScrollPane(newTable)
      // 添加新的表格容器到主容器
      contents += tableContainer
      // 刷新界面,确保组件更新生效
      revalidate()
      repaint()
    }.getOrElse(
      Dialog.showMessage(contents.head, "Incorrect input ! This seems that input isn't in that list, write a different code or country")
    )
  }
}

// 处理用户输入,完善Option分支(避免用户取消输入时抛异常)
def changeCountry(): Table = {
  val text = Dialog.showInput(parent = contents.head, message = "Write a code of a country or a country", initial = "test")
  text match {
    case Some(s) => airportRunwayByCountry(s)
    case None => 
      // 用户取消输入时抛出异常,让Try捕获并提示
      throw new IllegalArgumentException("User cancelled input")
  }
}

// 创建表格的逻辑不变
def airportRunwayByCountry(code : String): Table = {
  val headers = Seq("Airport","Runway linked")
  val rowData = Functions.findAirportAndRunwayByCountry(code).map(x => x.productIterator.toArray).toArray
  new Table(rowData, headers)
}

关键修改点:

  • 提前复用表格容器:用var tableContainer来保存当前的表格容器,每次点击时先移除旧的,再替换成新的
  • 完善输入处理:新增case None分支,处理用户取消输入的情况,避免程序崩溃
  • 强制刷新界面:添加revalidate()和repaint(),确保组件更新后界面能及时显示变化
  • 有效移除旧组件:点击时先检查表格容器是否在主容器中,存在就移除,再添加新的,避免堆叠

如果想要单独实现“重置清空表格”的功能,可以加一个按钮:

contents += Button("Reset") {
  if (contents.contains(tableContainer)) {
    contents -= tableContainer
    tableContainer = new ScrollPane()
    revalidate()
    repaint()
  }
}

内容的提问来源于stack exchange,提问作者Kev74

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 19:20:11