Skip to content

Instantly share code, notes, and snippets.

@voronaam
Last active February 24, 2022 23:32
Show Gist options
  • Save voronaam/7206119 to your computer and use it in GitHub Desktop.
Save voronaam/7206119 to your computer and use it in GitHub Desktop.
Mutable ComboBox for Scala Swing
import scala.swing.{ Component, Swing, event }
import javax.swing.JComboBox
/**
* Very basic Mutable ComboBox for Scala.
* <p>Sample usage:<p>
* <pre>
* val box = new MutableComboBox[String]
* box.items = List("1", "11", "222")
* listenTo(box)
* reactions += {
* case SelectionChanged(`box`) => println(box.item)
* }
* </pre>
* <p>Note that there is no separate "selection" member. This combobox publishes event on its own</p>
*/
class MutableComboBox[T] extends Component {
override lazy val peer = new JComboBox[T]() with SuperMixin
peer.addActionListener(Swing.ActionListener { e =>
publish(event.SelectionChanged(MutableComboBox.this))
})
def items_=(s: Seq[T]) {
peer.removeAllItems
s.map(peer.addItem)
}
def items = (0 until peer.getItemCount()).map(peer.getItemAt)
def index: Int = peer.getSelectedIndex
def index_=(n: Int) { peer.setSelectedIndex(n) }
def item: T = peer.getSelectedItem.asInstanceOf[T]
def item_=(a: T) { peer.setSelectedItem(a) }
}
@lnz611
Copy link

lnz611 commented Feb 24, 2022

You saved my day with this! I was going crazy trying to modify a ComboBox...

@voronaam
Copy link
Author

Glad it was useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment