Showing posts with label JDialog. Show all posts
Showing posts with label JDialog. Show all posts

JDialog to the Rescue

I had a requirement to display a list of choices in a window. Furthermore I wanted the dialog to be dismissed as soon as the user pressed a key. Turns out the JDialog was the class I needed. Mapped the keys of interest to a listener and I was good to go. But then I needed to handle the display of the dialog.

I must confess that I really did not have that much experience with JDialogs. Found out that it defaults to a BorderLayout. For my application, I needed more of a GridLayout. I surveyed a bunch of code on the web while searching for my solution. Learned that I could call the pack() method to size the dialog with the minimal amount of space required to fit the contents.

I had one hiccup where I wanted to map the keys with the JRootPane. Thought I needed to do that when I created the JRootPane in createRootPane(). Unfortunately that method gets called from the superclass. I could not pass it any data. That's okay. I found I could later call getRootPane() and handle my business.

All About the Keys

I wanted to provide an easy to use interface in my latest program. At times I put up a dialog where the user must choose a value. I want the user to be able to just press one key to make the choice. Initially I tried using the JOptionPane. But it required the user to press enter after making the choice.

I thought I needed to somehow specify an option (no pun intended) for the JOptionPane to just require a keypress. After a while, it felt like I was hacking to much to get this to work. I seemed to need to set some weird user interface options, then set up some maps, and I was still struggling to figure out which key got pressed.

Then I researched some mneumonics. Turns out those require you to press the Alt key along with the choice you make. No good. Finally I figured I needed some custom code. I forgot about the canned JOptionPane and started concentrating on a straight JDialog. Got an assist from the Java2s web site. A map plus a listener was all I needed. Now I am going back to the basics of drawing some user choices on the dialog. That should be a snap. I wish I knew to go straight to the JDialog in the first place. I been spending most of the day on this issue.