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

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

  • The use of "super" in a constructor

    Hi,
    I am wondering what using "super();" in a constructor does. I've seen this used in may other people's code and I simply don't understand what that line would do.
    Thanks for your advice.

    the super class being that class which you have derived from.
    Example:
    Base Class
    public class Amphibian
    Amphibian();
    System.out.println("Constructor of Amphibian");
    public swims()
    //swim
    <b>SubClass</b>
    public class Frog extends Amphibian
    Frog()
    super(); // this calls constructor of Amphibian and will print out: Constructor of Amphibian to the console
    I hope this helps

  • This() and super() invocations in constructor bodies

    Hi,
    Could someone please explain why it is not allowed to explicitly
    call this() or super() in a constructor body anywhere as opposed
    to the first statement in the constructor (which in turn implies that
    this() and super() can not be used together) ?
    Also, If the constructor is a constructor for an enum type, it is a compile-time
    error for it to invoke the superclass constructor explicitly. Why ?
    And the last question - why it is not allowed to invoke this() or super()
    with instance fields ?
    Cheers,
    Adrian

    AdrianSosialik wrote:
    Could someone please explain why it is not allowed to explicitly
    call this() or super() in a constructor body anywhere as opposed
    to the first statement in the constructorI think it was a language design decision. One could allow certain statements before invoking another constructor, but this would probably cause more confusion than help. So I guess it was deliberatly chosen to not allow this.
    (which in turn implies that this() and super() can not be used
    together) ?Yes, but if this would be permitted, it would also be harder to guarantee that a superclass constructor gets called exactly once.
    Also, If the constructor is a constructor for an enum type,
    it is a compile-time error for it to invoke the superclass
    constructor explicitly. Why ?Could you provide a "compilable" code snippet that demonstrates this?
    And the last question - why it is not allowed to invoke this()
    or super() with instance fields ?As you are not able to store something in them before the invocation, they contain their default values... (the JVM allows storing values in instance fields before invoking another constructor, but it was apparently decided to not include such a thing in Java)

  • 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

  • JDialog and request focus

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

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

  • Super class default constructor

    Hello,
    I want to clear some confusion. I am studying for the exam. In this particular book an example shows that
    Super class has 2 constructor
    public abc() and public abc(int n)
    Sub class has 2 constructor
    public xyz() and public xyz(int n)
    now when an instance is created for the subclass
    xyz t = new xyz(1)
    It will invoke the super class no argument constructor eventhough a default constructor exist in subclass?
    Regards,
    adil

    Here are the rules for constructors--"ctors" because I'm lazy. Also, because I'm lazy, "super(...)" and "this(...)" mean any super or this call, regardless of how many args it takes, including those that take no args.
    1) Every class has at least one ctor.
    1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
    1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a public MyClass() {...} if you want one.
    1.3) Constructors are not inherited.
    2) The first statement in the body of any ctor is either a call to a superclass ctor super(...) or a call to another ctor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor super() as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
    2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.

  • Film sprocket effect for Super 8MM footage used with HDV 16:9 footage

    Hi!
    I am working on a project that has both Super 8mm and 16:9 HDV footage.
    The Super 8mm is obviously not 16:9 and has two black lines either side of it so I was wondering is anyone knows of an effect/filter to make it appear that the Super 8mm film had sprocket holes running down the side of it, (instead of the dodgy black lines!!).
    If no one knows could someone tell me how best I could incorporate the Super 8mm footage into the HDV 16:9 project, (I have tried changing the aspect ratio but I'm worried it will make all the people have fatter heads!!)?
    Many thanks,
    Alex

    Make a graphic in Photoshop and composite it on top of your footage. It will need to be taller than your video's height in pixels. Keyframe the position so it looks like a continuous movement.

  • Regarding this or super call in constructors

    a call to this or super should be the first line of any constructor if we are providing them?Why cant we have them anywhere in our constructor code?

    You can do this using byte code. (not advised!!)
    However if you feel you want to move this() or super() there is another way to do what you have in mind.
    One thing you can do is call static method in the this/super line which means you can execute code before this/super is called.

  • After Effects CS6 super long render times.

    I am trying to render multiple 30 second long compositions and the renders are reaching over 5 hours each. There is nothing special in any of the compositions. I have rendered these same compositions in the past with minor changes in AE CS5 and they finished in seconds using the Open GL renderer. I understand CS6 uses a different engine for rendering. I have ensured my video card is in the supported list (added it), and ray tracing is set to the GPU. I triple checked all the drivers and everything is up to date. I have tried every combination of settings I can think of with no results. Help!
    System Specs:
    i7-3930K
    GTX 770
    32gb ram
    Windows 7 64bit

    Five hours is not an unusual render time for a 30-second composition, depending on the details of the composition.
    See this page for resources about making After Effects work faster: http://adobe.ly/eV2zE7

  • Everything in After Effects is SUPER pixelated

    Everything is pixelated. Whether I import an image, make a shape, or type in some text, everything is so pixelated! The pixels are HUGE. Like a centimeter across.
    Here is a screenshot:
    http://i43.tinypic.com/2vc6bsl.jpg
    That is a shape with some text on top.

    your viewer settings are set to Custom and you probably have it to some incredibly low setting. . Under your preview you see a pulldown that says custom, drop it down and select one of the presets. Full, Half, Third or Quarter.

  • How to make a JDialog that returns a modal result

    I have a JDialog with some input fields. The results of these fields are stored in a model bean. To get the changed model after the dialog will be closed, I must to write a listener of this dialog to listen a window closing event and from this listener get a model. But it would be nicer if I would habe a method showModalDialog that shows me a dialog and returns the changed model as a result. How can I do it?

    why not do what JOptionPane basically does...
    public Object getModalValue()
       Object obj = null;
       JDialog d = new JDialog(..., true);
       d.show();
       if(needed) obj = new Whatever();
       return obj;
    }

  • I want my JDialog to be the only focusable window

    Hi,
    I have a JFrame containing a button. When the button is pressed a settings dialog (JDialog) pops up. Now I want only the JDialog to be focusable, I mean so that the user can't click on the JFrame so it'll be in focus before closing the dialog window.
    Thanks

    Its called a modal dialog. Read the JDialog API, specifically the constructors, for information on how to make a dialog modal.

  • Popup a JDialog without it gaining focus. Can it be done?

    Can it be done?
    I have thought about having a JDialog already on screen but positioned off screen and move it onscreen when needed but seems a ugly idea. Any one got a nicer solution?

    setFocusableWindowState(false) sort of works but the jDialog does gain focus then focus is given back to whatever window had focus before the JDialog was shown.

  • Cannot use super(msg) in asbstract class constructor!!

    Hi, I'm getting compiling errors (compiler says I must call super first thing I do from constructor, which is exactly what I'm doing!) when trying to call super(String msg) from my subclass constructor. Superclass is abstract and subclasses Exception, on which I also want to call super(msg), to initialize the Exception class with a String message.
    What is wromg ? Please any help in resolving this issue will be highly appreciated...
    /Alcoolio
    abstract class SuperExceptionClass extends Exception{
    void SuperClass(String msg){
    super(msg);
    void someCoolCommonMethod(){
    //dostuff...
    class SubExceptionClass1 extends SuperClass{
    void SubClass(String msg){
    super(msg);
    }

    Hi, I'm getting compiling errors (compiler says I must
    call super first thing I do from constructor, which is
    exactly what I'm doing!) when trying to call
    super(String msg) from my subclass constructor.
    Superclass is abstract and subclasses Exception, on
    which I also want to call super(msg), to initialize
    the Exception class with a String message.
    What is wromg ? Please any help in resolving this
    issue will be highly appreciated...
    /Alcoolio
    abstract class SuperExceptionClass extends Exception{
    void SuperClass(String msg){
    super(msg);
    void someCoolCommonMethod(){
    //dostuff...
    class SubExceptionClass1 extends SuperClass{
    void SubClass(String msg){
    super(msg);
    }First:
    Constructor cannot have a return type. Not even void
    Second:
    Constructor should have same name as the class name. Otherwise it is a function. You can user "super()" only in constructor (although you could do super.xxx / super.xxx() in methods ).
    abstract class SuperClass extends Exception{
    SuperClass(String msg){ // change this
    super(msg);
    void someCoolCommonMethod(){
    //dostuff...
    class SubClass extends SuperClass{
    SubClass(String msg){
    super(msg);
    }

Maybe you are looking for