JOptionPane and Focus

Hello All,
I've got a small problem with setting the focus in a JOptionPane. My JOptionPane consists of one JComboBox and two JTextFields. I've created this JOptionPane by putting the components in an array and passing it to the JOptionPane constructor. Initially it starts with the focus on the top most component (the JComboBox). What i would like is to have it focussed on one of the JTextFields.
Does anyone have any idea how to do this?
Thanks in advance.

Don't use a JOptionPane, why not use a modal JDialog? That way it is much easier to organise the components and arrange focus

Similar Messages

  • JOptionPane and JDialog.DO_NOTHING_ON_CLOSE broken?

    Hi there
    I've created a JDialog from a JOptionPane and I don't want the user to simply dispose of the dialog by clicking on the close button but they are still able and I'm sure that my code is correct. Is it my code that is wrong or is it a java bug? Oh I'm running on 1.3 BTW
    JFrame f = new JFrame();
    f.setSize(500, 500);
    f.setVisible(true);
    JOptionPane optionPane = new JOptionPane("Hello there", JOptionPane.INFORMATION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
    JDialog d = optionPane.createDialog(f, "Testing");
    d.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    d.setVisible(true);I know that I can just set up a JDialog directly and use the setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE) and it seems to work properly but I would like to see it work for JOptionPane!
    Thanks in advance

    Sorry but this doesn't make it work either. I've looked at the code for createDialog in JOptionPane and it actually adds a WindowListener to the dialog in there as well as a propertyListener. On closing the option pane it calls a method in windowClosing of the windowListener which in turn fires a property change event which then tells the dialog to dispose itself so the addition of another windowAdapter to override the windowClosing method will not help :-(
    I've managed to get round it by doing something similar to
    JFrame frame = new JFrame();
    final JDialog dialog = new JDialog(frame, "Testing", true);
    JButton button = new JButton("OK");
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        dialog.dispose();
    JOptionPane optionPane = new JOptionPane(button, JOptionPane.INFORMATION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
    dialog.setContentPane(optionPane);
    dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    dialog.pack();
    dialog.setVisible(true);

  • Help on assignment, don't understand JOptionPane and showInputDialog

    Hi, I am currently studying java and have problems doing my assignment. here is the assignment question. What I am looking for is pointers and hints to start on my assignment. I am not looking for the source code, rather the way to actually understand it and start writting my code
    I believe this assignment wanted me to create a class Object called Zeller with the methods in it and a ZellerTester to test the Object?
    I read up on the JOptionPane and the showInputDialog, but don't really quite understand it.
    Do i need a constructor for the Object Zeller?
    Does my assignment require me to put the showInputDialog as a method in the Zeller class? Or put it in the ZellerTester?
    The isLeapYear is a method in the Object Zeller?
    Here is the assignment question
    Examine the method
    showInputDialog() and study its function. Note the return type of this method.
    Write a program on the following requirements:
    1. Use the JOptionPane facility to ask the user for three positive integers,
    representing the day, month and year of a date.
    2. Use the Zeller�s congruence formula to find the day of the week.
    3. Should include a method boolean isLeapYear(int year)
    that will return true if year is a leap year, and false otherwise.
    The method should check for leap years as follow:
    return true if the year is divisible by 400.
    return true if the year is divisible by 4 but not by 100
    return false for the remaining values
    Thank you.

    I can't seems to return the method back to the main
    Not sure where has gone wrong...
    here is my code
    import javax.swing.*;
    public class ZellerTester
        public static void main(String[]args)
        int day  = 28;
        int month = 2;
        int year = 2007;
        int z;
        boolean isLeapYear;
        String[] displayName = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
        if(month==1 || month==2) {
            if (isLeapYear = false)
                day = day-1;
              else
                day = day-2;
        if(month<3)
            month = month + 12;
        z = (1 + day + (month * 2) + (3 * (month + 1) / 5) +
             year + year / 4 + year / 400 - year/ 100) % 7;
        System.out.println("The day is " +displayName[z]);
    public boolean isLeapYear(int year)
           if (year%400 == 0)
               return true;
           else if((year%4 == 0) && (year%100 != 0))
                return true;
           else
                 return false;
    }

  • How to change the icon of JOptionPane and JFileChooser in swing

    Hi,
    Does any body know how to change the icon of JOptionPane and JFileChooser in swing.
    Please help me out in this.
    Thanx in advance.

    Try this
    import javax.swing.*;
    import java.awt.event.*;
    public class Untitled4 {
      public Untitled4() {
      public static void main(String[] args) {
        ImageIcon i = new ImageIcon("C:/TestTree/closed.gif");
        JOptionPane p = new JOptionPane();
        p.setMessage("This JOptionPane has my icon");
        p.setMessageType(JOptionPane.QUESTION_MESSAGE);
        p.setOptionType(JOptionPane.YES_NO_CANCEL_OPTION);
        final JDialog d = p.createDialog("test");
        d.setIconImage(i.getImage());
        d.setVisible(true);
        d.setModal(true);
        if(Integer.parseInt(p.getValue().toString()) == JOptionPane.YES_OPTION) {
            System.out.println("You Clicked Yes");
    }

  • [svn] 3079: Pop up and focus fixes.

    Revision: 3079
    Author: [email protected]
    Date: 2008-09-03 10:53:07 -0700 (Wed, 03 Sep 2008)
    Log Message:
    Pop up and focus fixes.
    QE: YES
    Doc:
    Checkintests: YES
    Reviewer: Alex
    Bugs: SDK-16669, SDK-15688
    mx/events/SWFBridgeEvent.as
    Add marshal() method. Update ASDoc.
    mx/managers/FocusManager.as
    Fix bug SDK-15688. Type coercion error fixed by moving to a common super class of IFocusManagerComponent and SWFLoader.
    mx/managers/PopUpManagerImpl.as
    Renaming.
    airframework/src/mx/managers/WindowedSystemManager.as
    mx/managers/SystemManager.as
    Fix problems introduced from API scrub and fix an old problem activating A.2.2.
    mx/managers/SystemManagerProxy.as
    Override addEventListener() and removeEventListener() to also add listeners on the proxied SystemManager. This
    allows the Proxy to get keyboard focus events that happen in the proxied SystemManager. Dispatch activate/deactivate messages to the sandbox root.
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-16669
    http://bugs.adobe.com/jira/browse/SDK-15688
    http://bugs.adobe.com/jira/browse/SDK-15688
    Modified Paths:
    flex/sdk/branches/3.0.x/frameworks/projects/airframework/src/mx/managers/WindowedSystemMa nager.as
    flex/sdk/branches/3.0.x/frameworks/projects/framework/src/mx/events/SWFBridgeEvent.as
    flex/sdk/branches/3.0.x/frameworks/projects/framework/src/mx/managers/FocusManager.as
    flex/sdk/branches/3.0.x/frameworks/projects/framework/src/mx/managers/PopUpManagerImpl.as
    flex/sdk/branches/3.0.x/frameworks/projects/framework/src/mx/managers/SystemManager.as
    flex/sdk/branches/3.0.x/frameworks/projects/framework/src/mx/managers/SystemManagerProxy. as

    I would suggest not to use JWindow but JPopupMenu! In
    the JPopupMenu you can add any swing-components!
    You can show the Popup in focusGained (ok, that is
    not so user-friendly, in my opinion a shortcut would
    do better!).
    The Popup will hide automatically if you click with
    the mouse somewhere else or hit escape.Thank you for the reply.
    I'm still having problems. I'd prefer not to use a jpopupmenu, because I want to use that for something else. This was just going to be a simple list that would appear near the text field so user could have a list of options to choose from.
    Focus gained on the textfield brings up the list. Selecting something on the list clears it (hides). This idea works well on the mac. But on the pc the jwindow keeps hiding behind the main frame ?
    I have the following code
    The windows is created as follows
         listWindow = new JWindow(SwingUtilities.getWindowAncestor(this));
    listWindow.getContentPane().add(pane);
    listWindow.setVisible(false);
    pane contains the jlist of values
    Then the textfield is as follows
    textField.addFocusListener(new java.awt.event.FocusAdapter() {
    public void focusGained(java.awt.event.FocusEvent evt) {
    if (showListWindow) {
    if (!listWindow.isVisible()) {
    Point los = getLocationOnScreen();
    listWindow.setVisible(true);
    listWindow.setLocation(los.x +580, los.y +75);
    listWindow.pack();
    listWindow.toFront();
              textField().requestFocus();
    I use a boolean showListWindow to decide when to show. Because I noticed that displaying the jlist and requesting focus to the textfield caused the focusGain to fire again.
    Any ideas why the pc keeps the list hidden ? If I move the main frame I can see !

  • AWT and focusing on different windows

    Hey guys.
    I have a problem, I'm trying to set the focus a window but can't.
    I have two windows A and B.
    I also have a Events being picked up set on window A.
    So the set of events are detailed as follows.
    Window A display's and responds to events.
    When a particular event occurs it loads up a new window (WindowB) and focus is given to that window.Wasn't a problem until we realised that there was a delay between Window A being displayed and Window B being displayed, enough to cause a problem.
    So the code was changed like follows.
    WindowB.pack();
    WindowB.setVisible(true);
    WindowA.setVisible(false);When it was changed to the above, we lost the ability to pick up keyboard events, as WindowA was still the window with focus.
    I've had a look at the KeyboardFocusManager where it seems that focus can be change between components.
    However is also states for method setGlobalFocusWindow() that it can only be set if it is in the same context.
    Which it is not.
    Is it possible to set focus to the window before the window has been set visible? Is KeyboardManager the right class to look at?
    Sorry about the lack of code(It's spread in many directions and is sensitive)
    Thanks for any help in advance

    hello,
    the following link may help: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/doc-files/FocusSpec.html
    wrappingduke

  • Web browser resets scroll position and focus when page load completes

    when a page is loading, the scroll position of the page reverts to the top-left and focus in a form element is lost whenever an element or the whole page finishes loading
    Post relates to: Pre p100eww (Sprint)

    Possibly related to the OP's question, I wish we could get the composition page to scroll when typing a reply here on the forum (while using my Pre plus).
    Quoting a reply fills half the text box, then once I reach the bottom of the box, I can't scroll any further downward to complete my reply...
    WyreNut
    I am a Volunteer here, not employed by HP.
    You too can become an HP Expert! Details HERE!
    If my post has helped you, click the Kudos Thumbs up!
    If it solved your issue, Click the "Accept as Solution" button so others can benefit from the question you asked!

  • JOptionPane and Threads

    I have a Class called Execute which runs as a thread. If this fails, then I want to show a JOptionPane from the main thread saying it failed (this works), but also I want to create a JOptionPane within the run() method of Execute stating the reason for the failure.
    I can not put a JOptionPane directly inside the run method 'cos it doesn't get rendered correctly, so I run this in it own thread. Only trouble is that now I have two modal dialog boxes appearing simultaneously; what I want is to have them appear consecutively. I have tried to join the thread that creates the pop-up but then it does not get rendered. Any ideas? I have posted an extract of the code below for testing
    public class Execute implements Runnable {
         File success = new File ("/ukirtdata/orac_data/deferred/.success");
         File failure = new File ("/ukirtdata/orac_data/deferred/.failure");
         success.delete();
         failure.delete();
         try {
             success.createNewFile();
             failure.createNewFile();
         catch (IOException ioe) {
             logger.error("Unable to create success/fail file", ioe);
             return;
         SpItem itemToExecute;
         if (!isDeferred) {
             itemToExecute = ProgramTree.selectedItem;
             logger.info("Executing observation from Program List");
         else {
             itemToExecute = DeferredProgramList.currentItem;
             logger.info("Executing observation from deferred list");
         SpItem inst = (SpItem) SpTreeMan.findInstrument(itemToExecute);
         if (inst == null) {
             logger.error("No instrument found");
             success.delete();
             return;
         String tname = QtTools.translate(itemToExecute, inst.type().getReadable());
         // Catch null sequence names - probably means translation
         // failed:
         if (tname == null) {
             //new ErrorBox ("Translation failed. Please report this!");
             logger.error("Translation failed. Please report this!");
             new PopUp ("Translation Error",
                     "An error occurred during translation",
                     JOptionPane.ERROR_MESSAGE).start();
             success.delete();
             return;
         else{
             logger.info("Trans OK");
             logger.debug("Translated file is "+tname);
                failure.delete()
                return;
        public class PopUp extends Thread implements Serializable{
         String _message;
         String _title;
            int    _errLevel;
         public PopUp (String title, String message, int errorLevel) {
             _message=message;
             _title = title;
             _errLevel=errorLevel;
         public void run() {
             JOptionPane.showMessageDialog(null,
                               _message,
                               _title,
                               _errLevel);

    Comeon,
    Someone must have some idea. I have tried making popup extend JOptionPane and implement Runnable, added a window listener which sets a boolean popDisplayed on windowOpen and windowClose, but this gets me nowhere (I have a Thread.sleep in the code as well)

  • JOptionPane and JList HELP!!!

    Hi there,
    I want to be able to use a JOptionPane and add these elements to my JList component. I know how to add elements to it through the source code but am not able to get a user to inout values into this JList. 've got my JOptionPane running by using the following code:
    public void actionPerformed(ActionEvent ae) {
           if(ae.getActionCommand().equals("New Player")){
                s1 = JOptionPane.showInputDialog("Enter player: ");
                list.append(s1);
           repaint();
      }I want the values taken from this Prompt and be shown in my JList. I tried doing:
    list.addElement(s1);
    list.append(s1);
    I tried looking at the Java API website but didn't find it helpful at all of what I'm trying to do.

    I keep getting an error on the line where it says:
    list.add(s1);And even when I try:
    list.addElement(s1);Still same error. Is it a different way of doing it?
    Thanks for any response

  • My iphone6 camera is rear , and focus dosnt work in it , although my front camera is working great

    My iphone6 camera is rear , and focus dosnt work in it , although my front camera is working great

    Hey there Aydarezania,
    It sounds like you are able to focus using the front camera, but the back one doesnt seem to. I would use these troubleshooting steps from the following article, named:
    Get help with the camera on your iPhone, iPad, or iPod touch
    Force the app to close, then open the Camera app again.
    Restart your device, then open the Camera app again.
    Your photos are blurred or out of focus
    If your photos are blurred, out of focus, or have dark spots, try these steps:
    Make sure that the camera lens is clean. If you need to clean the lens, use a microfiber cloth. If you see dirt or debris inside the lens, take your device to an Apple Retail Store or Authorized Service Provider for more help.
    Make sure that there’s nothing blocking the camera lens. If you’re using a case, try removing it.
    With iPhone 6 Plus, a metallic case or magnetic lens could interfere with optical image stabilization. If you have a metallic case or magnetic lens attachment, try taking a picture without it. Then compare the quality.
    Adjust the focus by tapping on the person or object in the preview screen. You’ll see the screen pulse or briefly go in and out of focus as the camera adjusts. In photo mode, try to stay steady when adjusting the focus. If you move too far in any direction, the camera will automatically refocus to the center. In video mode, you can adjust the focus before you begin recording.
    If the color seems too bright, or you see double-exposures of moving objects, make sure that HDR is set to Auto or Off. Tap HDR at the top of the screen to choose a different setting.
    Thank you for using Apple Support Communities.
    Cheers,
    Sterling

  • Problem while adding both Key And Focus Listeners to JTextField

    Hi!
    I have something peculiar while adding Key and Focus Listener to JTextField. Suppose i add just Key Listener then everything's fine and i could keep track of keys being pressed. But as soon as i add a Focus Listener to it with the code to select full text in focusGained() method, it starts reponding wrongly to arrow keys pressed and does not perform desired actions. For let arrow key it moves caret by one for the first time after that it does not resond to that unless caret is changed by using mouse. If right arrow key is pressed the it moves the caret to last position from wherever it is. For UP and DOWN it selects the full text(This should be done when it gets focus)
    public void focusGained(FocusEvent fe)
    setCaretPosition(0);
    moveCaretPosition(getDocument().getLength());
    Can someone help me out on this?
    thanks and regards,
    Amit.

    None of those things will cause your JFrame to resize itself. And this is probably a good thing, because your JFrame shouldn't change size once you have created it. Why not create your JPanel so that it has enough space for you to add the component later? Or why not just add the component to start with and then enable it or make it editable when you decide that's necessary?

  • What's focus-angle and  focus-distance in CSS radial-gradients?

    Reading the reference ( http://docs.oracle.com/javafx/2.0/api/javafx/scene/doc-files/cssref.html#typepaint ) I found these two values you can set in a radial-gradient definition:
    radial-gradient([ *focus-angle* <angle>, ]? [ *focus-distance* <percentage>, ]? [ center <point>, ]? radius [ <length> | <percentage> ] [ [ repeat | reflect ], ]? <color-stop>[, <color-stop>]+)
    Could someone enlighten me what they mean? I wrote a little tool for visual definition of Gradients (http://88.198.17.44/blog/2012/04/13/it-works-fxexperience-tools-gradienteditor-plugin/) as an extension to FXExperience Tools, and I'd like to include it if it makes sense.
    Thanks
    Toni

    focus-angle and focus-distance are together used to determine the focal point of the radial pattern.
    See this image: http://www.webdesign.org/img_articles/6822/gradient.jpg

  • Plazmic CDK 4.6 caret and focus button issues

    I hope I'm posting in the right thread? This is regarding the Plazmic CDK 4.6 for Blackberry - to create your own themes.
    Ok. I think I some what get the hang of Plazmic CDK 4.6 except for a few things.
    I use ArcSoft PhotoStudio to make color changes to certain things. However, in the Today style, when I try to change the 'caret' color, which is that selection bar, no matter how much I resize it, it always looks really thick, almost covering the top of the 2nd line (see image below).
    Also, when I try to change the focus circle, I open it with PhotoStudio and it changes the circle to this circle with a box around it, so when I try to change the color, it turns out like this (see picture below)
    I also have issues with using a transparent background if I upload and make minor changes to an icon (see picture below). So I found this american flag icon, altered the pic to make the colors darker, then it adds this white background instead of keeping it transparent.
    Is there a better program I could be using? Or any idea how to make these changes with this program? Or where can I find 'caret' and 'focus' icons so I don't have to worry about changing the colors.
    Sorry if I sound confusing, hopefully someone understands what I'm saying?
    Thanks!

    you can only use Plazmik, sorry.
    about transparency, when you use your drawing software and save the images, do you use a format that supports transparency ? There are two : GIF and PNG. All others add an opaque background color.
    The search box on top-right of this page is your true friend, and the public Knowledge Base too:

  • JOptionPane.showInputDialog and Focus

    I have a program that allows the user to type in a String in a text box and when they hit the enter key the text will appear in a text area. I've also added a menu bar to the program. When the user clicks on File and then Connect from the menu bar I want a JOptionPane to pop up that asks for the user to type in a username and then prompt for a password. And I've gotten all of that to work. Now for the problem. I click on file from the menu bar and then connect and it prompts me for the username as it should. I am able to just type in a phrase in the text field of the username dialog box and hit the enter key and then it prompts me for my password. I am still able to type in a phrase in the text field of the password Dialog box, however when I hit the enter key, the Dialog box does not close as it did for the username Dialog box. It will still close if I click on the OK button, but just pressing the enter key does not close the Dialog box as it did when it prompted for a username. I'm thinking I need to direct the focus to the password dialog box, but not sure how to go about doing this. Any help in solving this problem would be greatly appreciated.
    Here is my code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class TestJOptionPane extends JFrame implements ActionListener{
         private static int borderwidth = 570;
         private static int borderheight = 500;
         private JPanel p1 = new JPanel();
         private JMenu m1 = new JMenu("File");
         private JMenuBar mb1 = new JMenuBar();
         private JTextArea ta1 = new JTextArea("");
         private JTextField tf1 =new JTextField();
         private Container pane;
         private static String s1, username, password;
         private JMenuItem [] mia1 = {new JMenuItem("Connect"),new JMenuItem("DisConnect"),
              new JMenuItem("New..."), new JMenuItem ("Open..."), new JMenuItem ("Save"),
              new JMenuItem ("Save As..."), new JMenuItem ("Exit")};
    public TestJOptionPane (){
         pane = this.getContentPane();
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
         dispose();
    System.exit(0);
         setJMenuBar(mb1);
    mb1.add(m1);
    for(int j=0; j<mia1.length; j++){
         m1.add(mia1[j]);
    p1.setLayout( new BorderLayout(0,0));
    setSize(borderwidth, borderheight);
    pane.add(p1);
              p1.add(tf1, BorderLayout.NORTH);
              p1.add(ta1, BorderLayout.CENTER);
              this.show();
              tf1.addActionListener(this);
              for(int j=0; j<mia1.length; j++){
                   mia1[j].addActionListener(this);
         public void actionPerformed(ActionEvent e){
              Object source = e.getSource();
              if(source.equals(mia1 [0])){
                   username = JOptionPane.showInputDialog(pane, "Username");
                   password = JOptionPane.showInputDialog(pane, "Password");
              if(source.equals(tf1)){
                   s1=tf1.getText();
                   ta1.append(s1+"\n");
                   s1="";
                   tf1.setText("");
         public static void main(String args[]){
              TestJOptionPane test= new TestJOptionPane();
    }

    But using JOptionPane doesn't get the focus when you call itworks ok like this
    import javax.swing.*;
    import java.awt.event.*;
    class Testing
      public Testing()
        final JPasswordField pwd = new JPasswordField(10);
        ActionListener al = new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            pwd.requestFocusInWindow();}};
        javax.swing.Timer timer = new javax.swing.Timer(250,al);
        timer.setRepeats(false);
        timer.start();
        int action = JOptionPane.showConfirmDialog(null, pwd,"Enter Password",JOptionPane.OK_CANCEL_OPTION);
        if(action < 0)JOptionPane.showMessageDialog(null,"Cancel, X or escape key selected");
        else JOptionPane.showMessageDialog(null,"Your password is "+new String(pwd.getPassword()));
        System.exit(0);
      public static void main(String args[]){new Testing();}
    }

  • JOptionPane loosing focus

    I have the following piece of code. The problem is after I say YES to the first JOptionPane, the second JOptionPane displayed doesn't have focus. I'm displaying both the JOptionPane on JPanel. Can someone help me out and tell how can I get the focus on to the second JOptionPane ?
    public static boolean deleteConfirm(Component parent, String title, String confirmMsg1, String confirmMsg2) {
         int response = -1;
         response = JOptionPane.showOptionDialog(parent,                               confirmMsg1, title, JOptionPane.DEFAULT_OPTION,      JOptionPane.WARNING_MESSAGE, null, YES, NO);
         if(response == 0) {
    response = JOptionPane.showOptionDialog(parent,                               confirmMsg2, title, JOptionPane.DEFAULT_OPTION,                     JOptionPane.WARNING_MESSAGE, null, YES, NO);
         if(response == 1) return true;
         return false;

    This test worked just fine:
    import javax.swing.*;
    import java.awt.*;
    public class Test extends JFrame {
    public Test() {
         setSize(200,200);
         show();
         boolean b = deleteConfirm(this, "Please confirm", "Do you really want to delete", "Are you really really sure?");
    public static boolean deleteConfirm(Component parent, String title, String confirmMsg1, String confirmMsg2) {
    int response = -1;
    response = JOptionPane.showConfirmDialog(parent, confirmMsg1, title, JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
    if(response == 0) {
         response = JOptionPane.showConfirmDialog(parent, confirmMsg2, title, JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
         if(response == 1) return true;
    return false;
    public static void main(String args[]) {
         Test t = new Test();
    }Note that I used showConfirmDialog() instead of showOptionDialog().
    Save it to Test.java, compile and run.

Maybe you are looking for