2013年8月1日

在 SwingBuilder 中建立 CardLayout 的方式

Groovy 透過 SwingBuilder 可以用 DSL 方式表述 swing 各種 components 的佈建。
而建立 CardLayout 有 3 種方式可以進行:
(1) 由 builder 產生
import groovy.swing.SwingBuilder
import java.awt.*
import javax.swing.*

def swing = new SwingBuilder()
def cardLayout = swing.cardLayout()
def thePanel

swing.edt {
 frame (
  title: "Ex",
  defaultCloseOperation: JFrame.EXIT_ON_CLOSE,
  pack: true,
  show: true ) {
  
  borderLayout()
  panel(constraints: BorderLayout.PAGE_START) {
   
   borderLayout()
   panel(constraints: BorderLayout.PAGE_START) {
    label(text: 'header')
   }
   panel(id: 'cards', constraints: BorderLayout.CENTER, layout: cardLayout).with {
    thePanel = it
   }
   panel(constraints: BorderLayout.PAGE_END) {
    label(text: 'footer')
   }
  }

  thePanel.add(
   panel(border: emptyBorder(5,5,5,5)) {
    label(text: 'card 1 label')
   }, 'card1')
  thePanel.add(
   panel(border: emptyBorder(5,5,5,5)) {
    label(text: 'card 2 label')
   }, 'card2')
  cardLayout.show(thePanel, 'card2')
 }
}
(2) new 產生
import groovy.swing.SwingBuilder
import java.awt.*
import javax.swing.*

def swing = new SwingBuilder()
def thePanel

swing.edt {
 frame (
  title: "Ex",
  defaultCloseOperation: JFrame.EXIT_ON_CLOSE,
  pack: true,
  show: true ) {
  
  borderLayout()
  panel(constraints: BorderLayout.PAGE_START) {
   
   borderLayout()
   panel(constraints: BorderLayout.PAGE_START) {
    label(text: 'header')
   }
   panel(id: 'cards', constraints: BorderLayout.CENTER, layout: new CardLayout()).with {
    thePanel = it
   }
   panel(constraints: BorderLayout.PAGE_END) {
    label(text: 'footer')
   }
  }

  thePanel.add(
   panel(border: emptyBorder(5,5,5,5)) {
    label(text: 'card 1 label')
   }, 'card1')
  thePanel.add(
   panel(border: emptyBorder(5,5,5,5)) {
    label(text: 'card 2 label')
   }, 'card2')
  thePanel.getLayout().show(thePanel, 'card2')
 }
}
(3) 由 container 進行 setLayout()
import groovy.swing.SwingBuilder
import java.awt.*
import javax.swing.*

def swing = new SwingBuilder()
def cardLayout
def thePanel

swing.edt {
 frame (
  title: "Ex",
  defaultCloseOperation: JFrame.EXIT_ON_CLOSE,
  pack: true,
  show: true ) {
  
  borderLayout()
  panel(constraints: BorderLayout.PAGE_START) {
   
   borderLayout()
   panel(constraints: BorderLayout.PAGE_START) {
    label(text: 'header')
   }
   panel(id: 'cards', constraints: BorderLayout.CENTER).with {
    setLayout(cardLayout = new CardLayout())
    thePanel = it
   }
   panel(constraints: BorderLayout.PAGE_END) {
    label(text: 'footer')
   }
  }

  thePanel.add(
   panel(border: emptyBorder(5,5,5,5)) {
    label(text: 'card 1 label')
   }, 'card1')
  thePanel.add(
   panel(border: emptyBorder(5,5,5,5)) {
    label(text: 'card 2 label')
   }, 'card2')
  cardLayout.show(thePanel, 'card2')
 }
}
ps. groovy 版本 v2.0.7

沒有留言: