Making JFrame a parent of JDialog

I decided to start this post again because i was going a bit of the rails before. For now, i am keeping to my original code so i can see where i am going wrong. My JFrame class is my Title class. I have other buttons in this class but the one to concentrate on at the moment is my btnLogin which brings up my Login class, which is a Jdialog. Because the action event on this button was in an inner class, i couldnt make Title the direct parent. So i have made a few changes and made the action event call another class, so that hopefully i can make Title its parent. Here is the code for Title.
import java.awt.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.event.KeyListener;
import java.awt.event.*;
public class Title extends JFrame {
     public Title() {
        JPanel cp = new JPanel();
          cp.setLayout(new BorderLayout());
        Icon image = new ImageIcon("london.png");
          JLabel centerPanel1 = new JLabel(image);
        cp.add(centerPanel1, BorderLayout.CENTER);
          cp.add(createTitlePanel(), BorderLayout.NORTH);
          cp.add(createButtonPanel(), BorderLayout.SOUTH);
          setContentPane(cp);
          setTitle("Ner);
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          pack();
     private JPanel createButtonPanel() {
            JButton btnRegister = new JButton("REGISTER");
            JButton btnLogin = new JButton("LOGIN");
            JButton btnExit = new JButton("Exit");
            btnRegister.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    new Register();
            btnLogin.addActionListener(new LoginListener(this));
            btnExit.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                     cancel();
          JPanel panel = new JPanel();
          JPanel temp = new JPanel(new GridLayout(1,2, 5,5));
          temp.add(btnRegister, BorderLayout.LINE_START);
          temp.setPreferredSize(new Dimension(300, 40));
          temp.add(btnExit, BorderLayout.CENTER);
          temp.setPreferredSize(new Dimension(300, 40));
          temp.add(btnLogin, BorderLayout.LINE_END);
          temp.setPreferredSize(new Dimension(300, 40));
          panel.add(temp);
          return panel;
     private JPanel createTitlePanel()  {
          JLabel titleLabel = new JLabel("OFFICIAL RANKINGS");
          titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 48));
          titleLabel.setForeground(Color.black);
          JPanel titlePanel = new JPanel();
          titlePanel.setOpaque(false);
          titlePanel.add(titleLabel);     
          return titlePanel;
public void cancel(){
     this.dispose();
    public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                    new Title().setVisible(true);
class LoginListener implements ActionListener {
         JFrame jf;
         LoginListener(JFrame jf) {
              this.jf = jf;
         public void actionPerformed(ActionEvent evt) {
            new Login(jf);   
{code}
Now in my Login class, i have created a constructor which accepts a father as an arguement, so that Login can have a parent.  Here is the code to this class.
{code}
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.*;
public class Login extends JDialog implements ActionListener
ArrayList personsList;
PersonDAO pDAO;
JLabel userName, passWord;
JTextField userName1;
JPasswordField passWord1;
JButton jbnClear, jbnSubmit, jbnCancel;
String userName2, passWord2;
Container cPane;
public static void main(String args[]){
new Login();
public Login(JFrame father) {
super(father);
public Login()
userName2  = "";
passWord2   = "";
createGUI();
personsList = new ArrayList();
public void createGUI(){
cPane = getContentPane();
setLayout(new GridBagLayout());
//Arrange components on contentPane and set Action Listeners to each JButton
arrangeComponents();
setSize(210,170);
setTitle("Login");
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
public void arrangeComponents(){
userName = new JLabel("Username");
passWord = new JLabel("Password");
userName1   = new JTextField(20);
passWord1   = new JPasswordField(20);
jbnClear  = new JButton("Clear");
jbnSubmit = new JButton("Submit");
jbnCancel = new JButton("Cancel");
GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints();
gridBagConstraintsx01.gridx = 0;
gridBagConstraintsx01.gridy = 0;
gridBagConstraintsx01.insets = new Insets(5,5,5,5);
cPane.add(userName, gridBagConstraintsx01);
GridBagConstraints gridBagConstraintsx02 = new GridBagConstraints();
gridBagConstraintsx02.gridx = 1;
gridBagConstraintsx02.insets = new Insets(5,5,5,5);
gridBagConstraintsx02.gridy = 0;
gridBagConstraintsx02.gridwidth = 2;
gridBagConstraintsx02.fill = GridBagConstraints.BOTH;
cPane.add(userName1, gridBagConstraintsx02);
GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints();
gridBagConstraintsx03.gridx = 0;
gridBagConstraintsx03.insets = new Insets(5,5,5,5);
gridBagConstraintsx03.gridy = 1;
cPane.add(passWord, gridBagConstraintsx03);
GridBagConstraints gridBagConstraintsx04 = new GridBagConstraints();
gridBagConstraintsx04.gridx = 1;
gridBagConstraintsx04.insets = new Insets(5,5,5,5);
gridBagConstraintsx04.gridy = 1;
gridBagConstraintsx04.gridwidth = 2;
gridBagConstraintsx04.fill = GridBagConstraints.BOTH;
cPane.add(passWord1, gridBagConstraintsx04);
GridBagConstraints gridBagConstraintsx09 = new GridBagConstraints();
gridBagConstraintsx09.gridx = 0;
gridBagConstraintsx09.gridy = 4;
gridBagConstraintsx09.insets = new Insets(5,5,5,5);
cPane.add(jbnClear, gridBagConstraintsx09);
GridBagConstraints gridBagConstraintsx10 = new GridBagConstraints();
gridBagConstraintsx10.gridx = 1;
gridBagConstraintsx10.gridy = 4;
gridBagConstraintsx10.insets = new Insets(5,5,5,5);
cPane.add(jbnSubmit, gridBagConstraintsx10);
GridBagConstraints gridBagConstraintsx11 = new GridBagConstraints();
gridBagConstraintsx11.gridx = 1;
gridBagConstraintsx11.gridy = 5;
gridBagConstraintsx11.insets = new Insets(5,5,5,5);
cPane.add(jbnCancel, gridBagConstraintsx11);
jbnClear.addActionListener(this);
jbnSubmit.addActionListener(this);
jbnCancel.addActionListener(this);
public void actionPerformed (ActionEvent e){
if (e.getSource() == jbnClear){
clear();
else if (e.getSource() == jbnSubmit){               
Submit();
else if (e.getSource() == jbnCancel){               
cancel();
public void clear(){
userName1.setText("");
passWord1.setText("");
personsList.clear();
public void Submit(){
userName2=userName1.getText();
passWord2 = new String(passWord1.getPassword());
PersonInfo person = new PersonInfo(userName2, passWord2);
if(userName2.equals("") || passWord2.equals("")){
JOptionPane.showMessageDialog(null, "Please complete all fields.");
else
pDAO.loginPerson(person);
public void cancel(){
this.dispose();
{code}
Everything now compiles fine, and i get no runtime errors, but when i click the Login button on my Title page, nothing comes up.  So this is where i am at now.  Can anyone see my mistake?
cheers                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

A very simple example that shows concept without showing pretty well laid-out panels:
SimpleLoginMain.java: the main application that shows a login dialog on button press
import java.awt.Dimension;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class SimpleLoginMain extends JPanel
  private JTextField nameTF = new JTextField(10);
  private JTextField passwordTF = new JTextField(10);
  public SimpleLoginMain()
    setPreferredSize(new Dimension(400, 300)); // so it's bigger than the login pane
    // make textfields in main panel non-editable, so that only the login dialog can change these
    nameTF.setEditable(false);
    passwordTF.setEditable(false);
    add(nameTF);
    add(passwordTF);
    JButton loginBtn = new JButton("Login");
    add(loginBtn);
    loginBtn.addActionListener(new LoginListener());
  private class LoginListener implements ActionListener
    public void actionPerformed(ActionEvent arg0)
      SimpleLoginDlgPane dialogPane = new SimpleLoginDlgPane(); // create the login dialog JPanel
      // get parent JFrame as Window.  Will use this when we create a JDialog on the line below.
      Window window = SwingUtilities.getWindowAncestor(SimpleLoginMain.this);
      JDialog dialog = new JDialog(window, "Login", ModalityType.APPLICATION_MODAL);
      // add the login dialog JPanel to the JDialog's content pane
      dialog.getContentPane().add(dialogPane);
      dialog.pack();
      dialog.setLocationRelativeTo(null); // center everything
      dialog.setVisible(true);  // show as modal dialog box
      // This code only is called after dialog window has been closed     
      if (dialogPane.isAccept()) // if presses the dialog's accept button
        // here get the data from the dialog panel and place in the main application
        nameTF.setText(dialogPane.getName()); 
        passwordTF.setText(dialogPane.getPassword());
  // show everything in a thread-safe way
  private static void createAndShowUI()
    JFrame frame = new JFrame("Simple Login");
    frame.getContentPane().add(new SimpleLoginMain());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  public static void main(String[] args)
    java.awt.EventQueue.invokeLater(new Runnable()
      public void run()
        createAndShowUI();
}SimpleLoginDlgPane.java: The login JPanel that is shown in a JDialog
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class SimpleLoginDlgPane extends JPanel
  private static final String ACCEPT = "Accept"; // avoid silly spelling errors by using a constant
  private JTextField nameTF = new JTextField(10);
  private JPasswordField passwordPF = new JPasswordField(10);
  private boolean accept = false; // is set to true only if the acceptBtn has been pressed
  public SimpleLoginDlgPane()
    add(nameTF);
    add(passwordPF);
    JButton acceptBtn = new JButton(ACCEPT);
    add(acceptBtn);
    acceptBtn.addActionListener(new AcceptListener());
  public String getName()
    return nameTF.getText();
  public String getPassword()
    // I'm not sure of the correct/safe way to get this value
    return String.valueOf(passwordPF.getPassword());
  public boolean isAccept()
    return accept;
  private class AcceptListener implements ActionListener
    public void actionPerformed(ActionEvent e)
      if (e.getActionCommand().equals(ACCEPT))
        accept = true;
        // get the JDialog or JFrame that holds this JPanel
        Window window = SwingUtilities.getWindowAncestor(SimpleLoginDlgPane.this);
        window.dispose(); // and call dispose on it
}Edited by: Encephalopathic on Jun 14, 2008 9:20 AM

Similar Messages

  • How to access JFrame poppued up from JDialog

    Hi All,
    I have a JDialog(modal) with a Jbutton.If i click the button then a JFrame opens.Now as JDialog is setModal(true) im unable to acces the JFrame .Can u pls let mne know the way to handle this issue .I have a seroius issue with it.Kindly help me out....
    cheers,
    sharath

    Oh, and, dispose the non-modal db in button's listener method ...
    ... if it is your requirement ...

  • Bind Child JFrame to Parent JFrame

    Is there anyway of creating a JFrame that could have another JFrame attached to it? I don't so much mean an JInternalFrame, because what I need is a separate window (a properties window) that shows the user information, but doesn't register with the OS as a new window (i.e. place itself in the Windows taskbar). As far as I know, a JInternalFrame will actually be limited to the bounds of the JFrame containing it. I want mine to be a fully separate window, just bound to the parent window.
    Is it possible to do this by making both windows JInternalFrames and adding them both to a JDesktopPane???
    Thanks in advance for the help.

    What's with all those asterisks in your code? They're very distracting and prevent us from using your code.
    Anyway, the second window should be a JDialog, not a JFrame. I have to wonder why you call initComponents twice? Perhaps by doing so, the components displayed are not the ones with actionListeners added. It's hard to say not being able to run and test your code. Can you code Swing without using NetBeans code generation? If so, you should create a simpler example of this, one that we can run and test, and let us see exactly what is wrong. If you can't do this, then it would be worth your while to learn more Swing from the Sun/Oracle tutorials as this will serve you well in the long term.

  • Calling GUI jar from C++ and setting parent for JDialog

    Hi,
    i am calling a GUI jar from in C++ code using ShellExecuteEx API as follows.
    l_sei->cbSize=sizeof(SHELLEXECUTEINFO);
              l_sei->fMask = SEE_MASK_NOCLOSEPROCESS;
              l_sei->hwnd =l_hwndFound;          
              l_sei->lpVerb = "open";
              l_sei->lpFile = "java";     
              l_sei->lpParameters ="test.jar";
              l_sei->lpDirectory = NULL;
              l_sei->nShow = SW_HIDE;
              l_sei->hInstApp = NULL;
              ShellExecuteEx(l_sei);This GUI opens up from the parent application .
    The problem i am facing is the jar runs as an independent application. I want to set application as the parent window for my GUI.
    The frame is a JDialog. Can i set a parent for a JDialog? So that doing Alt+Tab would not open the GUI on any window other than the parent application.
    thanks.

    Well, you can certainly set a parent for a JDialog (an owner, anyway, since it isn't a "parent" in the GUI hierarchy)... but that won't necessarily make the windows task switch together.
    Now, the real problem is that the "parent" needs to be a Java Dialog or Frame object in the same JRE as the dialog, and in order to get what OS-specific task switching features can be provided by AWT, it needs to be set at the Dialog's creation. Since a JDialog does have a native peer at some level, (although I'm not sure if it actually would be a native dialog window), you might be able to use the Java Invocation API instead of ShellExecuteEx to set up the JAR, watch for the JDialog to be created, and then link its peer through native code... but I don't think there's any easy way to do what you want, since Java windows aren't even supposed to be aware of native ones.

  • Making JFrame Window Lose Focus to a Native Window

    How can i from within the same JFrame code or another class with the JFrame reference make JFrame lose focus to another native window on the desktop.
    Any tips

    In the core java API you can not make a native window take focus, you would have to use native code (JNI).
    The best you could do would be minimize the JFrame.

  • Making JFrame active

    I have a JFrame and I bring it toFront with native code because else it didn't work. But the JFrame is not active if the Programm which started my Application loses the Focus before my window is being displayed. I also tried the native C++ function CWnd::SetActiveWindow and other members of CWnd but the don't activate the window, although it's on top.
    Please help me!

    All these things make it just flashing in the taskbar.
    I now used the C++ function ::GetCursorPos(LPPOINT) to
    find out the mouse position via JNI and then I used
    java.awt.Robot to click on my JFrame and then move the mouse back.
    So all what I needed was JNI, no java method was invoked besides
    the java.awt.Robot's mouseMove/Press/Release. Everything
    is now done by JNI. First the window is brought to top:
    SetWindowPos(... topmost)
    SetWindowPos(... nottopmost)
    then
    GetCursorPos gets the mouse coordinates
    then the Robot clicks on the window
    Now I can have the JFrame on top and active whenever I want it to, but
    it is platformdependent and the Robot could raise AWTExceptions.
    So, If someone knows a working platformindependet solution that
    is "errorsave" please
    post it and you'll get all the remaining duke dollars.
    Thanks in advance!

  • Mouse Drag in JDialog produces Mouse Enter & Mouse Exit events in JFrame.

    Hi, all.
    Do I have a misconception here? When I drag the mouse in a modal JDialog, mouseEntered and mouseExited events are being delivered to JComponents in the parent JFrame that currently happens to be beneath that JDialog. I would not have expected any events to be delivered to any component not in the modal JDialog while that JDialog is displayed.
    I submitted this as a bug many months ago, and have heard nothing back from Sun, nor can I find anything similar to this in BugTraq.
    Here is sample code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    * This class demonstrates what I believe are TWO bugs in Mouse Event handling in Swing
    * 1.1.3_1, 1.1.3_2, 1.1.3_3, and 1.4.0.
    * 1) When a MODAL JDialog is being displayed, and the cursor is DRAGGED from the JDialog
    *    into and across the parent JFrame, Mouse Enter and Mouse Exit events are given to
    *    the parent JFrame and/or it's child components.  It is my belief that NO such events
    *    should be delivered, that modal dialogs should prevent ANY user interaction with any
    *    component NOT in the JDialog.  Am I crazy?
    *    You can reproduce this simply by running the main() method, then dragging the cursor
    *    from the JDialog into and across the JFrame.
    * 2) When a MODAL JDialog is being displayed, and the cursor is DRAGGED across the JDialog,
    *    Mouse Enter and Mouse Exit events are given to the parent JFrame and/or it's child
    *    components.  This is in addition to the problem described above.
    *    You can reproduce this by dismissing the initial JDialog displayed when the main()
    *    method starts up, clicking on the "Perform Action" button in the JFrame, then dragging
    *    the cursor around the displayed JDialog.
    * The Mouse Enter and Mouse Exit events are reported via System.err.
    public class DragTest
        extends JFrame
        public static void main(final String[] p_args)
            new DragTest();
        public DragTest()
            super("JFrame");
            WindowListener l_windowListener = new WindowAdapter() {
                public void windowClosing(final WindowEvent p_evt)
                    DragTest.this.dispose();
                public void windowClosed(final WindowEvent p_evt)
                    System.exit(0);
            MouseListener l_mouseListener = new MouseAdapter() {
                public void mouseEntered(final MouseEvent p_evt)
                    System.err.println(">>> Mouse Entered: " + ((Component)p_evt.getSource()).getName() );
                public void mouseExited(final MouseEvent p_evt)
                    System.err.println(">>> Mouse Exited: " + ((Component)p_evt.getSource()).getName() );
            JPanel l_panel1 = new JPanel();
            l_panel1.setLayout( new BorderLayout(50,50) );
            l_panel1.setName("JFrame Panel");
            l_panel1.addMouseListener(l_mouseListener);
            JButton l_button = null;
            l_button = new JButton("JFrame North Button");
            l_button.setName(l_button.getText());
            l_button.addMouseListener(l_mouseListener);
            l_panel1.add(l_button, BorderLayout.NORTH);
            l_button = new JButton("JFrame South Button");
            l_button.setName(l_button.getText());
            l_button.addMouseListener(l_mouseListener);
            l_panel1.add(l_button, BorderLayout.SOUTH);
            l_button = new JButton("JFrame East Button");
            l_button.setName(l_button.getText());
            l_button.addMouseListener(l_mouseListener);
            l_panel1.add(l_button, BorderLayout.EAST);
            l_button = new JButton("JFrame West Button");
            l_button.setName(l_button.getText());
            l_button.addMouseListener(l_mouseListener);
            l_panel1.add(l_button, BorderLayout.WEST);
            l_button = new JButton("JFrame Center Button");
            l_button.setName(l_button.getText());
            l_button.addMouseListener(l_mouseListener);
            l_panel1.add(l_button, BorderLayout.CENTER);
            JButton l_actionButton = l_button;
            Container l_contentPane = this.getContentPane();
            l_contentPane.setLayout( new BorderLayout() );
            l_contentPane.add(l_panel1, BorderLayout.NORTH);
            JPanel l_panel2 = new JPanel();
            l_panel2.setName("JDialog Panel");
            l_panel2.addMouseListener(l_mouseListener);
            l_panel2.setLayout( new BorderLayout(50,50) );
            l_panel2.add( new JButton("JDialog North Button"),  BorderLayout.NORTH  );
            l_panel2.add( new JButton("JDialog South Button"),  BorderLayout.SOUTH  );
            l_panel2.add( new JButton("JDialog East Button"),   BorderLayout.EAST   );
            l_panel2.add( new JButton("JDialog West Button"),   BorderLayout.WEST   );
            l_panel2.add( new JButton("JDialog Center Button"), BorderLayout.CENTER );
            final JDialog l_dialog = new JDialog(this, "JDialog", true);
            WindowListener l_windowListener2 = new WindowAdapter() {
                public void windowClosing(WindowEvent p_evt)
                    l_dialog.dispose();
            l_dialog.addWindowListener(l_windowListener2);
            l_dialog.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
            l_dialog.getContentPane().add(l_panel2, BorderLayout.CENTER);
            l_dialog.pack();
            Action l_action = new AbstractAction() {
                { putValue(Action.NAME, "Perform Action (open dialog)"); }
                public void actionPerformed(final ActionEvent p_evt)
                    l_dialog.setVisible(true);
            l_actionButton.setAction(l_action);
            this.addWindowListener(l_windowListener);
            this.pack();
            this.setLocation(100,100);
            this.setVisible(true);
            l_dialog.setVisible(true);
    }(Too bad blank lines are stripped, eh?)
    Thanks in advance for any insights you may be able to provide.
    ---Mark

    I guess we can think of this as one problem. When mouse dragged, JFrame also (Parent) receives events. If i understood correctly, what happens here is, Modal dialog creates its own event pump and Frame will be having its own. See the source code of Dialog's show() method. It uses an interface called Conditional to determine whether to block the events or yield it to parent pump.
    Here is the Conditional code and show method code from java.awt.dialog for reference
    package java.awt;
    * Conditional is used by the EventDispatchThread's message pumps to
    * determine if a given pump should continue to run, or should instead exit
    * and yield control to the parent pump.
    * @version 1.3 02/02/00
    * @author David Mendenhall
    interface Conditional {
        boolean evaluate();
    /////show method
        public void show() {
            if (!isModal()) {
                conditionalShow();
            } else {
                // Set this variable before calling conditionalShow(). That
                // way, if the Dialog is hidden right after being shown, we
                // won't mistakenly block this thread.
                keepBlocking = true;
                if (conditionalShow()) {
                    // We have two mechanisms for blocking: 1. If we're on the
                    // EventDispatchThread, start a new event pump. 2. If we're
                    // on any other thread, call wait() on the treelock.
                    if (Toolkit.getEventQueue().isDispatchThread()) {
                        EventDispatchThread dispatchThread =
                            (EventDispatchThread)Thread.currentThread();
                           * pump events, filter out input events for
                           * component not belong to our modal dialog.
                           * we already disabled other components in native code
                           * but because the event is posted from a different
                           * thread so it's possible that there are some events
                           * for other component already posted in the queue
                           * before we decide do modal show. 
                        dispatchThread.pumpEventsForHierarchy(new Conditional() {
                            public boolean evaluate() {
                                return keepBlocking && windowClosingException == null;
                        }, this);
                    } else {
                        synchronized (getTreeLock()) {
                            while (keepBlocking && windowClosingException == null) {
                                try {
                                    getTreeLock().wait();
                                } catch (InterruptedException e) {
                                    break;
                    if (windowClosingException != null) {
                        windowClosingException.fillInStackTrace();
                        throw windowClosingException;
        }I didn't get exactly what is happening but this may help to think further

  • Non-modal JDialog hides its JFrame "owner"

    I'm writing my first significant swing application. It has a JFrame that launches a JDialog. When constructing the JDialog, I have the JFrame as the owner and set it to be non-modal. The dialog is indeed non-modal, since it allows me to click on the JFrame and run it. However, if the two windows overlap, the JDialog is always on top, covering the JFrame, even if the JFrame has focus. This can make it difficult to effectively work with the JFrame while the JDialog is on the screen.
    There must be a simple solution to this, but I haven't discovered it yet. Any ideas?

    Thank you so much for your reply. I just confirmed that passing null to the JDialog does indeed allow the JFrame to overlay it. However, now if I minimize the JFrame, the JDialog stays up. I'd prefer that it go disappear with the JFrame. Is there a way to "have it both ways"? That is, Is there a way to make the JDialog go away when the JFrame is minimized, but still make it possible for the JFrame to overlay the JDialog?
    Thanks again for the original reply.
    TIA on this one, too!
    Tim

  • How to set a Japplet as parent for a JDialog ?

    Hi,
    I am using netbeans IDE 6.0 for swing development. I have a web application where i have main GUI as JApplet, In this I am calling a custom JDialog on a button click.
    Code for main GUI looks like,
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Demo extends JApplet implements ActionListener {
        JButton btn = new JButton();
        String msg;
        public void init(){
            add(btn);
            this.setBounds(200, 200, 200, 250);
            this.setVisible(true);
            btn.setText("Click");
            msg = "This is test message";
            btn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    MyDialog diag = new MyDialog(msg);
                    diag.setVisible(true);
         public void actionPerformed(ActionEvent arg0) {
    }The following code is for custom dialog. Here super(parent,modal) is commented as how don't know how to pass JApplet as container for JDialog.
    public class MyDialog extends javax.swing.JDialog {
        /** Creates new form MyDialog */
        public MyDialog(String msg) {
            //super(parent, modal);
            initComponents();
            jTextArea1.setText(msg);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            Jlbl = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
            jButton1 = new javax.swing.JButton();
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    closeDialog(evt);
            Jlbl.setText("Text");
            add(Jlbl, java.awt.BorderLayout.NORTH);
            jTextArea1.setColumns(20);
            jTextArea1.setRows(5);
            jScrollPane1.setViewportView(jTextArea1);
            add(jScrollPane1, java.awt.BorderLayout.CENTER);
            jButton1.setText("ok");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            add(jButton1, java.awt.BorderLayout.SOUTH);
            pack();
        /** Closes the dialog */
        private void closeDialog(java.awt.event.WindowEvent evt) {                           
            setVisible(false);
            dispose();
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                       
            setVisible(false);
            dispose();
        // Variables declaration - do not modify                   
        private javax.swing.JLabel Jlbl;
        private javax.swing.JButton jButton1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextArea jTextArea1;
        // End of variables declaration                 
    }My problem is that how can i set main window that is JApplet as parent to JDialog so that it should reside inside main window.
    Any suggestion would be helpfull.
    Thank you in advance.

    hi,
    I Got solution from following ;
    [Open a JDialog from an JApplet|http://forums.sun.com/thread.jspa?forumID=31&threadID=654054]
    But when I open the applet in browser and click button from applet to create JDialog, the dialog shown can be moved out side browser window (applet window). how is this happening ?
    Your suggestion would definitely help.
    Thank you

  • Change jFrame to be jDialog

    I wrote a big application using mostly jFrames as pop up screens to collect data. I only realized now I should have used jDialogs instead. Is there a way to convert the jFrames to jDialog instead of writing all new??

    question is - is there a way to convert a jFrame to be a jDialog?They are the same. You use either:
    JFrame frame = new JFrame();
    or
    JDialog dialog = new JDialog();
    They both use a content pane and you add components to the content pane the same way whether its a frame or a dialog.
    So your question doesn't make sense. You go through the code and change JFrame to JDialog. That is the simplest way.
    Of course it is not the best design as was stated in the first reply.

  • Own JDialog - works with java5, doesn't work with java6

    Hello,
    I'm working on map editor for a bigger project and I'm stuck with displaying my own JDialog (grrr...). I found out that problem occurs only with java6. See the screenshots below:
    java5
    http://student.agh.edu.pl/~kdzwinel/Projects/TrafficSim/MapEditor/good.jpg
    java6
    http://student.agh.edu.pl/~kdzwinel/Projects/TrafficSim/MapEditor/wrong.jpg
    And some implementation details:
    how do I create new dialog:
    NewMapDialog dialog = new NewMapDialog(this);
    dialog.setVisible(true);how dialog class looks like:
    public class NewMapDialog extends JDialog implements ActionListener, ChangeListener
         NewMapDialog(Main owner)
              super(owner,"New map",true);
              this.setAlwaysOnTop(true);
              this.setSize(200, 280);
              this.setResizable(false);
              this.setLocationRelativeTo(owner);
              makeLayout();
         private void makeLayout()     
              Container content = getContentPane();
              content.setLayout(new FlowLayout());
    //(...) <- add stuff
    }That is so simple that I'm really confused. I will appreciate some help.
    Regards,
    Konrad
    Edited by: kdzwinel on Feb 5, 2008 6:23 PM

    kdzwinel wrote:
    Hm, creating my applications I extend JFrame, JPanel, JLabel all the time, what is wrong with extending JDialog?In this case your class contained two methods that were already defined to mean something completely different in the class you derived from. That's just one example of what can go wrong when you use inheritance. Had you used composition rather than inheritance (i.e. your class contained a JDialog rather than being a JDialog) this problem would never have happened.
    Such an extension was quite natural for me to use because I was looking for this dialog to be modal. And I guess making JFrame modal is not so trivial.
    You can make a modal JDialog without extending JDialog, so that's not a problem.
    BTW, funny thing is that this 'mistaken' code worked just fine with java5 - I was confused by this fact so my first guess was that I messed something up with panes/layouts.Another reason you should be careful with inheritance: your program may break from implementation changes in the library code you are using and extending. Maybe Java 5 does not use those two methods when it "draws the dialog". Again, had you been using composition your program would not have been affected.
    If you can, get your hands on a copy of "Effective Java" by Joshua Bloch, and read chapter 14 "Favor composition over inheritance". He explains this much better than I can.

  • Effect of super() in JDialog constructor on focusability/modality

    Hello again,
    this is a JFrame which calls a JDialog which calls a JDialog.
    Using super(...) in the constructor of SecondDialog makes this dialog
    unfocusable as long as FirstDialog is shown. Without super(...) one can freely
    move between the dialogs.
    Can somebody exlain what "super" does to produce this difference?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SuperConstructor extends JFrame {
      public SuperConstructor() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(300,300);
        setTitle("Super constructor");
        Container cp= getContentPane();
        JButton b= new JButton("Show dialog");
        b.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
         new FirstDialog(SuperConstructor.this);
        cp.add(b, BorderLayout.SOUTH);
        setVisible(true);
      public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
         new SuperConstructor();
      class FirstDialog extends JDialog {
        public FirstDialog(final Frame parent) {
          super(parent, "FirstDialog");
          setSize(200,200);
          setLocationRelativeTo(parent);
          setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);
          JButton bNext= new JButton("Show next dialog");
          bNext.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
           new SecondDialog(parent, false);
          add(bNext, BorderLayout.SOUTH);
          setVisible(true);
      int i;
      class SecondDialog extends JDialog {
        public SecondDialog(Frame parent, boolean modal) {
          super(parent); // Makes this dialog unfocusable as long as FirstDialog is 
    shown
          setSize(200,200);
          setLocation(300,50);
          setModal(modal);
          setTitle("SecondDialog "+(++i));
          JButton bClose= new JButton("Close");
          bClose.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
           dispose();
          add(bClose, BorderLayout.SOUTH);
          setVisible(true);
    }

    nice day,
    there are three areas of get potential problem
    1/ FirstDialog helt pernament MODALITY, SecondDialog to have to same ...
    2/ there isn't something about change Window focus (if Parent inside of EDT, then you alyway lost focus, meaning SecondDialog)
    3/ constructor super inside class doesn't works, block move focus to the SecondDialog (and nonModal)
    ... but
    4/ here is second coins_side [http://forums.sun.com/thread.jspa?messageID=11020377#11020377]
    5/ in this form is my example returns similair result, isn't possible setWindow focus for visible JDialog (sure, remove Extend JDialog and create separate constuctor for JDialog, solve that)
    6/ maybe I'm wrong
    package JDialog;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    * Parent Modal Dialog. When in modal mode, this dialog
    * will block inputs to the "parent Window" but will
    * allow events to other components
    * @see javax.swing.JDialog
    public class PMDialog extends JDialog {
        private static final long serialVersionUID = 1L;
        private boolean modal = false;
        private WindowAdapter parentWindowListener;
        private Window owner;
        private JFrame blockedFrame = new JFrame("No blocked frame");
        private JFrame noBlockedFrame = new JFrame("Blocked Frame");
        public PMDialog() {
            noBlockedFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            noBlockedFrame.getContentPane().add(new JButton(new AbstractAction("Test button") {
                private static final long serialVersionUID = 1L;
                @Override
                public void actionPerformed(ActionEvent evt) {
                    System.out.println("Non blocked button pushed");
                    /*if (blockedFrame.isVisible()) {
                        noBlockedFrame.setVisible(false);
                    } else {
                        blockedFrame.setVisible(true);
                    noBlockedFrame.setVisible(true);
                    blockedFrame.setVisible(true);
            noBlockedFrame.setSize(200, 200);
            noBlockedFrame.setVisible(true);
            blockedFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
            blockedFrame.getContentPane().add(new JButton(new AbstractAction("Test Button") {
                private static final long serialVersionUID = 1L;
                @Override
                public void actionPerformed(ActionEvent evt) {
                    final PMDialog pmd = new PMDialog(blockedFrame, "Partial Modal Dialog", true);
                    pmd.setSize(200, 100);
                    pmd.setLocationRelativeTo(blockedFrame);
                    pmd.getContentPane().add(new JButton(new AbstractAction("Test button") {
                        private static final long serialVersionUID = 1L;
                        @Override
                        public void actionPerformed(ActionEvent evt) {
                            System.out.println("Blocked button pushed");
                            pmd.setVisible(false);
                            blockedFrame.setVisible(false);
                            noBlockedFrame.setVisible(true);
                    pmd.setDefaultCloseOperation(PMDialog.DISPOSE_ON_CLOSE);
                    pmd.setVisible(true);
                    System.out.println("Returned from Dialog");
            blockedFrame.setSize(200, 200);
            blockedFrame.setLocation(300, 0);
            blockedFrame.setVisible(false);
        public PMDialog(JDialog parent, String title, boolean isModal) {
            super(parent, title, false);
            initDialog(parent, title, isModal);
        public PMDialog(JFrame parent, String title, boolean isModal) {
            super(parent, title, false);
            initDialog(parent, title, isModal);
        private void initDialog(Window parent, String title, boolean isModal) {
            owner = parent;
            modal = isModal;
            parentWindowListener = new WindowAdapter() {
                @Override
                public void windowActivated(WindowEvent e) {
                    if (isVisible()) {
                        System.out.println("Dialog.getFocusBack()");
                        getFocusBack();
        private void getFocusBack() {
            Toolkit.getDefaultToolkit().beep();
            super.setVisible(false);
            super.pack();
            super.setLocationRelativeTo(owner);
            super.setVisible(true);
            //super.toFront();
        @Override
        public void dispose() {
            owner.setEnabled(true);
            owner.setFocusableWindowState(true);
            super.dispose();
        @Override
        @SuppressWarnings("deprecation")
        public void hide() {
            owner.setEnabled(true);
            owner.setFocusableWindowState(true);
            super.hide();
        @Override
        public void setVisible(boolean visible) {
            boolean blockParent = (visible && modal);
            owner.setEnabled(!blockParent);
            owner.setFocusableWindowState(!blockParent);
            super.setVisible(visible);
            if (blockParent) {
                System.out.println("Adding listener to parent ...");
                owner.addWindowListener(parentWindowListener);
                try {
                    if (SwingUtilities.isEventDispatchThread()) {
                        System.out.println("EventDispatchThread");
                        EventQueue theQueue = getToolkit().getSystemEventQueue();
                        while (isVisible()) {
                            AWTEvent event = theQueue.getNextEvent();
                            Object src = event.getSource();
                            if (event instanceof ActiveEvent) {
                                ((ActiveEvent) event).dispatch();
                            } else if (src instanceof Component) {
                                ((Component) src).dispatchEvent(event);
                    } else {
                        System.out.println("OUTSIDE EventDispatchThread");
                        synchronized (getTreeLock()) {
                            while (isVisible()) {
                                try {
                                    getTreeLock().wait();
                                } catch (InterruptedException e) {
                                    break;
                } catch (Exception ex) {
                    ex.printStackTrace();
                    System.out.println("Error from EDT ... : " + ex);
            } else {
                System.out.println("Removing listener from parent ...");
                owner.removeWindowListener(parentWindowListener);
                owner.setEnabled(true);
                owner.setFocusableWindowState(true);
        @Override
        public void setModal(boolean modal) {
            this.modal = modal;
        public static void main(String args[]) {
            PMDialog pMDialog = new PMDialog();
    }

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

  • Regarding listener on component in JFrame!!!!!

    I am making JFrame having a JPanel added to its North
    now in this JPanel i have JButton .
    Now i m adding key listener to the JPanel
    the problem is when i put focus on button and press any key
    the key pressed method is not called
    however i read that if button is not registered with listener then the event is dispacthed to its upper hierarchy and so looks for panel to be listened but here nothing is happened
    why????????????????
    i am confused
    let me know whats the problem
    thanks in advance
    upasna

    Hi,
    In the new (not very new) event model the events is not propagated
    to its parents. So to solve your problem simply add a listener to you Button
    instead to your Panel
    Hope this help

  • Frame icon for JDialog

    Hi all,
    I have a JDialog which is passed an instance of JFrame as parent component in its constructor.
    The problem is that if i set the dialog as non resizable, the icon that appears in title bar(top left corner) goes.
    It is visible only when the dialog is kept resizable.
    Further the dialog is a modal dialog.
    Please help,
    Regards,
    vikalp setya
    [email protected]

    To work around the bug, add this to your JDialog
          addComponentListener(new ComponentAdapter() {               // need this to prevent window resizing
             public void componentResized(ComponentEvent e) {          // can't use setResizable(false) because then the icon in the title bar is gone
                if (size==null) return;  // must be set elsewhere when JDialog is visible
                setSize(size);  // restore the original size of JDialog
          });;o)
    V.V.

Maybe you are looking for

  • I canu00B4t build a DC that share only classes

    Hi forum:    I want to make a Sharing Reference between two Web Dynpro DC, to share only classes of one project to another. I make the next steps: 1) i created one DC1 project 2) i put a classes that i want to share into the folder  src/packages.3) i

  • Screen Share issue!

    Screen share works when i connect from my mac mini to my macbook, but the other way around, i can only access my file on my mac mini from my macbook, there is no option for screen share, even though i have screen share activated on both machines. vnc

  • Find table with budjet records

    At which table can i find budjet records that was created at t.code FR04 and FR50?

  • LG Spectrum doesn't hold charge after latest update

    About 2 weeks ago my phone automatically updated overnight.  I was surprised the next morning to find a different look on my phone and having to change things back to my settings.  Since then, my phone won't hold a charge for more than 5-6 hours.  It

  • Fixing a NXT LabVIEW Toolkit compile/load problem

    I bought myself a Lego NXT Mindstorms to play with. I'm using the LabVIEW 8.5.1 from the FIRST Robotics competition and I downloaded the NXT Toolkit for Labview. I did a mass compile on the toolkit (like the getting started said to) and did the excer