JFrame references in JDialog constructors.

If you have a single JFrame that houses your GUI and have Dialogs scattered through out your application, what is the best way to make create each dialog with a reference to that one master JFrame.
Currently, I am passing the JFrame reference all over the place. Practically every constructor now has a JFrame as part of its argument list. The object graph is fairly deep, because I have screens that open sub screens, I have panels that are resused among screens; I have table editor that popup messages; etc; etc. It would be so nice if I didn't have to pass this JFrame reference to ever thing I created.
I could use the Singleton pattern, but I heard this was a bad idea.
Can someone give me some guidance, and perhaps an example?
Thanks.

When I say "Dialogs scattered throughout the application", I'm trying to say that I have one JFrame with a main method. When launched through the main method, the primary view is loaded. From there, the user can click in different areas to launch "detail" screens. Within these "detail" screens, I have fields that need validation. These validations require a lot of messages to be generated for the user. To do this, I use JOptionPane. JOptionPane requires a JFrame. (Technically, the JFrame is optional, but without it you run into other issues.)
For example, here's some I have plugged into one of my JTable Editors:
  public boolean stopCellEditing(){
    String startTime = (String)_table.getModel().getValueAt(_row, _col - 1);
    if(startTime == null || "".equals(startTime)){
      return super.stopCellEditing();
    Float start = getTimeAsDecimal(startTime);
    Float end = getTimeAsDecimal(_editor.getText());
    if(end < start){
      Object response = Message.showMessageDialog(_frame, "MESSAGE", JOptionPane.INFORMATION_MESSAGE, "End must be after start");
      _editor.setBackground(Color.RED);
      _editor.setForeground(Color.WHITE);
     _editor.requestFocus();
      return false;
    return super.stopCellEditing();
  }You will notice that I have "_frame" as a variable in my showMessageDialog. I have to pass this "_frame" object from the very top, pass it into the JDialog that houses the JTable, then pass it into the editor that has this message. Now, this is only three layers. There are occasions where I have to pass it even more layers.
Is this bad architecture? Can it be done better or more efficiently?
Why is it bad to have a singleton JFrame object? How is everyone else doing it?
Thanks.
Edited by: Kazan on Jan 21, 2009 2:11 PM

Similar Messages

  • JDialog constructor with Window

    Hi all,
    I have a class that gives at any moment the active window of my application. This window is either a Frame or a JDialog, it depends on the context.
    Thus I thought it would be possible to construct JDialogs without giving the owner parameter . The idea was to write something like
    class MyJDialog extends JDialog {
    public MyJDialog() {
    super(WindowsManager.getActiveWindow());
    but that does not work since the JDialog constructor takes either a Frame or a Dialog (and not a Window).
    The pb is I cannot test whether my window actually is a dialog or a frame and then use one of the existing JDialog constructors, because I can't execute code before calling super(...).
    Another idea that did not compile was
    MyJDialog() {
    super(WindowsManager.getActiveWindow() instanceof Frame?(Frame) WindowsManager.getActiveWindow():(Dialog)WindowsManager.getActiveWindow() );
    Any (other) idea ?

    What about a static block that checks for the current window...(not sure that it will work)
    public class YourClassName {
    public static JDialog createDialog(Window parentWindow) {
          JFrame parentFrame = null;
          JDialog parentDialog = null;
          if (parentWindow instanceof JDialog) {
             parentDialog = (JDialog) parentWindow;
             result = new MyDialog(parentDialog);
          } else {
             parentFrame = (JFrame) parentWindow;
             result = new MyDialog(parentFrame);
          return result;
    class MyDialog extends JDialog {
       public MyDialog(JFrame frame) {
          super(frame);
       public MyDialog(JDialog dialog) {
          super(dialog);
    }

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

  • Hiding/showing JFrame with active JDialog

    Hi,
    I have a problem with hiding and re-showing a JFrame that contains an active JDialog.
    I have a JFrame (named operatorFrame) that holds the main application and a JFrame that I use for showing a screensaver. When the screensaver has to be shown I perform a hide() of the operatorFrame and a show() of the screensaver frame.
    These actions are done in a Runnable that is called through SwingUtilities.invokeAndWait(). Now when the operatorFrame contained an opened JDialog and the screensaver started, when closing the screensaver the operatorFrame.show() method is called and there it stops. The instruction that follows the show() is never reached.
    Does anybody have any ideas?
    Thanks,
    Taaje

    I understand that but then why does it work when I run the same code in Windows (the normal environment is Red Hat Linux)?
    I just found out that it works when running it under Windows.

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

  • To close JFrame over a JDialog

    Hi,
    I am facing a slight problem. Say I have a code like under
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class abc extends JDialog implements ActionListener
         JPanel jp1 = new JPanel();
         JButton ok1 = new JButton("OK");
         public abc()
              this.getContentPane().setLayout(new BorderLayout());
              this.getContentPane().add(jp1,BorderLayout.CENTER);
              jp1.add(ok1);
              ok1.addActionListener(this);
              ok1.setActionCommand("ok1");
         public void actionPerformed(ActionEvent e)
              if (e.getActionCommand().equals("ok"))
                   System.out.println("Inside action performed method");
              else if (e.getActionCommand().equals("ok1"))
              JFrame j1 = new JFrame();
              JPanel jp2 = new JPanel();
              JButton btn1 = new JButton("OK");
              j1.getContentPane().add(jp2);
              jp2.add(btn1);     
              btn1.addActionListener(this);
              btn1.setActionCommand("ok");
              j1.show();
              j1.pack();
              j1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public static void main(String args[])
              abc ABC = new abc();
              ABC.show();
              ABC.pack();
    Now here in this code the line
    j1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    closes the application itself. What I want is only the JFrame closes while the main Dialog stills stays in context.
    Can someone help with me how I can achieve the same.
    Regards.
    Anand

    There is a dialog it has a OK button. When I click the OK button a frame opens with another OK1 button in it.
    Now if I click the "x" sign of the frame it should be disposed without doing anything. frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)But if I click the OK1 button then also the frame should be disposed but
    after doing something other processing corresponding to the OK1 button.
    OK1.addActionListener( new ActionListener() {
        public void actionPerformed(ActionEvent e) {
              // do processing
             frame.setVisible(false);
             // add this if you want to remove the frame from memory and recreate it when it needs to be opened
             frame.dispose();
    })>
    And within all this the parent(JDialog) and the child(JFrame) should be modal.A JFrame unfortunately cannot be modal, so you shd use a JDialog instead.
    ICE

  • Unable to create FXMLLoader controller reference: 'no suitable constructor'

    Greetings,
    I am in my first couple of days experimenting with JavaFX.
    I am trying to create a reference to my controller class from within my application start routine. All the posts that I have seen on this call for code such as the following:
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("MyFXML.fxml")); But in my NetBeans IDE editor this code signals the error 'no suitable constructor found for FXMLLoader(java.net.URL)'
    The FXMLLoader Class documentation clearly includes a FXMLLoader(java.net.URL) constructor. However, when I navigate to the source code from NetBeans, this constructor doesn't show: the only options are FXMLLoader() and FXMLLoader(Charset arg0).
    I am using NetBeans 7.1.2 ee version. I was using JavaFX 2.0, then downloaded the JavaFX 2.2 SDK (beta) to see if this would make a difference -- it hasn't.
    Any ideas would be much appreciated.

    Hi,
    My guess would be that NetBeans is still picking up the JavaFX 2.0 jars instead of JavaFX 2.2
    I would suggest playing with your project's properties: look at the library dependencies, and at the platform.
    If it's using a Default_JavaFX_Platform then check where it picks up JavaFX (click on "manage platform" and look in the JavaFX tab).
    Sometimes NetBeans is confused and will pick up the SDK 2.2 with the runtime 2.0 - so really check all the paths!
    Hopes this helps,
    -- daniel
    Edited by: daniel on Jun 13, 2012 6:18 AM

  • Create Requester ABCS without Reference using Service Constructor

    Hello,
    we using Service Constructor to create Requester ABCS. We disable the checkbox for CAVS and References, but the WSDL of EBS is as reference in Project and binding didn't bind to oramds. Another point is, that we disable ErrorHandling, but in composite and bpel is an external reference to AIAAsyncErrorHandling.
    Here are some screenshots:
    [Default Target Service Options|http://dl.dropbox.com/u/4274798/AIA-EAP/ServiceConstructor/SC_TargetServiceOptions-Enable.png]
    [Disable Checkboxes|http://dl.dropbox.com/u/4274798/AIA-EAP/ServiceConstructor/SC_TargetServiceOptions-Disable.png]
    [Reopen after editing|http://dl.dropbox.com/u/4274798/AIA-EAP/ServiceConstructor/SC_TargetServiceOptions-AfterConfirm.png]
    [Disable Error Handling|http://dl.dropbox.com/u/4274798/AIA-EAP/ServiceConstructor/SC_AddErrorHandling.png]
    Is it a bug in service constructor or did we misunderstanding the checkboxes?
    Marcel

    Bug 9431667 is logged for issue where error handling was unchecked, but it is still being defined.

  • Btn in JFrame to Open JDialog

    Hi Guys
    In NetBeans GUI Builder I have created and designed a MainGUI (JFrame Form) that has some buttons. I also went ahead and created and designed a SubGUI (JDialog Form).
    What do I need to do to link MainGUI to SubGUI through the press of a button ????
    I have added the ActionPerformed / ActionEvent method to the button, and inside that I have tried:
    SubGUI.setVisible(true);but it doesn't work !!
    I would greatly appreciate any help.
    Thank You.

    Here is the other bit that I think might be relevant:
    private void starterBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
            StarterDialog.setVisible(true);
        private void maincourseBtnActionPerformed(java.awt.event.ActionEvent evt) {                                             
            MainCourseDialog.setVisible(true);
        private void dessertBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
            DessertDialog.setVisible(true);
        private void adminBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
            AdminDialog.setVisible(true);
        private void starterListMouseClicked(java.awt.event.MouseEvent evt) {                                        
            Starter selectedStarter = (Starter)starterList.getSelectedValue();
            if (selectedStarter != null)
                populateSDialog(selectedStarter);
        private void sOKBtnActionPerformed(java.awt.event.ActionEvent evt) {                                      
            // TODO add your handling code here:
        private void sCancelBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
            this.dispose();
        private void maincourseListMouseClicked(java.awt.event.MouseEvent evt) {                                           
            MainCourse selectedMC = (MainCourse)maincourseList.getSelectedValue();
            if (selectedMC != null)
                populateMCDialog(selectedMC);
        private void mcOKBtnActionPerformed(java.awt.event.ActionEvent evt) {                                       
            // TODO add your handling code here:
        private void mcCancelBtnActionPerformed(java.awt.event.ActionEvent evt) {                                           
            // TODO add your handling code here:
        private void dessertListMouseClicked(java.awt.event.MouseEvent evt) {                                        
            Dessert selectedDessert = (Dessert)dessertList.getSelectedValue();
            if (selectedDessert != null)
                populateDDialog(selectedDessert);
        private void dOKBtnActionPerformed(java.awt.event.ActionEvent evt) {                                      
            // TODO add your handling code here:
        private void dCancelBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
            // TODO add your handling code here:
        private void populateSDialog(Starter s1)
            sNameJLi.setText(s1.getName());
            sCalsJLi.setText(String.valueOf(s1.getCalories()));
            sDescTA.setText(s1.getDescription());
            sPriceJLi.setText(String.valueOf(s1.getPrice()));
        private void populateMCDialog(MainCourse mc1)
            mcNameJLi.setText(mc1.getName());
            mcCalsJLi.setText(String.valueOf(mc1.getCalories()));
            mcDescTA.setText(mc1.getDescription());
            mcPriceJLi.setText(String.valueOf(mc1.getPrice()));
        private void populateDDialog(Dessert d1)
            dNameJLi.setText(d1.getName());
            dCalsJLi.setText(String.valueOf(d1.getCalories()));
            dDescTA.setText(d1.getDescription());
            dPriceJLi.setText(String.valueOf(d1.getPrice()));
        * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MainGUI().setVisible(true);
        }

  • Problem with JFrame, JInternalFrame and JDialog

    problem solved..sorry

    I have just found this post:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=302473
    And the first way seems to be the only way to solve the problem... :(
    Now the question is, does it exist a way to refresh a JFrame after that I have uset setVisible(true)?
    If it does exist I could have something like this:
    setVisible(true)
    new panel(getInsets(););
    contpan.add(panel);
    REFRESH();

  • Make jFrame wait for jDialog to finish

    I am making a project in Netbeans i have a main Frame and some Dialog windows that open up if you press some buttons.
    when one window opens i want the main Frame script to pause and wait for it to complete.
    i have tried 3 different ways:
    questionDialog.setVisible(true);
    while (questionDialog.isVisible()) {
        try {
            Thread.sleep(200);
        } catch (Exception e) {
    } but that shows the frame of the dialog box but never loads the inside and the whole application freezes.
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            questionDialog.setVisible(true);
    while (questionDialog.isVisible()) {
        try {
            Thread.sleep(200);
        } catch (Exception e) {
    }that loaded my Dialog box but the script never waits for it to close i assume it is because it waits until "later" to show the dialog box and in that time it skips the while loop.
    Thread t = new Thread(new Runnable() {
        public void run() {
            questionDialog.setVisible(true);
            while (questionDialog.isVisible()) {
                try {
                    Thread.sleep(200);
                } catch (Exception e) {
    t.start();
    System.out.println("Dialog started");
    System.out.println(questionDialog.isVisible());
    try {
        t.join();
    } catch (Exception e) {
    }but that had the same result as the first code it waited but never showed the dialog.
    where am i going wrong how should i go about this?
    Scott.
    EDIT:
    by finish i mean become not Visible. so isVisible() will return false
    Edited by: ratcateme on Nov 20, 2008 3:02 PM

    You don't have to do anything to do that
    questionDialog.setVisible(true), this method will block the thread, it would't keep going until the questionDialog is unvisible, this is the mistake of the way 1 and way 3.
    and the way 2: the while block will be execute before the questionDialog.setVisible(true) is execute, so questionDialog.isVisible() will return false
    my en is very poor, good luck!

  • Need help in Simple Java JDialog...

    have 3 classes..
    One class extend JFrame
    One class extend JPanel
    One class extend JDialog
    My JFrame is like my Main Frame...
    I have my JPanel that is always changing in my JFrame..
    How do i pass the JFrame into my JDialog constructor???
    (btw, is upon one of my JPanel click button, my JDialog appears)
    Thanks.

    have 3 classes..
    One class extend JFrame
    One class extend JPanel
    One class extend JDialog
    My JFrame is like my Main Frame...
    I have my JPanel that is always changing in my
    JFrame..
    How do i pass the JFrame into my JDialog
    constructor???
    (btw, is upon one of my JPanel click button, my
    JDialog appears)
    Thanks.You can pass the reference of JFrame in JDialog constructor as below:
    1) JDialog dialog = new JDialog(ClassName.this, "Title', true);
    where ClassName is the name of class that extends the JFrame. Thus you can capture reference of the parent.
    2) You can also get reference of JFrame by invoking method on your panel as:
    Container parent = jPanel.getParent();
    JDialog dialog = new JDialog(parent , "Title', true);
    where jPanel is instance of your JPanel.
    Post whether u need anything else.

  • 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

  • JDialog on top of full screen JFrame disappears

    I have a problem with a JDialog on top of a full screen JFrame, namely the JDialog kind of disappears when displayed (it bleeds through). I use JRE 1.6.0_03 on Windows. This does not happen under the same version on Linux. I'm attaching the code below.
    Test.java:
    import java.awt.GraphicsDevice;
    import java.awt.GraphicsEnvironment;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    public class Test extends JFrame {
         public Test() {
              final Test frame = this;
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              JButton button = new JButton("Open dialog");
              button.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent arg0) {
                        new TestDialog(frame);
              add(button);
              if (!isDisplayable()) {
                   setUndecorated(true);
              pack();
              setVisible(true);
         private static void createAndShowGui() {
              GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
              gd.setFullScreenWindow(new Test());
         public static void main(String[] args) throws Exception {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGui();
    }And TestDialog.java:
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    public class TestDialog extends JDialog {
         public TestDialog(JFrame frame) {
              super(frame);
              add(new JTextField("test"));
              setModal(true);
              pack();
              setVisible(true);
    }Any ideas why this is happening and how can I solve it? Thanks.

    I dont know if it works for you but, changing the createAndShowGui function
    (and so changing the way we make it fullscreen) as:
    private static void createAndShowGui() {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Test testFrame = new Test();
    testFrame .setBounds(0,0,screenSize.width, screenSize.height);
    }worked for me.
    (java.awt.Dimension and java.awt.Toolkit must be imported for this by the way.)
    I tried also decreasing the hardware acceleration and it worked, too.
    Edited by: Kaan_Ceylan on Nov 16, 2008 5:33 PM

  • ActionListener not working with JFrame

    Hi,
    I've just rehashed an old bit of code to work with a new application but for some reason the JButton ActionListeners aren't working. However if I extend JDialog they work ok. The current code for JDialog is:-
    * File:     GUI.java
    * @author           ODL 3xx Distributed Systems - Team x
    * @description      This class provides a means for the user to
    *                    interact with file server.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    public class GUI extends JDialog implements ActionListener, ApplicationConstants {
        private JLabel label1, label2, label3, label4, label5;
        private JTextField field1, field2, field3, field4, field5;
        private JButton button1, button2, button3, button4, button5;
        private Container container;
        private Message sendFile;
        private String id;
        private String defaultText = "Enter file name here";
        private ClientForGUI client;
        private long timeStart, timeEnd;
        public GUI(JFrame frame) {
            super(frame, "File Server Actions", true);
            client = new ClientForGUI(this);
            try{
                   InetAddress addr = InetAddress.getLocalHost();
                   id = addr.getHostName() + Long.toString((new java.util.Date()).getTime());
                   if(client.connectToServer())
                   initGUI();
                   else{
                        JOptionPane.showMessageDialog(this, "Unable to connect to server", "Error", JOptionPane.WARNING_MESSAGE);
                        System.exit(0);
              catch(UnknownHostException uhe){
                   System.out.println("Unknown Host Exception");
            initGUI();
         * Create the GUI
        private void initGUI() {
            container = this.getContentPane();
            container.setLayout(null);
            label1 = new JLabel("Upload File");
            label2 = new JLabel("Rename File");
            label3 = new JLabel("Delete File");
            label4 = new JLabel("Create File");
            label5 = new JLabel("Download File");
            field1 = new JTextField();
            field2 = new JTextField();
            field3 = new JTextField();
            field4 = new JTextField();
            field5 = new JTextField();
            button1 = new JButton("Upload");
            button2 = new JButton("Rename");
            button3 = new JButton("Delete");
            button4 = new JButton("Create");
            button5 = new JButton("Download");
            label1.setBounds(10,10,80,20);
            label2.setBounds(10,40,80,20);
            label3.setBounds(10,70,80,20);
            label4.setBounds(10,100,80,20);
            label5.setBounds(10,130,80,20);
            field1.setBounds(100,40,200,20);
            field1.setText("Old name");
            field2.setBounds(310,40,200,20);
            field2.setText("New name");
            field3.setBounds(100,70,410,20);
            field3.setText(defaultText);
            field4.setBounds(100,100,410,20);
            field4.setText(defaultText);
            field5.setBounds(100,130,410,20);
            field5.setText(defaultText);
            button1.setBounds(100,10,100,20);
            button1.addActionListener(this);
            button2.setBounds(520,40,100,20);
            button2.addActionListener(this);
            button3.setBounds(520,70,100,20);
            button3.addActionListener(this);
            button4.setBounds(520,100,100,20);
            button4.addActionListener(this);
            button5.setBounds(520,130,100,20);
            button5.addActionListener(this);
            container.add(label1);
            container.add(button1);
            container.add(label2);
            container.add(field1);
            container.add(field2);
            container.add(button2);
            container.add(label3);
            container.add(field3);
            container.add(button3);
            container.add(label4);
            container.add(field4);
            container.add(button4);
            container.add(label5);
            container.add(field5);
            container.add(button5);
            setSize(640,200);
            setResizable(false);
            //Centre on the screen
            Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
              int x = (int) ((d.getWidth() - getWidth()) / 2);
              int y = (int) ((d.getHeight() - getHeight()) / 2);
              setLocation(x,y);
            setVisible(true);
        private void sendMessageToServer(Message message){
             message.setId(id);
             timeStart = new java.util.Date().getTime();
             try{
                  client.sendMessageToServer(message);
             catch(IOException ioe){
                  System.out.println("Unable to send message to server");
          * Perform some action based on user interaction
          * @param ae - ActionEvent
        public void actionPerformed(ActionEvent e){
            Object o = e.getSource();
            String name;
            if(o == button1){
                 try{
                        JFileChooser fc = new JFileChooser();
                       fc.setVisible(true);
                      //return value is what the user presses in the open File dialog
                      int returnVal = fc.showOpenDialog(null);
                      //if they choose OK
                      if (returnVal == JFileChooser.APPROVE_OPTION) {
                             //file now references the selected
                             File file = fc.getSelectedFile();
                             //create a FileInputStream from file location
                             FileInputStream fis = new FileInputStream(file);
                             // Create the byte array to hold the data, the same size as the file
                             byte [] fileBytes = new byte[(int)file.length()];
                              // Read in the bytes from the file into the byte array
                              int offset = 0;
                              int numRead = 0;
                              while (offset < fileBytes.length &&
                             (numRead=fis.read(fileBytes, offset, fileBytes.length-offset)) >=
                             0) {
                                  offset += numRead;
                             // Ensure all the bytes have been read in
                             if (offset < fileBytes.length) {
                                  throw new IOException("Could not completely read file "+file.getName());
                             fis.close();
                             sendFile = new Message(SEND_FILE, fileBytes);
                             sendFile.setId(id);
                             sendFile.setFileName(file.getName());
                             byte [] myarray = ConvertData.messageToBytes(sendFile);
                             Message sendWarning = new Message(SEND_FILE_WARNING);
                               sendWarning.setFileName(file.getName());
                              sendWarning.setFileSize(myarray.length);
                              try{
                                    sendMessageToServer(sendWarning);
                               catch(Exception excep){
                                    System.out.println(excep);
                   catch(FileNotFoundException fnfe){
                        System.out.println("File Not Found Exception");
                   catch(java.io.IOException ioe){
                        System.out.println("IO Exception");
            else if(o == button2){
                   name = field1.getText();
                   String name2 = field2.getText();
                   Message renameMessage = new Message(RENAME_FILE);
                   renameMessage.setFileName(name);
                   renameMessage.setFileRename(name2);
                   sendMessageToServer(renameMessage);
                   field1.setText("Old name");
                   field2.setText("New name");
            else if(o == button3){
                   name = field3.getText();
                   Message deleteMessage = new Message(DELETE_FILE);
                   deleteMessage.setFileName(name);
                   sendMessageToServer(deleteMessage);
                   field3.setText(defaultText);
            else if(o == button4){
                   name = field4.getText();
                   Message createMessage = new Message(CREATE_FILE);
                   createMessage.setFileName(name);
                   sendMessageToServer(createMessage);     
                   field4.setText(defaultText);     
            else if(o == button5){
                   name = field5.getText();
                   Message downloadMessage = new Message(REQUEST_FILE);
                   downloadMessage.setFileName(name);
                   sendMessageToServer(downloadMessage);
                   field5.setText(defaultText);          
        public void processServerMessage(Message message){
             switch(message.getMessageHeader()){
                   case SEND_FILE_WARNING:
                   //change the download size to file size plus max message size
                   client.setDownload((int)message.getFileSize(),true);
                   //turn message back around with acknowledgement header
                   message.setMessageHeader(SEND_FILE_ACK);
                   //send the message
                   try{
                        sendMessageToServer(message);
                   catch(Exception e){
                        System.out.println(e);
                   break;
                   //server has acknowledged that the client wishes to send a message
                   //so send the message
                   case SEND_FILE_ACK:
                   //send the message
                   try{
                        sendMessageToServer(sendFile);
                   catch(Exception e){
                        System.out.println(e);
                   break;
                   //server is sending the file to the client.
                   case SEND_FILE:
                   //reset the download size to default
                   client.setDownload(DEFAULT_MESSAGE_SIZE,false);
                   //get the file name
                   File f = new File(message.getFileName());
                   //create the file chooser
                   JFileChooser fc = new JFileChooser();
                   //set selected file as thoe one downloaded
                   fc.setSelectedFile(f);
                   //get the button hit by the user
                 int returnVal = fc.showSaveDialog(null);
                 //if button is OK
                  if (returnVal == JFileChooser.APPROVE_OPTION){
                       File temp = fc.getCurrentDirectory();
                       String [] files = temp.list();
                       java.util.List alist = java.util.Arrays.asList(files);
                       f = fc.getSelectedFile();
                       if(alist.contains(message.getFileName())){
                            if(JOptionPane.showConfirmDialog(null,
                                       message.getFileName() + " already exists. Are you sure you want to overwrite this file?",
                                       "Instant Messenger: Quit Program",
                                       JOptionPane.YES_NO_OPTION,
                                       JOptionPane.QUESTION_MESSAGE,
                                       null) == JOptionPane.YES_OPTION) {
                                            //f = fc.getSelectedFile();
                                            System.out.println(f.toString());
                                           //this is where the file is copied
                                           try{
                                                FileOutputStream fs = new FileOutputStream(f);
                                                 fs.write(message.getFile());
                                                 fs.close();
                                           catch(IOException e){
                                                System.out.println(e);
                            else fc.hide();
                       else{
                            System.out.println("Here " + f.toString());
                            try{
                                 FileOutputStream fs = new FileOutputStream(f);
                                  fs.write(message.getFile());
                                  fs.close();
                            catch(IOException e){
                                 System.out.println(e);
                  else fc.hide();
                  break;
                  case INFORMATION:
                  timeEnd = new java.util.Date().getTime();
                  Long rtrip = timeEnd - timeStart;
                  String str = Long.toString(rtrip);
                  double d = Double.valueOf(str).doubleValue();
                  String fullMessage = message.getMessage();
                  fullMessage += " The total time taken for the last request was " +
                  rtrip + " milliseconds" + " or roughly " + d/1000 + " seconds";
                   JOptionPane.showMessageDialog(null,fullMessage,"Information",JOptionPane.INFORMATION_MESSAGE);
                   break;          
    class TestGUI{
        public static void main(String [] args){
             JFrame frame = new JFrame();
             GUI myGUI = new GUI(frame);
    }     If I change the GUI constructor to empty and extend JFrame instead of JDialog and change the call to super the ActionListener stops working. I've never known this problem before (i.e. I always use e.getSource()). I've even cast the object to a JButton to ensure that the right button is pressed and it is all ok.
    Is there something fundamentally wrong when I make those simple changes to JFrame?
    Regards,
    Chris

    I think rather the approach is your action handling in terms of the buttons. The giant actionPerformed method is difficult to read and maintain.
    I would recommend the following things:
    1. Split your ActionListener into multiple smaller listeners. There's not really even a reason for the GUI class to be an action listener. Instead of having GUI implement ActionListener and trying to keep all of the functionality in one place, use anonymous classes:
    button3.addActionListener(new ActionListener()
        public void actionPerformed(ActionEvent e)
            name = field3.getText();
            Message deleteMessage = new Message(DELETE_FILE);
            deleteMessage.setFileName(name);
            sendMessageToServer(deleteMessage);
            field3.setText(defaultText);
    button4.addActionListener(new ActionListener()
        public void actionPerformed(ActionEvent e)
            name = field4.getText();
            Message createMessage = new Message(CREATE_FILE);
            createMessage.setFileName(name);
            sendMessageToServer(createMessage);     
            field4.setText(defaultText);
    2. Only use the == operator on primitives. There are very few cases in which you can properly use the == operator on objects and, in every one of those cases I have experienced, the equals(Object) method produces the same result.
    3. Name your variables more descriptively. There is really very little reason for your buttons to be named button1, button2, and so on. Give them names that mean something. For example, button1 should be named something like uploadFileButton or buttonUpload. That will give us significant information about what it is expected to do, whereas button1 does not. You may be able to remember what button1 does, but you wrote the code. I keep having to refer back to the instantiation of the button to get a hint as to what it does and, in a few months' time, so will you. :) The same goes for your labels and fields, as well.
    I'm not sure why you aren't getting the behavior you want. However, have you checked to determine that the event source of the button click is actually the button when the whole thing is inside of a JFrame? I would expect it to be, but you never know. This is why I recommend using different ActionListeners for each button. That way, you can be sure of what caused the event.
    Just my 2c. Good luck to you. :)

Maybe you are looking for