Question

I'm a little late to the Groovy party (like most other parties) and the documentation I've been able to find online about SwingBuilder is somewhat limited. I am trying to build a gaming application in Groovy (converting my current Java code to Groovy). In Java I have a JFrame and multiple JPanels which include labels and text fields and buttons and all the other fun swing items that you can use in building a GUI.

The code for all this can be cumbersome, having to declare variables for each JButton and JPanel and so on and so forth, so naturally when I discovered SwingBuilder in groovy just days ago I was ecstatic.

However, the examples are somewhat limited. So here is my inital code.

def Game(){
    mainMenu = new MainMenuPanel()
    gPane = new SwingBuilder()
    gPane.edt{
        frame(size:[1024,768],
            defaultCloseOperation: JFrame.EXIT_ON_CLOSE, location:[75,50], show:true, pack:false){
            container(container:mainMenu){}
            widget(mainMenu)
            }
        }
    }
    mainMenu.shell.show()
}

in MainMenuPanel I have this code

class MainMenuPanel extends JPanel implements ActionListener, KeyListener, ItemListener { 
    public shell
shell = new SwingBuilder()
    shell.panel(id: "mainM",/*size:[512, 354],
    shell.edt{frame(show:true){panel(size:[512, 354],
            layout: new GridLayout(cols:1, rows: 7),*/
            visible:true, constraints: BL.NORTH){

            textLabel = label(text: "Welcome Travelers", horizontalAlignment: 0)
            speak = button(CreateButton("Say Hello", 83), 
                actionPerformed:{ shell.optionPane(message: "Hello World").createDialog(null, "Hello").show()})
            }
        }

When I run the groovy script I get an JFrame, with nothing in it. I've tried various combinations of this code, sometimes I get two frames, but they are not nested inside each other. Most of the time I get a lot of nothing.

The purpose of what I'm trying to do is have a MainMenu class that returns a Menu Panel that has functionality to control that panel, and have various other classes that also return Panels that do other various things and nest them all in the Pane.

Is it possible to do this? Am I missing something here?

Was it helpful?

Solution

I believe this is functionally similar to what you have above:

import groovy.swing.SwingBuilder

def mainMenu = { builder ->
  builder.panel( id:'mainM' ) {
    label( text: 'Welcome Travelers' )
    button( text: 'Say Hello', actionPerformed:{
      builder.optionPane( message:'Hello World' )
             .createDialog( null, 'Hello' )
             .show()
    } )
  }
}

new SwingBuilder().with { builder ->
  builder.edt {
    frame( size:[ 1024, 768 ], show:true ) {
      panel()
      mainMenu( builder )
    }
  }
}

Hope it helps?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top