JDialog + RequestFocus

Hi all,
how do i assign the focus to a JComponent (JTextArea) in a JDialog on opening the JDialog??
Tried calling textArea.requestFocusInWindow() in an overridden dialog.setVisible(..).
Thanks for any help.
Cheers,
Mark

Sorry, :(, no more ideas.
One thing only, try this to see how the focus is changing between components. Could help.
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener(new FocusChangeListener());
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addVetoableChangeListener(new FocusVetoableChangeListener());
    class FocusChangeListener implements PropertyChangeListener {
        public void propertyChange(PropertyChangeEvent evt) {
            Component oldComp = (Component)evt.getOldValue();
            Component newComp = (Component)evt.getNewValue();
            if ("focusOwner".equals(evt.getPropertyName())) {
                if (oldComp == null) {
                    // the newComp component gained the focus
                } else {
                    // the oldComp component lost the focus
            } else if ("focusedWindow".equals(evt.getPropertyName())) {
                if (oldComp == null) {
                    // the newComp window gained the focus
                } else {
                    // the oldComp window lost the focus
    class FocusVetoableChangeListener implements VetoableChangeListener {
        public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
            Component oldComp = (Component)evt.getOldValue();
            Component newComp = (Component)evt.getNewValue();
            if ("focusOwner".equals(evt.getPropertyName())) {
                if (oldComp == null) {
                    // the newComp component will gain the focus
                } else {
                    // the oldComp component will lose the focus
            } else if ("focusedWindow".equals(evt.getPropertyName())) {
                if (oldComp == null) {
                    // the newComp window will gain the focus
                } else {
                    // the oldComp window will lose the focus
            boolean vetoFocusChange = false;
            if (vetoFocusChange) {
                throw new PropertyVetoException("message", evt);
        }This piece of code helped me when I had a focus problem and I sow then how the events get through the system and figured out to use invokeLater().

Similar Messages

  • RequestFocus() not working for JTextArea

    requestFocus() is not working for JTextArea.
    A validation message is displayed and when clicked on 'ok', requestFocus() does not work. Cursor is not shown in the text
    area.
    Any suggestions/solutions pls?

    here is the sample code:
    public boolean checkData()
    String comment = commentArea.getText().trim();
    if( comment.length() < MN_COMMENT || comment.length() > MX_COMMENT )
    showError(COMMENT_ALERT);
    commentArea.requestFocus();
    return false;
    return true;
    Focus is lost. TextArea is in scroll pane. Scroll pane is contanined in a container pane and pane is for JDialog.
    RequestFocus() is working for JRE 1.5.0_07. But its not working for JRE 1.5.0_0 and lower versions.

  • JDialog and request focus

    Hi
    I am designing an application that brings up a JDialog box. When a button is pressed on this JDialog box this triggers an action event and some code is executed.
    When this button is pressed I dispose the dialog box and I want the focus to change to one of my components, I have been doing this with the requestFocus command. For some reason this focused event is not picked up by the focus handler. This only happens in this one place, if I move the requestFocus code to anywhere else in the program the focus event works fine. Does anyone have any ideas why.
    Thanks

    Without seeing any code, I would guess that disposing of a dialog causes focus changes to be requested internally. So if you put your focus change request after you dispose the dialog, that might help.

  • How to set Focus in a JDialog jdk 1.3.1

    I can't get the Focus to the wished component in my JDialogs when "invoke" them with
    setVisible(boolean)
    [\code]
    void mySetVisible()
    new FocusRequester(some JComponent of this Dialog);
    setVisible(true);
    public class FocusRequester implements Runnable // the classical Focus runner
    Component comp;
    public FocusRequester(Component comp)
    this.comp = comp;
    try
    if (comp != null)
    javax.swing.SwingUtilities.invokeLater(this);
    catch(Exception e)
    e.printStackTrace();
    public void run()
    comp.requestFocus();
    [\code]

    There are lot of way to do that. I suggest you use the WindowListener.
    import javax.swing.*;
    import java.awt.event.*;
    public class ShowDialog2 extends JFrame {
    public ShowDialog2() {
    this.setBounds(0, 0, 400, 400);
    this.setVisible(true);
    MyDialog waitDialog = new MyDialog (this);
    waitDialog.setBounds(0, 0, 100, 100);
    waitDialog.show();
    public static void main(String args[]) {
    new ShowDialog2();
    class MyDialog extends JDialog {
    JTextField _text1 = new JTextField();
    JTextField _text2 = new JTextField();
    public MyDialog(JFrame owner) {
    super(owner, true);
    this.getContentPane().add(_text1, "Center");
    this.getContentPane().add(_text2, "South");
    this.addWindowListener(new WindowAdapter() {
    public void windowOpened(WindowEvent e) {
    _text2.requestFocus();
    // Visual Paradigm for UML-Full feature UML CASE tool
    // http://www.visual-paradigm.com/

  • Clicking mouse after closing JDialog sends event to last component (1.1.8)

    There seems to be a bug in Java 1.1.8 that I'm looking for a workaround.
    I have a JButton on a JFrame that brings up a modal JDialog when you click it. After closing the dialog, if you click on the JFrame without moving the mouse, it will click the button on the frame that was last clicked, even if the mouse is not over the button.
    Steps to reproduce:
    1. Use the mouse to click on the button on the frame to bring up the dialog.
    2. Close the dialog with the mouse or keyboard and don't move the mouse at all. (Note that the mouse should be over the JFrame at this point, but not over the frame's button.)
    3. Click the mouse again.
    Result:
    This causes the button on the frame to be clicked.
    It seems as if the frame thinks that the mouse pointer is located where it was when the dialog came up.
    Does anyone know how to prevent this from happening or a workaround?

    We are using 1.1.8 because our product has to run on Mac OS 8.x - 9.x (and this is the latest JRE supported by these platforms).
    When I say don't move the mouse, what I mean is when closing the dialog, if you don't move the mouse, it doesn't matter where the mouse pointer is, as long as it's over the frame. When you click it, the last button to get clicked will be clicked again. It's as if the frame thinks that the mouse hasn't moved since the dialog came up. This isn't a focus problem because if I set the focus on another control after opening the dialog (by calling requestFocus()), this problem still happens. I can also tab to another control after closing the dialog, but when clicking the mouse it still clicks the last button that was clicked. It's as if the frame needs to reset where the mouse position is when it becomes activated.

  • Facing troubles with "requestFocus()"

    Hi
    Can anyone help me telling what is wrong with my code?. I hv 2 JTextFields and both will hv their values checked when losing focus. My problem is that a MessageDialog is showed telling what's wrong for the user, but then when ok button is clicked, the same messagedialog appears but with no button or message and everything freezes.
    Here's my code
    public void focusGained(FocusEvent e)
    public void focusLost(FocusEvent e)
    if (e.getSource().equals(edtCityCode))
    //check if CityCode is valid or not               
    if (!valid)
    JOptionPane.showMessageDialog(null, "This code is not valid. Type another");
    edtCityCode.requestFocus();
    else if (e.getSource().equals(edtCityName))
    if (edtCityName.getText().equalsIgnoreCase(""))
    JOptionPane.showMessageDialog(null, "You must type field = cityname");
    edtCityName.requestFocus();
    Thanks in advance.

    After reading all over Sun/Google/Yahoo about this bug and the workarounds posted for this problem I finally got to get it to work as per my requirements.
    Following were some of the constraints that I had:-
    1) All screens are already developed and buttons are already coded so I cannot go back and
    substitute extended JButton instance with has altered behaviour regarding focus events.
    So the one possible workaround that for this problem which involved extending JButton was ruled out.
    2) I want to make the IV generic so that it can read from some property file the rules to validate this.
    (I did not include this stuff in the implementation below but if you need that you can ask via email.
    3) I did not liked the idea of altering the basic plaf which was another way how people have worked out their ways from this problem.
    So here is my solution.
    1: Assign an extended verifier SCAInputVerifier to the JTextField/JTextArea. Pass the Container that contains the text field to the constructor of SCAInputVerifier.
    2: First time when the verify() method is called it creates a SCAJFocusListner as listed below. It validates and keeps the result in SCAInputVerifier but always returns true.
    3: As soon as the focus is about to loose to the next component the SCAJFocusListner comes into picture
    and displays the message via JOptionPane.showMessageDialog().
    (Before clicking the Ok button on this error message dialog if the user clicks on any AbstractButton it showed random behaviour.
    This is addressed in point 5)
    (Optional)
    4: As a general rule I we have all Cancel button or Close button closing the JDialog and their name starts with Cancel.
    If the user clicks cancel or close button on the screen user is allowed to go exit.
    5: Now the main problem:If the focus was going to a AbstractButton it was showing weired behaviour.
    It was getting pressed as soon as mouse was over that button.
    This problem is fixed in focusLost() method of SCAFocusListener.
    6: The focus is requested back into the text field.
    * SCAFocusListener.java
    * Created on August 14, 2003, 7:01 PM
    package walgreens.sca.system;
    import java.awt.event.*;
    import javax.swing.*;
    * @author Yogesh Gadge
    public class SCAFocusListener extends FocusAdapter{
    private SCAInputVerifier iv = null;
    public SCAFocusListener(SCAInputVerifier iv) {
    super();
    this.iv=iv;
    public void focusLost(FocusEvent fe) {
    if ( (! iv.isGood()) && iv.getParentPane()!= null && iv.getParentPane().isVisible()) {
    java.awt.Component opp = fe.getOppositeComponent();
    //if cancel or close button
    if (opp instanceof AbstractButton) {
    AbstractButton aBut = (AbstractButton)opp;
    String name = aBut.getText();
    if(name != null && (name.trim().toLowerCase().startsWith("cancel") || name.trim().toLowerCase().startsWith("close"))) {
    return;
    //workaround for bug in JDK 1.4.1 bugID 4342333
    ButtonModel mod = aBut.getModel();
    aBut.revalidate();
    if (mod.isArmed())
    mod.setArmed(false);
    if (mod.isPressed())
    mod.setPressed(false);
    JOptionPane.showMessageDialog(iv.getParentPane(),"Input is invalid.");
    java.awt.Component c = fe.getComponent();
    //fe.consume();
    c.requestFocusInWindow();//InWindow();
    } else
    super.focusLost(fe);
    import javax.swing.*;
    import java.awt.event.*;
    * @author Yogesh Gadge
    public class SCAInputVerifier extends javax.swing.InputVerifier {
    private java.awt.Container parentPane=null;
    private boolean good = false;
    private FocusListener focusListener = null;
    /** Creates a new instance of SCAInputVerifier */
    public SCAInputVerifier(java.awt.Container parentPane) {
    this.parentPane=parentPane;
    public boolean verify(javax.swing.JComponent comp) {
    if (focusListener == null)
    comp.addFocusListener(createFocusListener());
    this.good=true;
    if (comp instanceof javax.swing.text.JTextComponent) {
    javax.swing.text.JTextComponent field = (javax.swing.text.JTextComponent) comp;
    String input = field.getText();
    System.out.println(input);
    try {
    //lets say it is convergence factor
    double d = Double.parseDouble(input);
    if (d < 0.0 || d >=1.0 )
    good=false;
    } catch(Exception e) {
    good=false;
    return true;
    public boolean isGood() {
    return this.good;
    protected FocusListener createFocusListener() {
    FocusListener f = new SCAFocusListener(this);
    System.out.println(f);
    this.focusListener=f;
    return f ;
    /** Setter for property good.
    * @param good New value of property good.
    public void setGood(boolean good) {
    this.good = good;
    /** Getter for property focusListener.
    * @return Value of property focusListener.
    public java.awt.event.FocusListener getFocusListener() {
    return focusListener;
    /** Setter for property focusListener.
    * @param focusListener New value of property focusListener.
    public void setFocusListener(java.awt.event.FocusListener focusListener) {
    this.focusListener = focusListener;
    /** Getter for property parentPane.
    * @return Value of property parentPane.
    public java.awt.Container getParentPane() {
    return parentPane;
    /** Setter for property parentPane.
    * @param parentPane New value of property parentPane.
    public void setParentPane(java.awt.Container parentPane) {
    this.parentPane = parentPane;

  • Focus on JTextfield in JDialog box

    A JDialog box is being opened from a menu.
    There is only one JTextfield on the dialog box and 2 buttons.
    The focus is not on any of the components in the dialog box and I want it on the textfield by default.
    I have tried all the requestFocus(),requestDefaultFocus(),grabfocus() etc and none of them work.
    There is an eventListener added to the JTextfield could this be the problem.

    I am a little supprised that the focus is not given to the text field if that is the only thing on the dialog.
    You could try detecting the display of the dialog and then giving the focus to the text field. Focus will not be given to a component if the component cant be displayed at that time. My guess is that the dialog is still hidden when you are trying to set the focus and that is what is causing the problem.

  • JTextField.select(int, int) not working in modal JDialog

    Hi
    I have discovered something peculiar. When I have a JDialog, and it is modal, then the select method of any JTextfield will surely fail. (Only tested on win32)
    What the owner is does not matter (even null will give the same result). I made a JFrame for your convenience.
    import javax.swing.*;
    public class MyDialog extends JDialog
         private JTextField     tf     = new JTextField("not selected >selected< not selected");
         public static void main(String[] args)
              JFrame f = new JFrame("Some parent frame");
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.setVisible(true);
              new MyDialog(f);
         public MyDialog(JFrame parent)
              super(parent, "Child dialog", /*Selecct modality*/ true);
              // super();
              super.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
              super.add(this.tf);
              super.pack();
              super.setLocation(0, 50);
              super.setVisible(true);
              // Selection does not work when dialog is modal.
              this.tf.select(14, 22);
              this.tf.requestFocus();
    }I did not find a bug in the database concerning this.
    Did I do something wrong, or should I post this as a bug?

    1) Please do not dredge posts that are months or years old. If you have something important to say, create your own thread.
    2) If you have the same problem, then use the same solution.
    3) If this doesn't work, then show your problem: show your code. We don't want to see all of it, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem, in other words, an SSCCE (Short, Self Contained, Correct (Compilable), Example). For more info on SSCCEs please look here:
    http://homepage1.nifty.com/algafield/sscce.html
    Also, when posting your code, please use code tags so that your code will be well-formatted and readable. To do this, either use the "code" button at the top of the forum Message editor or place the tag &#91;code&#93; at the top of your block of code and the tag &#91;/code&#93; at the bottom, like so:
    &#91;code&#93;
      // your code block goes here.
    &#91;/code&#93;

  • RequestFocus() work only once? why???

    i have a JDialog called setting.
    When user press a button, setting is showed with this code.
    setting.setCenter();
    setting.focusFirstBlank();
    setting.setVisible(true);
    which focusFirstBlank() is
    public void focusFirstBlank(){
    if(Smtp.getText().trim().length() == 0) {Smtp.requestFocus(); return;}
              if(Pop.getText().trim().length() == 0) {Pop.requestFocus(); return;}
              if(UserName.getText().trim().length() == 0) {UserName.requestFocus(); return;}
              if(Password.getText().trim().length() == 0) { Password.requestFocus(); return;}
              if(Name.getText().trim().length() == 0) {Name.requestFocus(); return;}
              if(Email.getText().trim().length() == 0) {Email.requestFocus(); return;}
    Smtp,Pop,UserName,Password,Name,Email are JTextFiled.
    when button is first pressed, it works fine.
    The 1st blank JTextField is focused.
    but in 2nd and later pressed, there's no focus.
    why doesn't requestFocus() work??
    I read some forum about similar problem and some said try to put setVisible(true); before requstFocus();
    I tried but it still doesn't work.
    I really don't have a clue.
    Would you please help me??

    The problem is comming from Multithread (Because the swing is multithread). Try following code:
    Runnable r = new Runnable() {
    public void run() {
    Password.requestFocus();
    SwingUtilities.invokeAndWait(r);

  • Execute code after show() in a Modal JDialog

    Is there any way of executing a piece of code after a Modal JDialog's show() method ? I tried to run the code using SwingUtilities.invokeLater to no use. Any ideas ?
    Thanks !

    Thanks Jamie !
    Adding a new thread wasn't required. I found the solution in some forum. The main issue was to get focus to a textfield in JDialog along with displaying a JPopupMenu against it. I could get the focus in but the popup wasn't showing. In brief this is what solved it.
    Assuming JTextField is testField. I add this listener to the textField just before calling JDialog.show().
    <code>
         private FocusListener fListen = new FocusListener()
              public void focusGained(FocusEvent e)
                   // showPop() logic
              public void focusLost(FocusEvent e)
                   testField.removeFocusListener(fListen);
                   testField.requestFocus();
    </code>

  • Changing Focus on JDialog Button

    Hi,
    I have created a JOptionPane with the optionType of YES_NO_OPTION. I then create a JDialog out of it. So the JDialog honestly does the job and Shows up a Dialog Box with YES and NO button. The Focus is set on YES button...but I want it changed to NO button....does anyone have a Idea how to do it???
    Cheers,
    Manjunath Rane

    NO It does NOT work.
    Instead I have successfully tried out by attaching a WindowListener to the Dialog I create. I then override the windowOpened method and set the requestFocus on NO Button (Getting the Handle of the NO button was a Tough task. I had iterated thru the Panels inside the JDialog to get the instance......does somebody have a Better Solution????)
    Cheers,
    Manjunath Rane

  • SetVisible(false) doesn't work with JDialog

    Hi evry one in this forum, i am using JDialog to get some inputs from user, when the user click on the ok button, i start processing and the JDialog must be invisible, for that i use myJdialog.setVisible(false) methode, but the JDialog is still visible, i may be use the wrong component or there is a problem.
    I write some thing like this:
    actionPerformed(){
    //getinputs and make some controls
    if(test){
    this.setVisible(false);
    //some traitments
    //some traitments
    }I think there is no thing wrong, not? what happen?

    I am sorry, this is some thing complicated:
    public class OpenKeyStore
        extends JDialog
        implements ActionListener, KeyListener, WindowListener {
      JPanel jPanel1 = new JPanel();
      Border border1;
      JLabel lprivateKey = new JLabel();
      JLabel lkeyPass = new JLabel();
      JTextField tkeyStorePath = new JTextField();
      JPasswordField tkeyPass = new JPasswordField();
      JButton bvalidate = new JButton();
      JButton bopenKeyStore = new JButton();
      JButton breset = new JButton();
      GridBagLayout gridBagLayout1 = new GridBagLayout();
      JFileChooser jfc = new JFileChooser();
      JOptionPane jop = new JOptionPane();
      private UploadParameters uploadParameters;
      private OpenRequest openRequest;
      private OpenResponse openResponse;
      private CheckCertRequest checkCertRequest;
      private CheckCertResponse checkCertResponse;
      private WaitBox waitBox;
      UploadApplet uploadApplet;
      public OpenKeyStore(Frame frame, String title, boolean modal) {
        super(frame, title, modal);
        try {
          jbInit();
        catch (Exception ex) {
          ex.printStackTrace();
      public OpenKeyStore(UploadApplet uploadApplet) {
        this(null, "", false);
        this.uploadApplet = uploadApplet;
      private void jbInit() throws Exception {
        uploadParameters = new UploadParameters();
        border1 = new EtchedBorder(EtchedBorder.RAISED, Color.white,
                                   new Color(148, 145, 140));
        this.setModal(true);
        this.setTitle("Ouvrir");
        jPanel1.setBorder(border1);
        jPanel1.setLayout(gridBagLayout1);
        jPanel1.setSize(400, 140);
        lprivateKey.setText("Cl� priv�e :");
        lkeyPass.setText("Mot de passe : ");
        bopenKeyStore.setActionCommand("openKeyStore");
        bopenKeyStore.setText("Ouvrir");
        bopenKeyStore.setMnemonic(KeyEvent.VK_O);
        bopenKeyStore.addKeyListener(this);
        bopenKeyStore.addActionListener(this);
        bvalidate.setActionCommand("bvalidate");
        bvalidate.setText("Valider");
        bvalidate.setMnemonic(KeyEvent.VK_V);
        bvalidate.addKeyListener(this);
        bvalidate.addActionListener(this);
        breset.setActionCommand("breset");
        breset.setText("R�etablir");
        breset.setMnemonic(KeyEvent.VK_R);
        breset.addKeyListener(this);
        breset.addActionListener(this);
        tkeyStorePath.setText("C:\\y.p12");
        tkeyStorePath.addKeyListener(this);
        tkeyPass.setText("y");
        tkeyPass.addKeyListener(this);
        this.getContentPane().add(jPanel1, BorderLayout.CENTER);
        this.getContentPane().setSize(410, 150);
        jPanel1.add(lprivateKey, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
            , GridBagConstraints.WEST, GridBagConstraints.NONE,
            new Insets(5, 5, 5, 5), 0, 0));
        jPanel1.add(lkeyPass, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
                                                     , GridBagConstraints.WEST,
                                                     GridBagConstraints.NONE,
                                                     new Insets(5, 5, 5, 5), 0, 0));
        jPanel1.add(tkeyStorePath, new GridBagConstraints(1, 0, 1, 1, 10.0, 0.0
            , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
            new Insets(5, 5, 5, 5), 150, 0));
        jPanel1.add(tkeyPass, new GridBagConstraints(1, 1, 1, 1, 10.0, 0.0
                                                     , GridBagConstraints.WEST,
                                                     GridBagConstraints.HORIZONTAL,
                                                     new Insets(5, 5, 5, 5), 200, 0));
        jPanel1.add(bvalidate, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0
                                                      , GridBagConstraints.EAST,
                                                      GridBagConstraints.NONE,
                                                      new Insets(5, 5, 5, 5), 0, 0));
        jPanel1.add(bopenKeyStore, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0
            , GridBagConstraints.CENTER, GridBagConstraints.NONE,
            new Insets(5, 5, 5, 5), 0, 0));
        jPanel1.add(breset, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0
                                                   , GridBagConstraints.CENTER,
                                                   GridBagConstraints.NONE,
                                                   new Insets(5, 5, 5, 5), 0, 0));
        this.initFileChooser();
        this.tkeyStorePath.requestFocus();
        this.pack();
        Rectangle screenRect = this.getGraphicsConfiguration().getBounds();
        this.setLocation(
            screenRect.x + screenRect.width / 2 - this.getSize().width / 2,
            screenRect.y + screenRect.height / 2 - this.getSize().height / 2);
        this.show();
      public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("openKeyStore")) {
          this.showOpenFileChooser();
          return;
        if (e.getActionCommand().equals("bvalidate")) {
          this.acte();
          return;
        if (e.getActionCommand().equals("breset")) {
          this.reset();
          return;
      public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
          if (e.getSource() == this.bopenKeyStore ||
              e.getSource() == this.tkeyStorePath) {
            this.showOpenFileChooser();
            return;
          if (e.getSource() == this.bvalidate ||
              e.getSource() == this.tkeyPass) {
            this.acte();
            return;
          if (e.getSource() == this.breset) {
            this.reset();
            return;
      public void keyReleased(KeyEvent e) {}
      public void keyTyped(KeyEvent e) {
      private void initFileChooser() {
        jfc.setFileFilter(new javax.swing.filechooser.FileFilter() {
          public boolean accept(File f) {
            return (f.getName().endsWith(".p12") || f.isDirectory());
          public String getDescription() {
            return "(.p12) fichier key store";
        jfc.setDialogTitle("Selectionnez un fichier .p12");
        jfc.setMultiSelectionEnabled(false);
        jfc.setDialogType(JFileChooser.OPEN_DIALOG);
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
      private void showOpenFileChooser() {
        int returnVal = jfc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION && jfc.getSelectedFile() != null &&
            jfc.getSelectedFile().exists()) {
          this.tkeyStorePath.setText(jfc.getSelectedFile().getAbsolutePath());
          this.tkeyPass.requestFocus();
        else {
          this.tkeyStorePath.requestFocus();
      private void reset() {
        this.tkeyStorePath.setText("");
        this.tkeyStorePath.requestFocus();
        this.tkeyPass.setText("");
      private void acte() {
    //waitBox = new WaitBox();
        openRequest = new OpenRequest();
        openRequest.setStorePath(this.tkeyStorePath.getText());
        if (!openRequest.isValide()) {
          jop.showMessageDialog(null,
                                "S.V.P v�rifiez le chemin de votre cl�!",
                                "Echec...", jop.ERROR_MESSAGE);
          this.tkeyStorePath.requestFocus();
          this.tkeyStorePath.selectAll();
          return;
        openRequest.setStorePass(new String(this.tkeyPass.getPassword()));
        openRequest.setReciverCert(this.uploadParameters.getReciverCert());
        OpenAction openAction = new OpenAction(this.openRequest);
        try {
          while (openResponse == null) {
            Thread.sleep(100);
            openResponse = (OpenResponse) openAction.getResponse();
        catch (Exception e) {
          e.printStackTrace();
        if (openResponse.getSenderPK() == null) {
          jop.showMessageDialog(null,
              "S.V.P entrez une cl� valide, \n ou verifiez votre mot de passe !",
              "Echec...", jop.ERROR_MESSAGE);
          this.tkeyStorePath.requestFocus();
          this.tkeyStorePath.selectAll();
          return;
        if (openResponse.getCaCert() == null) {
          this.setVisible(false);
          jop.showMessageDialog(null,
              "Votre cl� n'est pas valide.\n contactez votre administrateur!",
              "Echec...", jop.ERROR_MESSAGE);
          this.gotoPreviousPage();
          return;
        if (this.uploadParameters.getCipher() && openResponse.getReciverCert() == null) {
    this.setVisible(false);//*********************Does not work
    jop.showMessageDialog(null,
              "Vous ne disposez pas de certificat pour votre correspondant!",
              "Echec...", jop.ERROR_MESSAGE);
          this.gotoPreviousPage();
          return;
        this.setVisible(false);//*********************Does not work
        if (this.uploadParameters.getCipher()) {
          String compte;
          while (true) {
            compte = (String) JOptionPane.showInputDialog(
                this, "S.V.P. entrez le compte de votre correspondant : ",
                "Customized Dialog", JOptionPane.PLAIN_MESSAGE, null, null, "");
            if (compte == null) {
              //gotoprevious page
              return;
            this.checkCertRequest.setCommunName(compte);
            if (this.checkCertRequest.isValide()) {
              this.checkCertRequest.setReciverCert(this.openResponse.getReciverCert());
              this.checkCertRequest.setCaCert(this.openResponse.getCaCert());
              CheckCertAction checkCertAction = new CheckCertAction(this.
                  checkCertRequest);
              try {
                while (this.checkCertResponse == null) {
                  Thread.sleep(100);
                  this.checkCertResponse = (CheckCertResponse) checkCertAction.
                      getResponse();
              catch (Exception e) {
                e.printStackTrace();
              if (this.checkCertResponse.getReciverCertState()) {
                return;
              else {
                jop.showMessageDialog(null,
                    "L'identit� de votre correspondant n'a pas pu etre v�rifier!",
                    "Echec...", jop.ERROR_MESSAGE);
      public void windowActivated(WindowEvent e) {}
      public void windowClosed(WindowEvent e) {}
      public void windowDeactivated(WindowEvent e) {}
      public void windowDeiconified(WindowEvent e) {}
      public void windowIconified(WindowEvent e) {}
      public void windowOpened(WindowEvent e) {}
      public void windowClosing(WindowEvent e) {
        this.gotoPreviousPage();
      public void gotoPreviousPage() {
    }

  • ToFront() for JDialog Re-visited

    My JDialog is buried behind other windows on Win2K using JDK 1.4.0. After searching the archives on this subject I tried the suggestions and am still having no luck. Below are my code snippets (which use some suggestions in past posts of this same question).
    public class MyDialog extends JDialog implements ActionListener {
    // Constructor
    public MyDialog(Frame f, Object o, ...) {
         super (f, "MyTitle", true);
         // create and add a panel w/ controls
         // Stuff I tried and commented out when it didn't work
         // f.setState(Frame.ICONIFIED);
         // f.setState(Frame.NORMAL);
         // f.setVisible(true);
         // f.toFront();
         // f.requestFocus();
         // toFront();
         // requestFocus();
    The caller code:
    Frame f = new Frame();
    MyDialog dialog = new MyDialog(f, this, ...);
    dialog.pack();
    dialog.setLocation(400, 400);
    f.setState(Frame.ICONIFIED);
    f.setState(Frame.NORMAL);
    f.setVisible(true);
    f.toFront();
    f.requestFocus();
    dialog.setVisible(true);
    dialog.toFront();
    dialog.requestFocus();
    Any suggestions would make me a happer camper!!
         

    V.V.,
    You hit on the 'trick' that I FINALLY figured out--
    In my code, the caller was already a JFrame (it was the main window for my GUI app). I passed "this" JFrame in to the JDialog constructor instead of a new JFrame AND used a hack mentioned by a previous kind soul to first set the state of the OWNER to 'iconified' and then to 'normal'.
    To help out all past and future askers of this same question, I'll give my code (and basic threading model) that seems to be working (SO FAR, at least) under Windows2000 w/ JDK1.4.0.
    1) The main window of the GUI app extends JFrame and is
    the creator of a MyDialog object:
    public class MainWindow extends JFrame implements ActionListener {
         // lots of variables and methods here
         // etc.
         // etc.
    public void showDialog(String s, String s2)
         // Use SwingUtilities.invokeLater() since a
         // different thread (one that listens on a
         // blocked socket) will call this method.
         final String sender = s;
         final String name = s2;
         SwingUtilities.invokeLater(new Runnable()
         public void run()
              // do some parsing, etc.
              // blah, blah.
              // blah
              MyDialog md = new MyDialog(this, this, ...);
         // hack to prevent 'md' from being
              // buried behind other open windows
              // it first iconifies the main win and
              // then de-iconifies it
              this.setVisible(true);
              this.setExtendedState(Frame.ICONIFIED);
              this.setExtendedState(Frame.NORMAL);
              this.toFront();
              this.requestFocus();
              md.pack();
              md.setLocation(400, 400);
              md.setVisible(true);
              // Don't know if the following is
              // redundant and unnecessary... will
              // delete and test later
              md.toFront();
              md.requestFocus();
    public class MyDialog extends JDialog implements ActionListener {
         // some variables here before the constructor
         public MyDialog(Frame f, MainWindow win, ...)
         // Make this modal.
         super(f, "My Dialog", true);
         // Now create JPanel and controls...
    public actionPerformed(ActionEvent e) {
         // code here for processing actions
    My intention was to show how I did finally manage to get a JDialog to popup in front of any and all open
    windows and do so in a multi-threaded app.
    If anyone has a better solution, I'm all ears!!
    Thanks to those to led me this far :)     

  • Enter in JDialog

    Hello friends !
    I have JDialog with some JLabels, JSpinners and one JButton.
    The JSpinners are numerical, i.e. if I type say "bla bla" in it, I hear a beep. Only when enter a number JSpinner accepts it.
    When I click the JButton, loadPicture() called.
    I want that if I press Enter after (enter some number in the JSpinner), loadPicture() will be called.
    What should I add ?
    Below is the code of the JDialog.
    Thanks in advance !!!
    public class JCRandomCrosswordDialog extends JDialog implements ActionListener {
         private JCFrame mainFrame;
         private JTextField fillingPercentageField;
         private JSpinner rowsSpinner, columnsSpinner;
         private JButton createButton = new JButton("Create random crossword");
         public JCRandomCrosswordDialog(JCFrame mainFrame) {
                super(mainFrame, "Create random crossword", true);
                this.mainFrame = mainFrame;
                rowsSpinner = new JSpinner(new SpinnerNumberModel(mainFrame.getDefaultNumberOfRows(), 1, mainFrame.getMaxNumberOfRows(), 1));
                columnsSpinner = new JSpinner(new SpinnerNumberModel(mainFrame.getDefaultNumberOfColumns(), 1, mainFrame.getMaxNumberOfColumns(), 1));
                fillingPercentageField = new JTextField(String.valueOf(mainFrame.getDefaultPercentageOfFilling()));
                ((JSpinner.DefaultEditor)(rowsSpinner.getEditor())).getTextField().setHorizontalAlignment(JTextField.LEFT);
                ((JSpinner.DefaultEditor)(columnsSpinner.getEditor())).getTextField().setHorizontalAlignment(JTextField.LEFT);
                JCToolkit.setSelectAllFieldText(((JSpinner.DefaultEditor)(rowsSpinner.getEditor())).getTextField());
                JCToolkit.setSelectAllFieldText(((JSpinner.DefaultEditor)(columnsSpinner.getEditor())).getTextField());
                JCToolkit.setSelectAllFieldText(fillingPercentageField);
                Container contentPane = getContentPane();
                JPanel dialogPanel = new JPanel();
             dialogPanel.setLayout(new GridLayout(3, 2));
             dialogPanel.add(new JLabel("  Number of rows:", JLabel.LEFT));
             dialogPanel.add(rowsSpinner);
             dialogPanel.add(new JLabel("  Number of columns:", JLabel.LEFT));
             dialogPanel.add(columnsSpinner);
             dialogPanel.add(new JLabel("  Filling percentage:", JLabel.LEFT));
             dialogPanel.add(fillingPercentageField);
             contentPane.add(dialogPanel, BorderLayout.NORTH);
             createButton.addActionListener(this);
             contentPane.add(createButton, BorderLayout.SOUTH);
                setSize(260, 125);
         public void actionPerformed(ActionEvent e) {
              int numOfRows = getSpinnerValue(rowsSpinner, mainFrame.getDefaultNumberOfRows());
              if ((numOfRows < 1) || (numOfRows > mainFrame.getMaxNumberOfRows())) throw new NumberFormatException();
              int numOfColumns = getSpinnerValue(columnsSpinner, mainFrame.getDefaultNumberOfColumns());
              if ((numOfColumns < 1) || (numOfColumns > mainFrame.getMaxNumberOfColumns())) throw new NumberFormatException();
              try {     
                   float percentage = (Float.valueOf(fillingPercentageField.getText())).floatValue();
                   if ((percentage < 0.0f) || (percentage > 100.0f)) throw new NumberFormatException();
                   dispose();
                   ((JCFrame)getOwner()).loadPicture(JCToolkit.getRandomCrossword(numOfRows, numOfColumns, percentage / 100));
              } catch (NumberFormatException nfe) {
                   fillingPercentageField.requestFocus();
         private int getSpinnerValue(JSpinner spinner, int defaultValue) {
              try { spinner.commitEdit(); }
              catch (ParseException pe) { spinner.setValue(defaultValue); }
              return ((Integer)(spinner.getValue())).intValue();
    }

    OK, Michael. Now is much much better !
    But still 2 questions:
    1) If I type some string on the "Number of rows" spinner, then press Enter, the dialog takes the default value 10 (which I see when I enter the dialog again). But If I enter some string in the "Filling percentage" spinner, then press Enter, the dialog doesn't take the default value (it takes all the string). Why ?
    2) I want that if the entered number is out of legal range, i.e. for example ((numOfRows < 1) || (numOfRows > 99)) then pressing Enter will not close the dialog with the default values, and the user will need to enter a legal values. What should I change to add this requirement ?
    Many thanks again !!!
    Here is the last code:
    import javax.swing.*;       
    public class Test {
         private static void createAndShowGUI() {       
            JFrame frame = new JFrame("HelloWorldSwing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            MyDialog dialog = new MyDialog(frame);
                MyMenuBar menuBar = new MyMenuBar(frame);
              frame.setJMenuBar(menuBar);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    import java.text.ParseException;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MyDialog extends JDialog implements ActionListener {
         private JFrame mainFrame;
         private JTextField fillingPercentageField;
         private JSpinner rowsSpinner, columnsSpinner;
         private JButton createButton = new JButton("Create random crossword");
         public MyDialog(JFrame mainFrame) {
                super(mainFrame, "Create random crossword", true);
                this.mainFrame = mainFrame;
                rowsSpinner = new JSpinner(new SpinnerNumberModel(10, 1, 99, 1));
                columnsSpinner = new JSpinner(new SpinnerNumberModel(20, 1, 100, 2));
                fillingPercentageField = new JTextField(String.valueOf(8.7));
                ((JSpinner.DefaultEditor)(rowsSpinner.getEditor())).getTextField().setHorizontalAlignment(JTextField.LEFT);
                ((JSpinner.DefaultEditor)(columnsSpinner.getEditor())).getTextField().setHorizontalAlignment(JTextField.LEFT);
                Container contentPane = getContentPane();
                JPanel dialogPanel = new JPanel();
                  dialogPanel.setLayout(new GridLayout(3, 2));
                  dialogPanel.add(new JLabel("  Number of rows:", JLabel.LEFT));
                  dialogPanel.add(rowsSpinner);
                  dialogPanel.add(new JLabel("  Number of columns:", JLabel.LEFT));
                  dialogPanel.add(columnsSpinner);
                  dialogPanel.add(new JLabel("  Filling percentage:", JLabel.LEFT));
                  dialogPanel.add(fillingPercentageField);
                  contentPane.add(dialogPanel, BorderLayout.NORTH);
                  createButton.addActionListener(this);
                  contentPane.add(createButton, BorderLayout.SOUTH);
                  KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
                      public boolean dispatchKeyEvent(KeyEvent ke) {
                             if(ke.getID() == KeyEvent.KEY_PRESSED) {
                               if (((KeyEvent) ke).getKeyCode() == KeyEvent.VK_ENTER) {
                                      //createButton.doClick();
                                      if(isVisible()) createButton.doClick();
                             return false;
                setSize(260, 125);
         public void actionPerformed(ActionEvent e) {
              int numOfRows = getSpinnerValue(rowsSpinner, 10);
              if ((numOfRows < 1) || (numOfRows > 99)) throw new NumberFormatException();
              int numOfColumns = getSpinnerValue(columnsSpinner, 20);
              if ((numOfColumns < 1) || (numOfColumns > 100)) throw new NumberFormatException();
              try {     
                   float percentage = (Float.valueOf(fillingPercentageField.getText())).floatValue();
                   if ((percentage < 0.0f) || (percentage > 100.0f)) throw new NumberFormatException();
              } catch (NumberFormatException nfe) {
                   fillingPercentageField.requestFocus();
              } finally {
                   dispose();
              JOptionPane.showMessageDialog(mainFrame, "OK", "Important Message", JOptionPane.PLAIN_MESSAGE);
         private int getSpinnerValue(JSpinner spinner, int defaultValue) {
              try { spinner.commitEdit(); }
              catch (ParseException pe) { spinner.setValue(defaultValue); }
              return ((Integer)(spinner.getValue())).intValue();
    import javax.swing.*;
    import java.awt.event.*;
    public class MyMenuBar extends JMenuBar implements ActionListener {
         private JFrame mainFrame;
         private JMenuItem showDialog;
         private MyDialog dialog;
         public MyMenuBar(JFrame mainFrame) {
              this.mainFrame = mainFrame;
              dialog = new MyDialog(mainFrame);
              JMenu menu = new JMenu("Misc");    
              menu.setMnemonic(KeyEvent.VK_M);
              showDialog = new JMenuItem("Show dialog");
              showDialog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0));
              showDialog.addActionListener(this);
              menu.add(showDialog);
              add(menu);
         public void actionPerformed(ActionEvent e) {
              if (e.getSource() == showDialog) {
                   dialog.setVisible(true);
                   return;
    }

  • RequestFocus and GrabFocus Problems

    I have created a class that extends from JDialog and asks the user to enter some data. It is important that the text field always has initial focus, but this only occurs the first time the dialog is displayed. Any other times I call it up ( show() ) the text field does not get focus. I've tried all the following functions to no avail:
    infoTextField.setRequestFocusEnabled(true);
    infoTextField.requestDefaultFocus();
    infoTextField.grabFocus();
    infoTextField.requestFocus();
    Why are these functions not working properly for me? Any help would be much appreciated! Here is the function code that I call repeatedly and if any errors lie in it, please let me know:
    public String getInfoBox(String topmessage, String bottommessage, String buttonText) {
    this.addKeyListener(this);
    speichern.setText(""+buttonText+"");
    infoTextField.setText("");
    message1.setText(topmessage);
    message2.setText(bottommessage);
    bh.setVisible(false);
    infoPanel.setVisible(true);
    infoTextField.setRequestFocusEnabled(true);
    infoTextField.requestDefaultFocus();
    show();
    while(!ready) { } // waits till a button is pressed
    ready = false;
    this.removeKeyListener(this);
    return infoTextField.getText();
    } // end getInfoBox

    I had the same problem on Solaris. Add a WindowListener to the dialog, then in the windowOpened() method (and possibly, just to be sure, in the windowIsClosing() method as well) set the focus to the component (the clue is: the dialog is visible).
    The code:
    public class GrabFocusWindowAdapter extends WindowAdapter
        private JComponent component;
        public GrabFocusWindowAdapter(JComponent component)
            this.component = component;
        public void windowOpened(WindowEvent event)
            if (component != null && component.isEnabled())
                component.requestFocus();
    }Use this adapter with the component to focus in the constructor.
    Kurta

Maybe you are looking for

  • How do I transfer voice memos from my iPhone to iTunes?

    How do I transfer voice memos from my iPhone5 to iTunes?

  • How do I continue a migration from iPhoto to Photos that was interrupted part way through?

    I began a VERY large migration (40k+ photos) from iPhoto (v9.6.1) to Photos on an external hard drive.  I have a MacBook Pro with Yosemite 10.10.3 that is connected to a network that has a Synology network drive.  The iPhoto library is on that drive

  • Crazy Things Happening

    I've been using the 'old versions' of this software for years to create simple web page designs. Plain old HTML pages from slices, with a few rollovers. Never any problems. Until I upgraded to CS2 with Dreamweaver 8. Now NOTHING works properly. Not o

  • IPhot erkennt DVD mit iPhoto libary nicht

    Habe eine iPhoto Libary auf DVD gebrannt. Wenn ich diese DVD nun einlege, kann ich sie zwar im Finder sehen, nicht aber in der "Quelle"-Box in iPhoto. Laut "iPhoto Hilfe" sollte diese hier jedoch ersichtlich und auswählbar sein. Kann mir da bitte jem

  • Lockbox is already created by mistake...

    hi all, i am doing enhancment in user exit for lockbox, so while doing teasting i run the transaction FLB2 and executed...now when i run other file then it shows error that " this lockbox already imported into bank data storage" now i want to test th