编辑Combobox Scala

时间:2013-03-28 16:42:42

标签: swing scala

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

然而,我遇到的问题是scala组合框摆动不可变(我猜)?

有没有办法使用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
    }
  }
}

2 个答案:

答案 0 :(得分:2)

你是对的,ComboBox的Scala-Swing JComboBox包装器有一个不允许添加或删除的静态模型。不幸的是,Scala-Swing中有很多东西比底层的Java-Swing组件功能更少。

然而,好处是每个Scala-Swing组件都有一个Java-Swing peer字段,您可以使用它来修补丢失的位。我认为最简单的方法是为javax.swing.DefaultComboBoxModel创建一个瘦包装器,如:

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
}

答案 1 :(得分:0)

在“0___”你测试了你的代码吗?它似乎有一些不匹配的问题。我正在使用scala 2.10。

实际上有一种解决问题的方法,而无需处理ComboBoxModel。 这是一个简短的例子:

class ComboBox(items: Array[String])
extends scala.swing.Component with java.awt.event.ActionListener with Publisher{

  override lazy val peer = new JComboBox(items)

  def +=(item: String) = peer.addItem(item)
  def -=(item: String) = peer.removeItem(item)
  def item = peer.getSelectedItem.asInstanceOf[String]
  def reset{peer.setSelectedIndex(0)}
  //additional methods

  //since its peer val is now a JComboBox

  peer.addActionListener(this)
  def actionPerformed(e: ActionEvent){
    //how to react once the selection changes
  }

  //since its also a scala.swing.Component extender
  listenTo(mouse.clicks) //and all the rest of the Publishers
  reactions += {
    case e: MouseClicked => //do something awesome
  }

  /* Also one could additionally extend the scala.swing.Publisher Trait
   * to be able to publish an event from here.
   */
  publish(MyEvent(item))
}

case class MyEvent(item: String) extends Event