Styling a Pop-Up Confirmation Dialog and Forcing Focus in Java

This is really Concurrent Programming in Java part II. So consider it part of that post.

Anyways I needed a pop up confirmation box which had a styled entry field. This isn’t possible in normal Java but I am going to show you how to do it anyways. First, why? Because I need the confirmation box entry field to be styled, and I need it to request focus. Unfortunately since I was adding the entryField myself (to get it styled, since I couldn’t figure out how to access the one that comes with Swing) Java wouldn’t autofocus to it. After a lot of hacking around I felt this wasn’t possible normally. So here’s what I did to get it done:

JTextField entryField = new JTextField(); // global so it's in the same scope as popUpConf and it's thread.
public String popUpConf(String title, String msg) {

        // create a thread to wait until the dialog box pops up.
        (new Thread() {
            public void run() {
                // Sleep long enough for the window to pop up.....
                try {
                    // a half second should be fine...
                } catch (Exception e) {
                    // not required
                // request focus.

        Object[] message = new Object[]{msg, entryField};
        JOptionPane.showConfirmDialog(mainFrame, message, title,

        // return the string.
        String s = entryField.getText();
        return s;

In retrospect I probably should have used entryField.isShowing() and/or entryField.isVisible() to determine when I should request focus. Perhaps a short while loop with a small sleep value (50 or 100). Maybe I’ll go fix that now. But so far I’ve never had it barf on me. The only “error” is that it wouldn’t get focus, I suppose, which would be annoying but not unbearable.

Ok so that’s how you can set the font on a pop up confirmation box’s entry field. Cool, huh?


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: