comboBoxDemo/scala/ComboBoxDemo.scala

  1: //..+....1....+....2....+....3....+....4....+....5....+....6....+....7....+....8
  2: /*
  3:  * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
  4:  */ 
  5: package components
  6: 
  7: import java.awt.BorderLayout
  8: import java.awt.Dimension
  9: import java.awt.Font
 10: import javax.swing.BorderFactory
 11: import javax.swing.ImageIcon
 12: import swing._
 13: import swing.event._
 14: 
 15: // ----------------------------------------
 16: object ComboBoxDemo {
 17:   val version =          ComboBoxDemo
 18:     .getClass.getName+": #1.0.16"
 19: }
 20: 
 21: // ----------------------------------------
 22: class ComboBoxDemo extends BorderPanel {
 23: // implements ActionListener
 24: 
 25:   val petStrings = Array("Bird","Cat","Dog","Rabbit","Pig")
 26: 
 27:   // ---------------------------------------- Command::Invoker
 28:   val panel = this
 29:   val petList = new ComboBox(petStrings) {
 30:     selection.index = 4
 31:     Command.listenTo(selection)
 32:     panel.peer.add(peer, BorderLayout.PAGE_START)
 33:   }
 34: 
 35:   val picture = new Label {
 36:     horizontalAlignment = Alignment.Center
 37:     border = Swing.EmptyBorder(10,0,0,0)
 38: 
 39:     preferredSize = new Dimension(177,122+10)
 40:     panel.peer.add(peer, BorderLayout.PAGE_END)
 41:   }
 42:   picture.font = picture.font.deriveFont(Font.ITALIC)
 43: 
 44:   updateLabel(petStrings(petList.selection.index))
 45: 
 46:   // ---------------------------------------- Command::Command
 47:   object Command extends Publisher {
 48:     reactions += {
 49:       case SelectionChanged(source) =>
 50: /*'****************************************'
 51:         val cb = source
 52: '****************************************'*/
 53:         val cb = source.asInstanceOf[ComboBox[String]]
 54:         val petName = cb.selection.item.mkString
 55:         updateLabel(petName)
 56:     }
 57:   }
 58: 
 59:   def updateLabel(name: String) {
 60:     val icon = createImageIcon("images/%s.gif" format name)
 61:     picture.icon = icon
 62:     picture.tooltip = "A drawing of a %s" format name.toLowerCase
 63:     picture.text = if (icon == null) "Image not found" else null
 64:   }
 65: 
 66:   // ----------------------------------------
 67:   /** Returns an ImageIcon, or null if the path was invalid. */
 68:   def createImageIcon(path: String): ImageIcon = {
 69:     val imgURL = ComboBoxDemo.getClass.getResource(path)
 70:     if (imgURL != null) {
 71:       return new ImageIcon(imgURL)
 72:     } else {
 73:       System.err.println("Couldn't find file: " + path)
 74:       return null
 75:     }
 76:   }
 77: 
 78:   border = Swing.EmptyBorder(20,20,20,20)
 79: }
 80: 
 81: // ========================================