JComboBox.setPopupVisible() and focus

Hello,
the following code demonstrates that always when the combobox is editable and the standard focus sequence is modified, a setPopupVisible(true) indeed opens the popup, but it is immediately closed again. Is anything wrong with the code?
Although there are quite a number of JComboBox bugs in the database, I did not find this one. If it is a bug, of course I would be interested in a workaround.
Regards
J�rg
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Y extends JFrame
  private JComboBox cmb;
  public Y()
  { setSize(300,300);
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    Container cp= getContentPane();
    cp.setLayout(null);
    final JCheckBox cb= new JCheckBox("Combo editable");
    cb.setBounds(80,30,130,20);
    cb.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
     cmb.setEditable(cb.isSelected());
    final JTextField tf1= new JTextField();
    tf1.setBounds(50,60,60,20);
    tf1.addFocusListener(new FocusAdapter() {
      public void focusLost(FocusEvent evt) {
     if (!tf1.getText().equals("ee")) {
       cmb.requestFocusInWindow(); // Prevents popup to stay open.
       cmb.setPopupVisible(true);
       System.out.println(cmb.isVisible());
    JTextField tf2= new JTextField();
    tf2.setBounds(150,60,60,20);
    tf2.addFocusListener(new FocusAdapter() {
      public void focusLost(FocusEvent evt) {
     cmb.setPopupVisible(true);
    cmb = new JComboBox(new String[]{"Item 1", "Item 2", "Item 3", "Item 4"});
    cmb.setBounds(100,90,50,20);
    cmb.setSelectedIndex(-1);
    System.out.println("LightWeight: "+cmb.isLightWeightPopupEnabled());
    cp.add(cb);
    cp.add(tf1);
    cp.add(tf2);
    cp.add(cmb);
    setVisible(true);
    tf1.requestFocusInWindow();
  public static void main(String args[])
  { java.awt.EventQueue.invokeLater(new Runnable()
    { public void run()
      { new Y();
}

Well, there's two things I note. The first is you're printing out the comboBox's visible status, which is always true, when you're probably trying to get the comboBox's popup's visible status.
The second thing is the cause of your problem. You request focus on the combo box. When it is editable, however, it is the editor component that gets the focus, not the combo box. So, the popup is made visible and then the editor component loses focus because the combo box gets focus, and so the popup is hidden.
This change does what you want, I think:
    tf1.addFocusListener(new FocusAdapter() {
      public void focusLost(FocusEvent evt) {
    if (!tf1.getText().equals("ee")) {
        if ( cmb.isEditable() )
            cmb.getEditor().getEditorComponent().requestFocusInWindow();
        else
            cmb.requestFocusInWindow(); // Prevents popup to stay open.
      cmb.setPopupVisible(true);
      System.out.println(cmb.isVisible());
    });

Similar Messages

  • [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!

  • 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:

  • JComboBox and focus

    I have 7 JComboBoxes on a JPanel on a JFrame.
    How can I dictate in the code which JComboBox has focus? Other languages I've have setFocus methods.
    Thanks,

    call requestFocus on the desired combo

  • Possible to get JComboBox before and after chaged value?

    Hi,
    I have a JComboBox... whenever the JComboBox value change is it possible to get the before and after changed value? For example:
    Let says the JComboBox is showing "One" and the user change it to "Three" after the user chged... I want to System.out.println before chged value ("One") and aft chged value ("Three")
    I tried:
    put in some code in the itemStateChanged() method... but no success...
    Can someone pls provide some pointer or sample code...
    Thank you for your time...

    Ok, I lost half a day on this (novice problem), but I arranjed a solution that resolve the problem totally. There is the code:
    YourComboBox.addFocusListener(new java.awt.event.FocusAdapter()
            int aux_selected;
            // if YourComboBox gains Focus
           public void focusGained(java.awt.event.FocusEvent fe)
                // get index value of selected element
               aux_selected= YourComboBox.getSelectedIndex();
               // create a variable for storing de ItemListener
              ComboBListener = new java.awt.event.ItemListener() {
                   public void itemStateChanged(java.awt.event.ItemEvent e)
                       if(e.getStateChange()==java.awt.event.ItemEvent.SELECTED)
                           // compares the selected value with the old one
                           if (aux_selected!=YourComboBox.getSelectedIndex())
                           System.out.println("ComboBox Changed !");
               // add the variable Listener to your Combo
               YourComboBox.addItemListener(ComboBListener);
           // if focus is lost
           public void focusLost(java.awt.event.FocusEvent fe)
              // remove the itemListener from the combobox
             YourComboBox.removeItemListener(ComboBListener);
    //Put the Listener variable outside
    private java.awt.event.ItemListener ComboBListener; //----------------------------------------------------------------------------------------------------
    You only have to change YourComboBox by the name of the combobox.
    To all people that help this forum (specially from PORTUGAL) and all java people: YOU ARE DOING A GREAT JOB

  • 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

  • Editable JComboBox in JTable focus issue

    Please look at the sample code below.
    I am using a JComboBox as the editor for a column in the table. When a cell in that column is edited and the user presses enter, the cell is no longer in edit mode. However, the focus is now set on the next component in the scrollpane (which is a textfield).
    If I don't add the textfield and the the table is the only component in the scroll pane, then focus correctly remains on the selected cell.
    When the user exits edit mode, I'd like the table to have focus and for the cell to remain selected. How can I achieve this?
    thanks,
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import javax.swing.plaf.basic.*;
    import java.awt.Component;
    import javax.swing.JComboBox;
    import java.util.EventObject;
    import java.awt.event.*;
    import javax.swing.event.*;
    public class TableComboBoxTest extends JFrame {
         protected JTable table;
         public TableComboBoxTest() {
              Container pane = getContentPane();
              pane.setLayout(new BorderLayout());
              MyTableModel model = new MyTableModel();
              table = new JTable(model);
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              table.setSurrendersFocusOnKeystroke(true);
              TableColumnModel tcm = table.getColumnModel();
              TableColumn tc = tcm.getColumn(MyTableModel.GENDER);
              tc.setCellEditor(new MyGenderEditor(new JComboBox()));
              tc.setCellRenderer(new MyGenderRenderer());
              JScrollPane jsp = new JScrollPane(table);
              pane.add(jsp, BorderLayout.CENTER);          
              pane.add(new JTextField("focus goes here"), BorderLayout.SOUTH);
         public static void main(String[] args) {
              TableComboBoxTest frame = new TableComboBoxTest();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(500, 300);
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         public class MyTableModel extends AbstractTableModel {
              public final static int FIRST_NAME = 0;
              public final static int LAST_NAME = 1;
              public final static int DATE_OF_BIRTH = 2;
              public final static int ACCOUNT_BALANCE = 3;
              public final static int GENDER = 4;
              public final static boolean GENDER_MALE = true;
              public final static boolean GENDER_FEMALE = false;
              public final String[] columnNames = {
                   "First Name", "Last Name", "Date of Birth", "Account Balance", "Gender"
              public Object[][] values = {
                        "Clay", "Ashworth",
                        new GregorianCalendar(1962, Calendar.FEBRUARY, 20).getTime(),
                        new Float(12345.67), "three"
                        "Jacob", "Ashworth",
                        new GregorianCalendar(1987, Calendar.JANUARY, 6).getTime(),
                        new Float(23456.78), "three1"
                        "Jordan", "Ashworth",
                        new GregorianCalendar(1989, Calendar.AUGUST, 31).getTime(),
                        new Float(34567.89), "three2"
                        "Evelyn", "Kirk",
                        new GregorianCalendar(1945, Calendar.JANUARY, 16).getTime(),
                        new Float(-456.70), "One"
                        "Belle", "Spyres",
                        new GregorianCalendar(1907, Calendar.AUGUST, 2).getTime(),
                        new Float(567.00), "two"
              public int getRowCount() {
                   return values.length;
              public int getColumnCount() {
                   return values[0].length;
              public Object getValueAt(int row, int column) {
                   return values[row][column];
              public void setValueAt(Object aValue, int r, int c) {
                   values[r][c] = aValue;
              public String getColumnName(int column) {
                   return columnNames[column];
              public boolean isCellEditable(int r, int c) {
                   return c == GENDER;
         public class MyComboUI extends BasicComboBoxUI {
              public JList getList()
                   return listBox;
         public class MyGenderRenderer extends DefaultTableCellRenderer{
              public MyGenderRenderer() {
                   super();
              public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {
                   JComboBox box = new JComboBox();
                   box.addItem(value);
                   return box;
         public class MyGenderEditor extends DefaultCellEditor  { // implements CaretListener {
              protected EventListenerList listenerList = new EventListenerList();
              protected ChangeEvent changeEvent = new ChangeEvent(this);
              private JTextField comboBoxEditorTField;
              Object newValue;
              JComboBox _cbox;
              public MyGenderEditor(JComboBox cbox) {
                   super(cbox);
                   _cbox = cbox;
                   comboBoxEditorTField = (JTextField)_cbox.getEditor().getEditorComponent();
                   _cbox.addItem("three");
                   _cbox.addItem("three1");
                   _cbox.addItem("three2");
                   _cbox.addItem("One");
                   _cbox.addItem("two");
                   _cbox.setEditable(true);
                   _cbox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
                             System.out.println("\nactionPerformed ");
                             fireEditingStopped();
              public void addCellEditorListener(CellEditorListener listener) {
                   listenerList.add(CellEditorListener.class, listener);
              public void removeCellEditorListener(CellEditorListener listener) {
                   listenerList.remove(CellEditorListener.class, listener);
              protected void fireEditingStopped() {
                   System.out.println("fireEditingStopped called ");
                   CellEditorListener listener;
                   Object[] listeners = listenerList.getListenerList();
                   for (int i = 0; i < listeners.length; i++) {
                        if (listeners[i] instanceof CellEditorListener) {
                             System.out.println("calling editingStopped on listener....................");                    
                             listener = (CellEditorListener) listeners;
                             listener.editingStopped(changeEvent);
              protected void fireEditingCanceled() {
                   System.out.println("fireEditingCanceled called ");
                   CellEditorListener listener;
                   Object[] listeners = listenerList.getListenerList();
                   for (int i = 0; i < listeners.length; i++) {
                        if (listeners[i] instanceof CellEditorListener) {
                             listener = (CellEditorListener) listeners[i];
                             listener.editingCanceled(changeEvent);
              public void cancelCellEditing() {
                   System.out.println("cancelCellEditing called ");
                   fireEditingCanceled();
              public void addNewItemToComboBox() {
                   System.out.println("\naddNewItemToComboBox called ");
                   // tc - start
                   String text = comboBoxEditorTField.getText();
                   System.out.println("text = "+text);                    
                   int index = -1;
                   for (int i = 0; i < _cbox.getItemCount(); i++)
                        String item = ((String)_cbox.getItemAt(i));
                        System.out.println("item in cbox = "+item);
                        if (item.equals(text))
                             System.out.println("selecting item now...");                              
                             index = i;
                             _cbox.setSelectedIndex(index);
                             break;
                   if (index == -1)
                        _cbox.addItem(text);
                        int count = _cbox.getItemCount();
                        _cbox.setSelectedIndex(count -1);
              public boolean stopCellEditing() {
                   System.out.println("stopCellEditing called ");
                   fireEditingStopped();
                   _cbox.transferFocus();
                   return true;
              public boolean isCellEditable(EventObject event) {
                   return true;     
              public boolean shouldSelectCell(EventObject event) {
                   return true;
              public Object getCellEditorValue() {
                   System.out.println("- getCellEditorValue called returning val: "+_cbox.getSelectedItem());
                   return _cbox.getSelectedItem();
              public Component getTableCellEditorComponent(JTable table, Object value,
                        boolean isSelected, int row, int column) {
                   System.out.println("\ngetTableCellEditorComponent "+value);
                   String text = (String)value;               
                   for (int i = 0; i < _cbox.getItemCount(); i++)
                        String item = ((String)_cbox.getItemAt(i));
                        System.out.println("item in box "+item);
                        if (item.equals(text))
                             System.out.println("selecting item now...");     
                             _cbox.setSelectedIndex(i);
                             break;
                   return _cbox;

    I was using java 1.5.0_06 in my application and I had this problem
    When I upgraded to java 1.6.0_01, I no longer had this issue.
    This seems to be a bug in 1.5 version of Java that has been fixed in 1.6
    thanks,

  • Problem with applet, popup window and focus loss

    Hi all !
    I've got a problem when my applet lose the focus. Let me explain :
    I've got an applet embed in a jsp page. There are several buttons in it that allow the user to open modal windows.
    The problem comes when the user gives the focus to another application whithout closing the modal window first.
    When he tries to come back to the web page owning the applet (using the task bar), then the modal window stays behind it and blocks any action on the applet.
    Does anyone know how to force the modal window to be displayed in front of the applet, even when the user plays with focuses ?
    Thank's in advance.

    thank you for your help, sils.
    I've written that code :
    * Cr�� le 31 ao�t 05
    package com.scor.apricot.web.rpc.ltnp.applet.listener.ldf;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    public class AppletWindowListener extends WindowAdapter {
         private JPanel panel;
         private JDialog dialogWindow;
         public AppletWindowListener(JPanel panel, JDialog dialogWindow) {
              this.panel = panel;
              this.dialogWindow = dialogWindow;
         public void windowActivated(WindowEvent e) {
              if (dialogWindow!=null && dialogWindow.isShowing())
                   dialogWindow.toFront();
    }Is that right ?
    I don't know how to add the listener, where must I put the addWindowListener method ? It seems that this method cannot be used with a JApplet object.

  • 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();}
    }

  • JDesktopPane / JInternalFrames and Focus

    Hi,
    I am running into a confusing focus issue with JDesktopPane and JInternalFrames. The problem is that when I close a JInternalFrame that has the keyboard focus, the DesktopPane will activate another internal frame, but that internal frame doesn't get the keyboard focus. I thought that some of my extension classes might be screwing this up, but I can recreate the problem using just the basic JDesktopPane and JInternalFrame objects. Has anyone run into this before? If so, how have you gotten around it? I'm using JDK 1.5 and the default Metal LAF.
    I have included a little application that demonstrates the issue. Click on one frame, then click on another frame and close this frame. The first frame will be active (ie highlighted), but it doesn't own the keyboard focus. Acutally the first frame gains the focus and then immediately looses the focus.
    Thanks for any help,
    -Yeath
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class DesktopTest extends JFrame
       private JDesktopPane desktop_pane;
       private int number;
       public DesktopTest()
          super( "DesktopTest Application" );
          this.desktop_pane = new JDesktopPane();
          this.number = 0;
          this.getContentPane().setLayout( new BorderLayout() );
          this.getContentPane().add( this.desktop_pane, BorderLayout.CENTER );
          JMenuBar menu_bar = new JMenuBar();
          JMenu file_menu = new JMenu( "File" );
          file_menu.add( new AbstractAction( "New Frame", null )
             public void actionPerformed( ActionEvent e )
                newFrame();
          menu_bar.add( file_menu );
          this.setJMenuBar( menu_bar );
          for( int i = 0; i < 4; i++ )
             newFrame();
       private void newFrame()
          final JInternalFrame jif = new JInternalFrame( "Frame " + Integer.toString( number + 1 ), true, true, true );
          jif.getContentPane().setLayout( new BorderLayout() );
          JTextField jtf = new JTextField();
          jif.getContentPane().add( jtf );
          jif.setBounds( number * 30, number * 30, 150, 100 );
          jtf.addFocusListener( new FocusListener()
             public void focusGained( FocusEvent e )
                System.out.println( jif.getTitle() + " has gained the focus" );
             public void focusLost( FocusEvent e )
                System.out.println( jif.getTitle() + " has lost the focus" );
          this.desktop_pane.add( jif );
          jif.setVisible( true );
          this.number++;
       public static void main( String[] args )
          DesktopTest desktop = new DesktopTest();
          desktop.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
          desktop.setSize( 800, 800 );
          desktop.setVisible( true );
    }

    Thanks for the replies,
    This sounds very much like the bug that has already been reported. But the work around doesn't seem to solve the problem. I catch the internalFrameClosed() event, and have the newly selected frame request the keyboard focus. But still I run into the situation where the frame gets the focus and immediately looses it again. If you look at the debug statements when executing the app, you'll see what i mean.
    Here is my updated newFrame function
    private void newFrame()
       final JInternalFrame jif = new JInternalFrame( "Frame " + Integer.toString( number + 1 ), true, true, true, true );
       jif.getContentPane().setLayout( new BorderLayout() );
       final JTextField jtf = new JTextField();
       jif.getContentPane().add( jtf );
       jif.setBounds( number * 30, number * 30, 150, 100 );
       jif.addInternalFrameListener( new InternalFrameAdapter()
          public void internalFrameActivated( InternalFrameEvent e )
             jtf.requestFocusInWindow();
          public void internalFrameClosed( InternalFrameEvent e )
             JInternalFrame selected = desktop_pane.getSelectedFrame();
             if( selected != null )
                selected.requestFocus();
       jtf.addFocusListener( new FocusListener()
          public void focusGained( FocusEvent e )
             System.out.println( jif.getTitle() + " has gained the focus" );
          public void focusLost( FocusEvent e )
             System.out.println( jif.getTitle() + " has lost the focus" );
       this.desktop_pane.add( jif );
       jif.setVisible( true );
       this.number++;
    }When I run this, and close a frame, I get the following debug output: It is as if nothing owns the keyboard focus after closing a frame.
    Frame 2 has lost the focus
    Frame 1 has gained the focus
    Frame 1 has lost the focusThanks for your help,
    -Yeath

Maybe you are looking for

  • Need help with Apple Display 20" going black

    There support and mac comrades, I was wondering if anyone has this following problem and had it fixed. I am currently using double 20" Apple display on a Mac Pro, and suddenly one of the screen start to turn black and get back to normal after few sec

  • "Slide to unlock" as well as characters "r,d,f,x,c" is not being typed in my iphone3 which has 6.0.1

    "Slide to unlock" as well as characters "r,d,f,x,c" is not being typed in my iphone3 which has 6.0.1 Other characters work though! Its hard to use it without being able to type those particular letters!! I have restored it but the problem reamined un

  • Secured Playlists

    Does anyone know of a way for users to secure Playlists? For example, I have a 10 yr old daughter and we share our Nano. However, I may have songs that may not be suitable for a 10yr old. Therefore, I would want to secure MY Playlist with some type o

  • Mac Pro Keeps Rebooting itself

    Hello, I am trying to figure out what is wrong with a Mac Pro I have.  It is 2.1, 3Ghz Quad Core.  It will run for about 30 to 40 minutes then automatically reboot it self.  I got it from someone else who told me about the problem, and I am trying to

  • Vmware fusion 4 needs vitalization technology enabled

    I need to install windows server 2008 because i need it for school, it installs with no problems in vmware, but when I try to enable hyper-v role it said that i need to have vt enabled. I tried the refit firmware, but when it starts i can't find the