scala-swing icon indicating copy to clipboard operation
scala-swing copied to clipboard

Request for a scala.swing.CardPanel (uses javax.swing.CardLayout)

Open scabug opened this issue 15 years ago • 2 comments

Here is a simple implementation:

import swing.{Component, LayoutContainer, Panel}
import java.awt.CardLayout

class CardPanel extends Panel with LayoutContainer {
  type Constraints = String
  def layoutManager = peer.getLayout.asInstanceOf[CardLayout]
  override lazy val peer = new javax.swing.JPanel(new CardLayout) with SuperMixin

  private var cards : Map[String, Component] = Map.empty

  protected def areValid(c: Constraints) = (true, "")
  protected def add(comp: Component, l: Constraints) = {
    // we need to remove previous components with the same constraints as the new one,
    // otherwise the layout manager loses track of the old one
    cards.get(l).foreach { old => cards -= l; peer.remove(old.peer) }
    cards += (l -> comp)
    peer.add(comp.peer, l)
  }

  def show(l : Constraints) = layoutManager.show(peer, l)

  protected def constraintsFor(comp: Component) = cards.iterator.find { case (_, c) => c eq comp}.map(_._1).orNull
}

scabug avatar Oct 18 '10 09:10 scabug

Imported From: https://issues.scala-lang.org/browse/SI-3933?orig=1 Reporter: @oxbowlakes

scabug avatar Oct 18 '10 09:10 scabug

Samuel Halliday (fommil) said (edited on Mar 27, 2013 2:39:47 PM UTC): hmm, this seems somewhat limited as an implementation.

Anytime I want to use a CardLayout I find myself wanting to use the following functions (much more than the arbitrary String lookup of the Components)

  • first
  • last
  • next
  • previous

and being able to access the current Component that is shown. This I do with the following helper method

  def current = getComponents.filter(_.isVisible).headOption

If these functions were made available to subclasses of CardPanel, then very clean code to replace the following would be possible

  addKeyListener(new KeyAdapter {
    override def keyPressed(e: KeyEvent) {
      e.getKeyCode match {
        case KeyEvent.VK_ENTER if current == Some(panel3) =>
          log.info("finished...")

        case KeyEvent.VK_ENTER =>
          cards.next(IntroductionView.this)

        case KeyEvent.VK_LEFT if current != Some(panel0) =>
          cards.previous(IntroductionView.this)

        case _ =>
      }
    }
  })

scabug avatar Mar 27 '13 14:03 scabug