本文介绍了编辑组合框 Scala的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个简单的应用程序,在该应用程序中我可以在 Textfield 中编写一个项目,然后输入一个按钮,该按钮又通过将该项目插入到组合框中来做出反应.

I am trying to implement a simple application in which I can write an item in Textfield and then entering a button which in turn reacting by inserting that item in a combo box.

但是,我面临一个问题,即 Scala 组合框的摆动是不可变的(我猜)?

However, I am facing a problem that the scala combobox swing is not mutable(I guess)?

有没有办法使用 Scala 摆动使组合可变?

Is there any way to make a combo mutable using scala swing?

import scala.swing._
import scala.swing.event._
import scala.swing.BorderPanel.Position._

object ReactiveSwingApp extends SimpleSwingApplication {
  def top = new MainFrame {
    title = "Reactive Swing App"

    val button = new Button {
      text = "Add item" 
    }   
    var textfield = new TextField {
      text = "Hello from a TextField"
    }

    var items = List("Item 1","Item 2","Item 3","Item 4")
    val combo = new ComboBox(items)

    contents = new BorderPanel {
      layout(new BoxPanel(Orientation.Vertical) {
          contents += textfield 
          contents += button
          contents += combo   
          border = Swing.EmptyBorder(30, 30, 10, 30)
      }) = BorderPanel.Center
    }

    listenTo(button, textfield)
    reactions += {
      case ButtonClicked(button) =>
        // var items1 = textfield.text :: items  <- how can a read Item be inserted
    }
  }
}

推荐答案

你说得对,Scala-Swing ComboBox 包装器 JComboBox 具有不允许添加或删除的静态模型.不幸的是,Scala-Swing 中有很多功能不如底层 Java-Swing 组件.

You are correct, the Scala-Swing ComboBox wrapper for JComboBox has a static model which does not allow additions or removals. Unfortunately, there are quite a few things in Scala-Swing which are less capable than the underlying Java-Swing components.

然而,好消息是每个 Scala-Swing 组件都有一个 Java-Swing peer 字段,您可以使用它来修补缺失的位.我认为最简单的方法是为 javax.swing.DefaultComboBoxModel,如:

The good thing however is that each Scala-Swing component has a Java-Swing peer field, which you can use to patch the missing bits. I think the easiest is to create a thin wrapper for javax.swing.DefaultComboBoxModel, like:

class ComboModel[A] extends javax.swing.DefaultComboBoxModel {
  def +=(elem: A) { addElement(elem) }
  def ++=(elems: TraversableOnce[A]) { elems.foreach(addElement) }
}

那么你的构造就变成了

val combo = new ComboBox(List.empty[String])
val model = new ComboModel[String]
model ++= items
combo.peer.setModel(model)  // replace default static model

你的反应

reactions += {
  case event.ButtonClicked(button) =>
    model += textfield.text
}

这篇关于编辑组合框 Scala的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 12:05