Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does anyone know of code that wraps JOptionPane using the builder pattern?

Tags:

java

swing

Good ol' JOptionPane contains a plethora of static methods. There are many combinations, yet to change certain options (like buttons) you still must specify other optional arguments - often defaults (like a null icon). This doesn't lead to easy to read code.

Moreover the methods aren't particularly consistent (does an int return correspond to a ***_OPTION constant or a button index?) so it requires a slew of documentation to disambiguate: it's not quick & easy to learn, remember or write.

It would seem natural to me to create a 'Builder' wrapper. It might look something like this:

String[] buttonText = { "Looks good", "It sucks" };

Object selection = new OptionPaneBuilder("What do you think?")
    .question()
    .message(messageComponent)
    .resizable(true)
    .showOptionDialog(parent, buttonText);

return buttonText[0].equals(selection);

The final method call could be:

// returns int (or enum?)
.showConfirmDialog(parent, JOptionPane.YES_NO_CANCEL_OPTION) 

// returns JOptionPane
.build()

// etc... 

I'm happy to go write it - but my failure to find anything existing makes me wonder: am I crazy (it's a bad idea / there are better ways) ... or just inept at using Google? :-)

So... does anyone know of anything that achieves something like this?

My feeling is to stick with JOptionPane dialogs so that the UI delegates gets things like fonts and system icons correct for any Look and Feel; but I guess if alternatives succeed at this, they would be fine too.

like image 268
Luke Usherwood Avatar asked Nov 18 '11 09:11

Luke Usherwood


1 Answers

There is an API called oxbow TaskDialogs. It includes some decent standard Task-Dialog-Layouts and you are also able to design your own ones. Within this API you are free to use their static methods to create a standard dialog, as well as using their builder to construct the desired dialog.

Example with builder pattern:

int choice =
    TaskDialogs
        .build( owner, "What do you think?",
            "You have to choose, either this dialog looks good or it just sucks!" )
        .title( "Make a decision!" )
        .choice( 0,
            new CommandLink( "Looks good", "With good I mean it looks reaaaally awesome!" ),
            new CommandLink( "It sucks", "I cant see it anymore, take it away!" ) );
like image 82
crusam Avatar answered Sep 21 '22 18:09

crusam