Dialogs VS Frames

I am creating a simple program that needs to make use of the modal facility of the "Dialog" class but at the same time have the same functionality of the "Frame" class. I've been looking into Dialogs on the web, and looked at the API spec. It says that both the "Frame" and "Dialog" class extend the window class, adding the border and the Title bar. I read on http://java.sun.com/docs/books/tutorial/uiswing/components/dialog.html
that "windows that are more limited than frames". But the only difference I can spot is that it doesn't have the "minimise" "iconify" buttons, but does have a close button-does that close button actually work? My question is, is that the only difference, or are there more? The windows that I want to create, that I want to be modal, will be using the AWT package and have a lot of controls on it!

Windows basically have no decorations, including the taskbar button on the bottom of Windows systems, so any minimize or resize stuff needs to be handled yourself. Because of this, minimize might be difficult. Otherwise, I think for the most part, Windows are the same as Frames, as far as being top level containers. Dialogs have the modal capability, but not Frames or Windows. However, modal is relative. Relative to the the parent "window", that is. So you can't really create an application with 1 window and have that modal. I think you might mean "always on top", and there's no system level "always on top" mode for windows in Java. Maybe there is if you were to use the skins look & feel (http://www.l2fprod.com/). But I think this is only good on MS Windows.

Similar Messages

  • Add picture in a Dialog or Frame??

    hello everybody,
    i ask about how add a picture in a pan of a dialoge a frame. and how change the icon placed in the top right of a dialog.
    thakx in advance

    Do a search on "coffee cup". That question has been answered in detail within the last few days.
    Try the same on "adding image" or "toolkit"
    Cheers
    DB

  • Dialog vs Frame

    I'm making an applet with an 'OutputView'.
    This is a class where an awt.TextArea with the Results is displayed.
    When I make this class inherit from awt.Dialog, I can't longer copy-paste the output (from the textarea) in another program.
    (As the matter of fact, on my computer it works well, on another Pc here, with the same browser, it doesn' t work.)
    When I make this class inherit from awt.frame, everything works fine. But actually, I want to use a Dialog so I can set this OutputView 'modal'.
    Can I do this ? Or is this something typical about dialogs?

    I had this problem with JDialog and JFrame, so it's probably the same bug you see. And I think the bug was related to that you run in an applet, is that what you do also?
    I don't know whether this bug has been fixed, but if you run your code in a browser, without using the plugin, it may very well be the same bug you experience. You can search in the bug database to see if there are any workarounds. I used the trick with frame instead of dialog, but didn't solve the problem that I wanted it to be modal, since that required a dialog box.

  • Problem with file dialog (root frame)

    Hi guys
    I�m having a problem with open up a filedialog.
    I have a rendered jlist and the are some items inside. The user, can right click any item and choose from a list some commands (print, save, update etc)
    Everything works fine but when he clicks the SAVE option (again, right click and choose save)
    FileDialog fd = new FileDialog(new JFrame(),"Save PAX list",FileDialog.SAVE);
    I cannot use new JFrame() (as I did above) because it might block the application.
    For this I�m trying to get the root by:
    Component c = SwingUtilities.getRoot((Component)e.getSource());
    JFrame myFrame = (JFrame)c;
    And than:
    FileDialog fd = new FileDialog myFrame,"Save PAX list",FileDialog.SAVE);
    This get me a null frame :- (
    Anyone?

    The following worked on a "normal" menu item. I didn't test it on a "popup" menu item:
    JMenuItem mi = (JMenuItem)e.getSource();
    JPopupMenu popup = (JPopupMenu)mi.getParent();
    Component c = SwingUtilities.windowForComponent(popup.getInvoker());
    System.out.println(c);

  • JTextField to be focussed while loading the dialog or frame

    hi,
    i would like to know how i could get the focus on the JTextField when my dialogs are displayed.
    while coding in windows, it brings focus at my JTextField if the text field is the first object.
    but in unix Solaris , in which am working now, this doesn't happen.
    can anyone help me out?

    hi,
    i would like to know how i could get the focus on the JTextField when my dialogs are displayed.
    while coding in windows, it brings focus at my JTextField if the text field is the first object.
    but in unix Solaris , in which am working now, this doesn't happen.
    can anyone help me out?

  • How to create a bordeless and titleless dialog or frame?

    Hi people,
    I am trying to do a simple start up screen for my application. I have done the graphics for the startup screen and save as filename.gif. I am looking for a container or a way to paint my the gif so that it looks like a startup screen. I have considered JFrame but haven't found a way to remove the window's title bar. Should I use JDialog?.. Is there a way for me to remove the top title bar. Also anybody knows how I could set my startup screen to be visible for a set period of time and then later display?
    AG

    If your application is out of swing, you can use JWindow, of your application is out of regular components, use Window. I'm more experiancedin swing and I know there are methods to get the users screen size and then from that info you can center the window on the screen. Just don't forget to terminate the window, otherwise people will get mad with an "unclosable" window (they'd have to CTRL+ALT+Del it to close it).
    I have an example: (for Swing, but I'm sure it'll be useful)
    package com.foley.utility;
    import java.awt.*;
    import java.beans.*;
    import javax.swing.*;
    * A window that contains an image.
    * @author Mike Foley
    public class SplashWindow extends JWindow {
         * The Icon displayed in the window.
        private Icon splashIcon;
         * A label used to display the Icon.
        private JLabel iconLabel;
         * Bound property support and name constants.
        private PropertyChangeSupport changeSupport;
        public static final String SPLASHICON_PROPERTY = "SplashIcon";
         * SplashWindow, null constructor.
        public SplashWindow() {
            this( null );
         * SplashWindow, constructor.
         * @param splashIcon�The Icon to view in the window.
        public SplashWindow( Icon splashIcon ) {
            super();
            iconLabel = new JLabel();
            iconLabel.setBorder( BorderFactory.createRaisedBevelBorder() );
            getContentPane().add( iconLabel, BorderLayout.CENTER );
            setSplashIcon( splashIcon );
         * Set the image displayed in the window.
         * This is a bound property named SPLASHICON_PROPERTY.
         * If this property is changed when the window is
         * visible, the window is NOT re-centered on the screen.
         * @param splashIcon�The icon to draw in the window.
        public void setSplashIcon( Icon splashIcon ) {
            Icon old = this.splashIcon;
            this.splashIcon = splashIcon;
            iconLabel.setIcon( splashIcon );
            pack();
            if( changeSupport != null ) {
                changeSupport.firePropertyChange( SPLASHICON_PROPERTY,
                                                  old, splashIcon );
         * Extend the setVisible method to center this window
         * on the screen before being displayed.
         * @param visible�True if showing the window, false if hiding.
        public void setVisible( boolean visible ) {
            if( visible ) {
                // Display the window in the center of the screen.
                Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                Dimension size = getSize();
                int x;
                int y;
                x = screenSize.width / 2 - size.width / 2;
                y = screenSize.height / 2 - size.height / 2;
                    setBounds( x, y, size.width, size.height);
            // Let super show or hide the window.
            super.setVisible( visible );
         * Need to handle PropertyChangeListeners here until this
         * type of code is moved from JComponent to Component.
        public synchronized void addPropertyChangeListener(PropertyChangeListener listener) {
            if (changeSupport == null) {
                changeSupport = new PropertyChangeSupport(this);
            changeSupport.addPropertyChangeListener(listener);
        public synchronized void removePropertyChangeListener(PropertyChangeListener listener) {
            if (changeSupport != null) {
                changeSupport.removePropertyChangeListener(listener);
    } // SplashWindow

  • How Can I make A Dialog/Frame Transparent

    Hi
    I want to make a dialog or frame Transparent. Is it possible in java. Actually i want to add an gif image on the Frame container that image is in curve shape with transparency, and I want this transparency also on the Frame in the java application. I m using JFrame with setUndecorated(true). It will display image (just image) not any Frame behind it, I any one solves my problem to make a frame transparent.
    Thanks
    Khurram

    Check out this link:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=490146
    The program contained therein is really slick.
    My hat is off to the coder.
    Lance

  • Modal Frame or Dialog with Minimize/Maximize buttons

    I want to create a window (dialog or frame) that is modal and has the minimize/maximize buttons. Is it possible? How?
    I normally would use a dialog if I wanted the window to be modal, but a dialog does not have the minimize/maximize buttons. I normally would use a frame if I wanted the window have the minimize/maximize buttons, but a frame cannot be modal.
    Any suggestions, please?

    You can make your "modal panel" listener the window events from all others frames:
    public class YourModalFrame extends JFrame implements WindowListener{
      public YourModalFrame(JFrame owner){
        super("Modal Frame");
        this.owner = owner;
        // we put a glass panel into the main frame
        JPanel glassPanel = new JPanel();
        glassPanel.setOpaque(false);
        glassPanel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        // blocking the events!!!
        glassPanel.addKeyListener        (new KeyAdapter()        {});
        glassPanel.addMouseListener      (new MouseAdapter()      {});
        glassPanel.addMouseMotionListener(new MouseMotionAdapter(){});
        owner.setGlassPane(glassPanel);
        // the frame will listener owner windows events
        owner.addWindowListener(this);
      // Window Listener  //
       * Invoked the first time a window is made visible.
      public void windowOpened(WindowEvent e){}
       * Invoked when the user attempts to close the window
       * from the window's system menu.  If the program does not
       * explicitly hide or dispose the window while processing
       * this event, the window close operation will be cancelled.
      public void windowClosing(WindowEvent e){}
       * Invoked when a window has been closed as the result
       * of calling dispose on the window.
      public void windowClosed(WindowEvent e){}
       * Invoked when a window is changed from a normal to a
       * minimized state. For many platforms, a minimized window
       * is displayed as the icon specified in the window's
       * iconImage property.
       * @see java.awt.Frame#setIconImage
      public void windowIconified(WindowEvent e){
        // Do you want this too?
        //super.setState(JFrame.ICONIFIED);
       * Invoked when a window is changed from a minimized
       * to a normal state.
      public void windowDeiconified(WindowEvent e){
        if(super.getState() == JFrame.ICONIFIED)
          super.setState(JFrame.NORMAL);
        this.requestFocus();
       * Invoked when the window is set to be the user's
       * active window, which means the window (or one of its
       * subcomponents) will receive keyboard events.
      public void windowActivated(WindowEvent e){
        this.requestFocus();
       * Invoked when a window is no longer the user's active
       * window, which means that keyboard events will no longer
       * be delivered to the window or its subcomponents.
      public void windowDeactivated(WindowEvent e){}
    }

  • Hel with modifying cs5/6 script...create anchored frames from text

    hello
    I have one great time saver script for cs5 for create anchored frames from text tagged with/or charachter style/paragraph style. This work in cs6 but have some "bugs" for me. Script need to be compatible with InDesign CS6.
    1. script in original (look bellow) create text frame which is fitted to lenght of the text. I make change and change 466 line:
    AnchoredTextFrame.fit(FitOptions.FRAME_TO_CONTENT);
    now frame is wide as I write in check box, good. But frame not resize to lenght of the text so I add after above lines 466-470:
        var FO = FitOptions.FRAME_TO_CONTENT,
        tfs = ([]).concat.apply([], app.activeDocument.stories.everyItem().textContainers),
        t, i = tfs.length;
    while( i-- ) (t=tfs[i]).overflows && ( t.locked || t.fit(FO) );
    now all is ok but is here better way to make this to work? Simply, i want to spec text frame width in dialog box, frame will resize only verticaly in direction to amount text in frame. I dont want any overset text.
    2. One "bug". For some reason script alter paragraph style of other text which is not subject to be cutted in anchored frame.
    How to resolve this?
    #targetengine "session"
              Automating anchored object creation
              Version: 2
        Script by Thomas Silkjær
              http://indesigning.net/
    Модификация Б. Кащеев, www.adobeindesign.ru
    Скрипт предназначен для создания привязанных фреймов из текста, отформатированного
    каким-либо абзацным или символьным стилем. Эти стили задаются пользователем в диалоговом
    окне скрита. Там же необходимо задать объектный стиль для привязанного фрейма, в котором
    пользователь должен заранее задать оформление и параметры привязки. Далее необходимо
    указать ширину привязанного фрейма, а его высота будет рассчитана автоматически исходя из
    объема текста. При вводе дробных значений ширины привязанного фрейма в качестве
    разделителя целой и дробной части следует использовать не запятую, а точку, следуя западным
    стандартам разработчиков программы  Adobe InDesign. Первоначально идея и скрипт по созданию
    привязанных фреймов принадлежит Thomas Silkjær для версии ID CS4. C появлением версий CS5
    и CS5.5 скрипт перестал в них выполняться, да и в версии CS4 не всегда корректно работал.
    Анализируя недочеты скрипта в данной его версии были исправлены ошибки и внесены
    функциональные дополнения исходя из понимания задачи автором модификации. Добавлена
    возможность выбора стилей, если они они находятся в группах (папках), возможность выбора
    единиц измерения из выпадающего списка, изменены GREP-выражения для поиска текста,
    область действия скрипта ограничена материалом (Story), а не документом.
    var myMeasureUnits = ["Milimeters","Centimeters","Points","Inches", "Picas", "Ciceros"];
    var selectUnits;
    var pStyleIndex = null;
    var cStyleIndex = null;
    var oStyleIndex = null;
    var myH, myW;
    function main()
        app.scriptPreferences.userInteractionLevel = UserInteractionLevels.interactWithAll;
              if (app.documents.length == 0)
                        alert ("Document is not open. Open document first");
                        return;
        var myParaStyleList = myGetParagraphStyleNames();
        var myCharStyleList = myGetCharacterStyleNames();
        var myObjStyleList = myGetObjStyleNames();
        if(app.selection.length && app.selection[0].hasOwnProperty("baseline"))
            var myStory = app.selection[0].parentStory;
            var myWin = myDialog(myParaStyleList, myCharStyleList, myObjStyleList);
            if ( myWin.show()  == 1 )
                var myDocument = app.activeDocument
                with (myDocument.viewPreferences){
                    // Сохраняем старые единицы измерения в переменных myOldXUnits, myOldYUnits
                    var myOldXUnits = horizontalMeasurementUnits;
                    var myOldYUnits = verticalMeasurementUnits;
                    // Устанавливаем новые единицы измерения
                    switch(selectUnits)
                        case 0:                   
                            horizontalMeasurementUnits = MeasurementUnits.millimeters;
                            verticalMeasurementUnits = MeasurementUnits.millimeters;
                            break;
                        case 1:
                            horizontalMeasurementUnits = MeasurementUnits.centimeters;
                            verticalMeasurementUnits = MeasurementUnits.centimeters;
                            break;
                        case 2:
                            horizontalMeasurementUnits = MeasurementUnits.points;
                            verticalMeasurementUnits = MeasurementUnits.points;
                            break;                  
                        case 3:
                            horizontalMeasurementUnits = MeasurementUnits.inches;
                            verticalMeasurementUnits = MeasurementUnits.inches;
                            break;
                        case 4:
                            horizontalMeasurementUnits = MeasurementUnits.picas;
                            verticalMeasurementUnits = MeasurementUnits.picas;
                            break;
                        case 5:
                            horizontalMeasurementUnits = MeasurementUnits.ciceros;
                            verticalMeasurementUnits = MeasurementUnits.ciceros;
                            break;
                        default: break;
                    } // switch
                if(cStyleIndex == null)
                {/*поиск по стилю абзаца*/
                    var pStyle = getParagraphStyleByName(myParaStyleList[pStyleIndex]);
                    resetGREPfindChange();
                    app.findGrepPreferences.appliedParagraphStyle = pStyle;
                    app.findGrepPreferences.findWhat = NothingEnum.nothing;
                else //
                    // поиск по стилю символов
                    var cStyle = getCharacterStyleByName(myCharStyleList[cStyleIndex]);
                    resetGREPfindChange();
                    app.findGrepPreferences.appliedCharacterStyle = cStyle;
                    //app.findGrepPreferences.findWhat = ".+";
                    app.findGrepPreferences.findWhat = NothingEnum.nothing;
                var foundItems = myStory.findGrep();
                if(!foundItems.length) {
                    alert("Found the text to be placed in a linked frames"); exit();
                //alert(foundItems.length);
                //alert (foundItems[0].contents)
                //alert (foundItems[1].contents)
                var oStyle = getObjectStyleByName(myObjStyleList[oStyleIndex]);
                for(var i = foundItems.length-1; i >=0; i--)
                    //alert (foundItems[i].contents)
                    createAnchoredFrame(foundItems[i], oStyle);
                with (myDocument.viewPreferences){
                    try{
                        horizontalMeasurementUnits = myOldXUnits;
                        verticalMeasurementUnits = myOldYUnits;
                    catch(myError){
                        alert("Unable to return to the original unit");
            } //if ( myWin.show()
        } //if(app.selection.length && app.selection[0].hasOwnProperty("baseline"))
        else
            alert("Place the cursor in the text and run the script again")
    } // main
    function myGetParagraphStyleNames()
    // Получаем список стилей абзацев
              var curGroup;
              var curGroupName;
              var curNameInGroup;
              var myParagraphStyleNames = app.activeDocument.paragraphStyles.everyItem().name;
              myParagraphStyleNames.shift(); // удаление стиля No Paragraph Style
              var paraGroups = app.activeDocument.paragraphStyleGroups;
              var paraGroupsLen = paraGroups.length;
              for(var i = 0; i < paraGroupsLen; i++) {
                        curGroup = paraGroups[i];
                        curGroupName = paraGroups[i].name;
                        curGroupStyleNames = curGroup.paragraphStyles.everyItem().name
                        for (j=0; j< curGroupStyleNames.length; j++)
                                  curNameInGroup = curGroupName +":"+ curGroupStyleNames[j];
                                  myParagraphStyleNames.push(curNameInGroup);
              return myParagraphStyleNames;
    function myGetCharacterStyleNames()
    // Получаем список символьных стилей
              var curGroup;
              var curGroupName;
              var curNameInGroup;
              var myCharacterStyleNames = app.activeDocument.characterStyles.everyItem().name;
              myCharacterStyleNames.shift(); // удаление стиля None
              var charGroups = app.activeDocument.characterStyleGroups;
              var charStyleGroupLen = charGroups.length;
              for(var i=0; i < charStyleGroupLen; i++)
                        curGroup = charGroups[i];
                        curGroupName = charGroups[i].name;
                        curGroupStyleNames = curGroup.characterStyles.everyItem().name;
                        for (j=0; j< curGroupStyleNames.length; j++)
                                  curNameInGroup = curGroupName +":"+ curGroupStyleNames[j];
                                  myCharacterStyleNames.push(curNameInGroup);
              } //for
              return myCharacterStyleNames;
    } // fnc
    function myGetObjStyleNames()
        var curGroup;
              var curGroupName;
              var curNameInGroup;
              var myObjStyleNames = app.activeDocument.objectStyles.everyItem().name;
        myObjStyleNames.shift();
        var objGroups = app.activeDocument.objectStyleGroups;
        var objStyleGroupLen = objGroups.length;
        for(var i=0; i < objStyleGroupLen; i++)
                        curGroup = objGroups[i];
                        curGroupName = objGroups[i].name;
                        curGroupStyleNames = curGroup.objectStyles.everyItem().name;
                        for (var j=0; j< curGroupStyleNames.length; j++)
                                  curNameInGroup = curGroupName +":"+ curGroupStyleNames[j];
                                  myObjStyleNames.push(curNameInGroup);
              } //for
        return myObjStyleNames;
    } // fnc
    function myDialog(myParaStyleList, myCharStyleList, myObjStyleList)
        var myDialog = new Window('dialog', 'Create anchored text frames');
        this.windowRef = myDialog;
              myDialog.orientation = "column";
        myDialog.alignChildren = ['fill', 'fill'];
        // добавляем панель 1 с элементами управления
        myDialog.Pnl1 = myDialog.add("panel", undefined, "Move the text in linked frames");
              myDialog.Pnl1.orientation = "column";
        myDialog.Pnl1.alignChildren = "left";
        myDialog.Pnl1.pstyle = myDialog.Pnl1.add('checkbox', undefined, "Text with the paragraph style");
        myDialog.Pnl1.pstyle.value = false;
        myDialog.Pnl1.dropdownParaStyle = myDialog.Pnl1.add("dropdownlist", undefined, myParaStyleList);
        myDialog.Pnl1.dropdownParaStyle.title = "Select the paragraph style ";
        myDialog.Pnl1.dropdownParaStyle.minimumSize = [250,20];
        myDialog.Pnl1.dropdownParaStyle.enabled = false;
        myDialog.Pnl1.dropdownParaStyle.selection = 0;
        if(myCharStyleList.length)
            myDialog.Pnl1.сstyle = myDialog.Pnl1.add('checkbox', undefined, "Text with character style");
            myDialog.Pnl1.сstyle.value = false;
            myDialog.Pnl1.dropdownCharStyle = myDialog.Pnl1.add("dropdownlist", undefined, myCharStyleList );
            myDialog.Pnl1.dropdownCharStyle.title = "Select the character style ";
            myDialog.Pnl1.dropdownCharStyle.minimumSize = [250,20];
            myDialog.Pnl1.dropdownCharStyle.enabled = false;
            myDialog.Pnl1.dropdownCharStyle.selection = 0;
            myDialog.Pnl1.pstyle.onClick = function()
                if(this.value) {
                    myDialog.Pnl1.dropdownParaStyle.enabled = true;
                    myDialog.Pnl1.dropdownCharStyle.enabled = false;
                    myDialog.Pnl1.сstyle.value = false;
                else
                    myDialog.Pnl1.dropdownParaStyle.enabled = false;
                    myDialog.Pnl1.dropdownCharStyle.enabled = true ;
                    myDialog.Pnl1.сstyle.value = true;
            }// fnc
            myDialog.Pnl1.сstyle.onClick = function()
                if(this.value)
                    myDialog.Pnl1.dropdownCharStyle.enabled = true;
                    myDialog.Pnl1.dropdownParaStyle.enabled = false;
                    myDialog.Pnl1.pstyle.value = false;
                else
                    myDialog.Pnl1.dropdownCharStyle.enabled = false;
                    myDialog.Pnl1.dropdownParaStyle.enabled = true ;
                    myDialog.Pnl1.pstyle.value = true;
            }// fnc
        }//  if(myCharStyleList.length)
        else
            myDialog.Pnl1.pstyle.onClick = function()
                if(this.value)
                    myDialog.Pnl1.dropdownParaStyle.enabled = true;
                else
                    myDialog.Pnl1.dropdownParaStyle.enabled = false;
    //  Вторая панель
        myDialog.Pnl2 = myDialog.add("panel", undefined, "Parameters of the text frame");
              myDialog.Pnl2.orientation = "column";
        myDialog.Pnl2.alignChildren = "left"; 
        myDialog.Pnl2.dropdownObjStyle = myDialog.Pnl2.add("dropdownlist", undefined, myObjStyleList );
        myDialog.Pnl2.dropdownObjStyle.title = "Select an object style ";
        myDialog.Pnl2.dropdownObjStyle.minimumSize = [250,20];
        myDialog.Pnl2.dropdownObjStyle.enabled = true;
        myDialog.Pnl2.dropdownObjStyle.selection = 0;
        myDialog.Pnl2.Group1 = myDialog.Pnl2.add( "group" );
        myDialog.Pnl2.Group1.stxt1 = myDialog.Pnl2.Group1.add("statictext", undefined, "The width of the text frame");
        myDialog.Pnl2.Group1.etxt = myDialog.Pnl2.Group1.add("edittext", undefined, "40");
        myDialog.Pnl2.Group1.etxt.characters = 10;
        myDialog.Pnl2.Group1.dropdownMeasurementUnits = myDialog.Pnl2.Group1.add("dropdownlist", undefined, myMeasureUnits );
        myDialog.Pnl2.Group1.dropdownMeasurementUnits.maximumSize = [80,20];
        myDialog.Pnl2.Group1.dropdownMeasurementUnits.selection = 0;
        //myDialog.Pnl2.Group1.stxt2 = myDialog.Pnl2.Group1.add("statictext", undefined, "mm ");
        /*myDialog.Pnl2.Group2 = myDialog.Pnl2.add( "group" );
        myDialog.Pnl2.Group2.stxt1 = myDialog.Pnl2.Group2.add("statictext", undefined, "Высота привязанного фрейма  ");
        myDialog.Pnl2.Group2.etxt = myDialog.Pnl2.Group2.add("edittext", undefined, "30");
        myDialog.Pnl2.Group2.etxt.characters = 10;
        //myDialog.Pnl2.Group2.stxt2 = myDialog.Pnl2.Group2.add("statictext", undefined, "mm ");*/
        myDialog.Pnl2.stxt1 = myDialog.Pnl2.add("statictext", undefined, "Attention! When you enter fractional values as");
        myDialog.Pnl2.stxt2 = myDialog.Pnl2.add("statictext", undefined, "the decimal part, should be used");
        myDialog.Pnl2.stxt3 = myDialog.Pnl2.add("statictext", undefined, "point, not comma.");
        myDialog.Pnl2.stxt1.graphics.foregroundColor = myDialog.Pnl2.stxt1.graphics.newPen (myDialog.Pnl2.stxt1.graphics.PenType.SOLID_COLOR, [1, 0, 0, 1], 1);
        myDialog.Pnl2.stxt2.graphics.foregroundColor = myDialog.Pnl2.stxt2.graphics.newPen (myDialog.Pnl2.stxt2.graphics.PenType.SOLID_COLOR, [1, 0, 0, 1], 1);
        myDialog.Pnl2.stxt3.graphics.foregroundColor = myDialog.Pnl2.stxt3.graphics.newPen (myDialog.Pnl2.stxt3.graphics.PenType.SOLID_COLOR, [1, 0, 0, 1], 1);
        // --------- кнопки --------------
        var myGroup = myDialog.add( "group" );
        myGroup.orientation = 'row';
        myGroup.alignChildren = ['fill', 'fill']; 
        myGroup.okButton = myGroup.add( "button", undefined, "OK" );
        myGroup.okButton.onClick = function()
            if(myCharStyleList.length) // есть символьные стили в документе
                if(!myDialog.Pnl1.pstyle.value && !myDialog.Pnl1.сstyle.value)
                    alert("You must select a paragraph style or character style");
                    return ;
                if(myDialog.Pnl1.pstyle.value) { pStyleIndex= myDialog.Pnl1.dropdownParaStyle.selection.index; cStyleIndex = null;}
                else {cStyleIndex = myDialog.Pnl1.dropdownCharStyle.selection.index; pStyleIndex=null; }
            else // нет символьных стилей
                if(!myDialog.Pnl1.pstyle.value)
                    alert("You must select a paragraph style");
                    return;
                pStyleIndex = myDialog.Pnl1.dropdownParaStyle.selection.index;
                cStyleIndex = null;
            } //  else // нет символьных стилей
           oStyleIndex = myDialog.Pnl2.dropdownObjStyle.selection.index;
           if(myDialog.Pnl2.Group1.etxt.text =="")
               alert("Enter the width of the text frame");
               return;
            else
                myW = myDialog.Pnl2.Group1.etxt.text;
                myH = myW;
            /*if(myDialog.Pnl2.Group2.etxt.text == "")
                alert("Введите высоту привязанного фрейма");
                return;
            else
                myH = myDialog.Pnl2.Group2.etxt.text;
           selectUnits = myDialog.Pnl2.Group1.dropdownMeasurementUnits.selection.index;
            myDialog= this.window.close( 1 );
        myGroup.cancelButton = myGroup.add( "button", undefined, "Cancel" );
        myGroup.cancelButton.onClick = function() { myDialog = this.window.close( 0 ); }
        myDialog.Pnl3 = myDialog.add("panel", undefined, "");
        myDialog.Pnl2.alignChildren = "left";
        myDialog.Pnl3.stxt = myDialog.Pnl3.add("statictext", undefined, "(с) Thomas Silkjær        (с) Борис Кащеев, www.adobeindesign.ru ");
        return myDialog;   
    } // fnc
    function getParagraphStyleByName(myStyleName)
              var DocParaStyles = app.activeDocument.paragraphStyles;
              var DocParaGroups = app.activeDocument.paragraphStyleGroups;
              myStyleName = ""+myStyleName;
              var pos = myStyleName.indexOf(":")
              if(pos == -1)
              // стиль не в группе
              var myStyle = DocParaStyles.item(myStyleName);
                        return myStyle;
              } //if
              else
                        var myGroupAndStyleNames = myStyleName.split(":")
                        var myGroupName = myGroupAndStyleNames[0];
                        var myStyleName = myGroupAndStyleNames[1];
                        var myGroup =DocParaGroups.item(myGroupName);
                        return myGroup.paragraphStyles.item(myStyleName);
    } // fnc
    function getCharacterStyleByName(myStyleName)
              var DocChStyles = app.activeDocument.characterStyles;
              var DocCharGroups = app.activeDocument.characterStyleGroups;
              // Есть ли в имени полученного символьного стиля двоеточие? (двоеточие разделяет название группы стилей и название стиля)
              myStyleName = String (myStyleName);
              var pos = myStyleName.indexOf(":");
              if(pos == -1)
              // стиль не в группе
                        return DocChStyles.item(myStyleName)
              } //if...
              else
              {// Стиль в какой-то группе
                        var myGroupAndStyleNames = myStyleName.split(":")
                        var myGroupName = myGroupAndStyleNames[0];
                        var myStyleName = myGroupAndStyleNames[1];
                        var myGroup = DocCharGroups.item(myGroupName);
                        return myGroup.characterStyles.itemByName(myStyleName);
              } // else
    } // fnc()+
    function getObjectStyleByName(myStyleName)
        var DocObjStyles = app.activeDocument.objectStyles;
        var DocCObjGroups = app.activeDocument.objectStyleGroups;
        myStyleName = String (myStyleName);
        var pos = myStyleName.indexOf(":");
        if(pos == -1)
              // стиль не в группе
                        return DocObjStyles.item(myStyleName);
              } //if...
        var myGroupAndStyleNames = myStyleName.split(":");
        var myGroupName = myGroupAndStyleNames[0];
        var myStyleName = myGroupAndStyleNames[1];
        var myGroup = DocObjGroups.item(myGroupName);
                        return myGroup.objectStyles.itemByName(myStyleName);
    } //fnc
    function resetGREPfindChange()
        app.changeGrepPreferences = NothingEnum.nothing;
        app.findGrepPreferences = NothingEnum.nothing;
        app.findChangeGrepOptions.includeFootnotes = false;
        app.findChangeGrepOptions.includeHiddenLayers = false;
        app.findChangeGrepOptions.includeLockedLayersForFind = false;
        app.findChangeGrepOptions.includeLockedStoriesForFind = false;
        app.findChangeGrepOptions.includeMasterPages = false;
    function createAnchoredFrame(myText, myObjStyle)
        var myGeometricBounds = [];
        var myInsertionPoint = myText.insertionPoints[0];
        myInsertionPoint.select;
        var AnchoredTextFrame = myInsertionPoint.textFrames.add();
        myGeometricBounds = AnchoredTextFrame.geometricBounds;
        //alert(parseFloat(myH) + " " + parseFloat(myW))
        myGeometricBounds[2] = myGeometricBounds[0] + parseFloat(myH);
        myGeometricBounds[3] = myGeometricBounds[1] + parseFloat(myW);
        AnchoredTextFrame.geometricBounds = myGeometricBounds;
        AnchoredTextFrame.anchoredObjectSettings.anchoredPosition = AnchorPosition.anchored;
        myText.move(LocationOptions.before, AnchoredTextFrame.texts[0]);
        AnchoredTextFrame.appliedObjectStyle = myObjStyle;
        AnchoredTextFrame.fit(FitOptions.CONTENT_TO_FRAME);
        var FO = FitOptions.FRAME_TO_CONTENT,
        tfs = ([]).concat.apply([], app.activeDocument.stories.everyItem().textContainers),
        t, i = tfs.length;
    while( i-- ) (t=tfs[i]).overflows && ( t.locked || t.fit(FO) );
    } //fnc
    main();

    Hi Cari,
    I did create a new user account (admin level) and InDesign works like a charm.
    When I went back to the other account, plug-ins gone, I deleted the prefs and caches, restarted and still everything is crashing as before.
    At least I am working on one account and I will contiue to troubleshoot on the other account. And at some point either the new account will crash or the old account will work and I will go from there.
    Thanks for the info about Mac remembering info. Always trying to be helpful these Macs.
    And thanks for getting at least into a workable space!!! I am supremely grateful!

  • What's the best way of using dialogs?

    Let's guess that we have frame and dialog,
    dialog is really complicated and have many components like JTextField, JTextArea check bottons etc...
    What's right way to return all information from dialog to frame when user fill all components and push OK? I thought that it'd better to create an object put all information in there and return it to frame, but I didn't find how to set user return object to dialogs..
    What do you usually do?

    Let's guess that we have frame and dialog...
    What do you usually do? I look at the API specs and Tutorials to see if I missed something in using dialogs, if I still can't figure it out, then I post a question here with sample code and error messages...
    Otherwise it a huge GUESS as to what the problem is...
    The Java Tutorial
    http://java.sun.com/docs/books/tutorial/index.html
    Essentials of the Java Programming Language: A Hands-On Guide, Part 1 and 2
    http://java.sun.com/developer/onlineTraining/Programming/BasicJava1/
    http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/
    Language Essentials Short Course
    http://java.sun.com/developer/onlineTraining/JavaIntro/contents.html
    Tutorial Index
    http://java.sun.com/developer/onlineTraining/index.html
    J2SE API Specification Index
    http://java.sun.com/reference/api/index.html
    Setting the class path
    http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/classpath.html
    - MaxxDmg...

  • Keep dialog on top while clicking elsewhere, like JToolBar

    Hi,
    I have a JDialog, that once it is open I would like for it to remain visible even if the user clicks elsewhere in the application. If the user clicks in the application the dialog should just lose focus (but not get hidden)...the JToolBar has this functionality. When u "undock" a JToolBar the dialog (or frame, not sure what it is) does not get hidden when something else gets focus...how/what can i do to solve my problem?
    thanks

    for anyone who cares...u need a window ancestor for ur dialog..u can find it by this
         JDialog dialog;
         Window window = SwingUtilities.getWindowAncestor(toolbar);
         if (window instanceof Frame) {
         dialog = new ToolBarDialog((Frame)window, toolbar.getName(), false);
         } else if (window instanceof Dialog) {
         dialog = new ToolBarDialog((Dialog)window, toolbar.getName(), false);
         } else {
         dialog = new ToolBarDialog((Frame)null, toolbar.getName(), false);
         }

  • How to link frames like jdialog

    i uses many JFrame, what i want is to link all new JFrames to a parent frame, similiar to passing parent frame argument to new JDialog
    Why i want is to close all the frame running in a application except parent one.

    Use the following from within your main frame
    for (Frame f : Frame.getFrames()){
        if (f != this){
             f.dispose();
    }If that doesn't work, you could maintain a array of Frames in your main frame and have each dialog / child frame register when it is created or when it becomes visible.

  • Custom dialog

    hello guys,
    I need help with some code. I am trying to request a user to click a button to get a number and then use this number in the program.
    The problem is that the program continues before the user gets a chance to do this. This is my "code"!
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class MyFrame extends JFrame{
        public MyFrame(){
            super("Choose a number");
            NumberInput numberInput = new NumberInput();
            int any_number;
            any_number = numberInput.getNumber();
            JOptionPane.showMessageDialog(null, "You have chosen the number "
                + any_number, " ", JOptionPane.INFORMATION_MESSAGE);
        public static void main(String[] args){
            MyFrame myframe = new MyFrame();
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class NumberButton extends JButton implements ActionListener{
        boolean isClicked = false;
        private int number;
        public NumberButton(int num){
            setNumber(num);
            setText("" + num);
            addActionListener(this);
        public int getNumber(){
            return number;
        public void setNumber(int num){
            this.number = num;
        public boolean getClicked(){
            return isClicked;
        public void setClicked(boolean ic){
            this.isClicked = ic;
        public void actionPerformed(ActionEvent e) {
            if(isClicked == false){
                setClicked(true);
            else{
                setClicked(false);
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    class NumberInput extends JDialog{
        final static ArrayList numberlist = new ArrayList(27);
        private JButton okayButton = new JButton("OKAY");
        private static JPanel numberPanel = new JPanel();
        private int chosen_number = 0;
        public NumberInput(){
            for (int i = 0; i < 10; i++){
                NumberButton numbutton = new NumberButton(i);
                numberPanel.add(numbutton);
                numberlist.add(numbutton);
            okayButton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    for (int i = 0; i < 10; i++){
                        NumberButton n = (NumberButton)numberlist.get(i);
                        if(n.getClicked()== true){
                            chosen_number = n.getNumber();
                            break;
                        else if(n.getClicked() == false)
                            chosen_number = 20;
                    dispose();
            getContentPane().add(new JLabel("Click a number ", SwingConstants.CENTER), BorderLayout.NORTH);
            getContentPane().add(numberPanel, BorderLayout.CENTER);
            getContentPane().add(okayButton, BorderLayout.SOUTH);
            setVisible(true);
            setSize(500, 150);
            show();
        public int getNumber(){
            return chosen_number;
    }I would really, sincerely appreciate any pointers or suggestions... Thanks in advance.

    the simplest solution is to make your dialog modal. This will enfore the user to enter a value before the next line of code can be executed.
    below is an exmaple of a Login Dialog that prompt the user for the loogin and password. the main() method shows how to use the dialog.
    public class LoginDialog  {
        public final static int CANCEL_OPTION     = 0; 
        public final static int UNDECIDED_OPTION  = 1; 
        public final static int APPROVE_OPTION    = 2; 
        private JDialog        dialog      = null;  // the Login dialog
        private JFrame         parent      = null;  // the owner of this object
        private JPanel         loginPanel  = null;   
        private JPanel         buttonPanel = null;
        private JLabel         prompt1     = new JLabel("Login:");
        private JLabel         prompt2     = new JLabel("Password:");
        private JTextField     txtLogin    = new JTextField(15);
        private JPasswordField txtPwd      = new JPasswordField(15);     
        private int            retValue    = UNDECIDED_OPTION;
        * Main driver
        public static void main(String args[]){
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(200,250);
            frame.setVisible(true);
            LoginDialog dialog = new LoginDialog();
            dialog.showDialog(frame, true);
            if (dialog.getUserOption() == LoginDialog.APPROVE_OPTION){
                System.out.println("Ret Value = " + dialog.getUserOption());
                System.out.println("Login     = " + dialog.getLogin());
                System.out.println("Password  = " + dialog.getPassword());
        * Default constructor to instantiate an instance of this class.
         public LoginDialog(){
             loginPanel  = createLoginPanel();
             buttonPanel = createButtonPanel();
        * Pops up a "Login" input dialog.
        * @param parent the owner of this dialog (usually a Frame or a Dialog)
        * @param modal true if this dialog is modal, false otherwise.
         public void showDialog(JFrame parent, boolean modal){
              txtPwd.setText("");
              txtLogin.setText("");
              retValue = UNDECIDED_OPTION;
              this.parent = parent;
              dialog = new JDialog(parent, "Login", modal);
              dialog.setLayout(new BorderLayout());
              dialog.add(loginPanel,  CENTER);
              dialog.add(buttonPanel, SOUTH);
              dialog.setResizable(false);
              dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
              dialog.setLocationRelativeTo(parent);
              dialog.setSize(350, 130);
              dialog.setVisible(true);
        * Create and return a login panel.  This panel contains the two textfields
        * for entering the user's login and password.
        * @return a login panel.
         private JPanel createLoginPanel(){
             JPanel p1 = new JPanel(new GridLayout(2,1));
             JPanel p2 = new JPanel(new GridLayout(2,1));
             p1.add(prompt1);
             p1.add(prompt2);
             p2.add(txtLogin);
             p2.add(txtPwd);
             JPanel panel = new JPanel();
             panel.add(p1);
             panel.add(p2);
             panel.setBorder(BorderFactory.createEmptyBorder(5,5,0,5));
             return panel;
        * Create and return a button panel. This panel contains the "Cancel" and
        * "OK" buttons.
        * @return a button panel.
         private JPanel createButtonPanel(){
              Dimension dim = new Dimension(80, 23);
              JButton btnCancel = new JButton("Cancel");
              btnCancel.setMnemonic('C');
              btnCancel.setPreferredSize(dim);
              btnCancel.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                       retValue = CANCEL_OPTION;
                       dialog.setVisible(false);     
              JButton btnLogin = new JButton("Login");
              btnLogin.setMnemonic('L');
              btnLogin.setPreferredSize(dim);
              btnLogin.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        retValue = APPROVE_OPTION;
                       dialog.setVisible(false);     
              JPanel panel = new JPanel();
              panel.add(btnLogin);
              panel.add(Box.createRigidArea(new Dimension(10,10)));
              panel.add(btnCancel);
              panel.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
             return panel;
        * Return the state of the login dialog option. The states can be one of the
        * following:
        *    LoginDialog.CANCEL_OPTION
        *    LoginDialog.APPROVE_OPTION
        *    LoginDialog.UNDECIDED_OPTION
        * @return the state of the login dialog option.
         public int getUserOption(){ return retValue; }
        * Return the login if the user's option is FontDialog.APPROVE_OPTION;
        * otherwise, return null.
        * @return the login.
         public String getLogin(){
             return (retValue == APPROVE_OPTION)? txtLogin.getText(): null;
        * Return the password if the user's option is FontDialog.APPROVE_OPTION;
        * otherwise, return null.
        * @return the login.
         public String getPassword(){
             return (retValue == APPROVE_OPTION)? new String(txtPwd.getText()): null;
    }

  • Closing a Swing App with Window Closing Event With Dialogs On Close

    A while back I started a thread discussing how to neatly close a Swing app using both the standard window "X" button and a custom action such as a File menu with an Exit menu item. Ultimately, I came to the conclusion that the cleanest solution in many cases is to use a default close operation of JFrame.EXIT_ON_CLOSE and in any custom actions manually fire a WindowEvent with WindowEvent.WINDOW_CLOSING. Using this strategy, both the "X" button and the custom action act in the same manner and can be successfully intercepted by listening for a window closing event if any cleanup is required; furthermore, the cleanup could use dialogs to prompt for user actions without any ill effects.
    I did, however, encounter one oddity that I mentioned in the previous thread. A dialog launched through SwingUtilities.invokeLater in the cleanup method would cause the app to not shutdown. This is somewhat of an academic curiosity as I am not sure you would ever have a rational need to do this, but I thought it would be interesting to explore more fully. Here is a complete example that demonstrates; see what you think:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class CloseByWindowClosingTest {
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        launchGUI();
         private static void launchGUI() {
              final JFrame frame = new JFrame("Close By Window Closing Test");
              JPanel panel = new JPanel();
              panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
              JButton button1 = new JButton("No Dialog Close");
              JButton button2 = new JButton("Dialog On Close");
              JButton button3 = new JButton("Invoke Later Dialog On Close");
              button1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        postWindowClosingEvent(frame);
              button2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        JOptionPane.showMessageDialog(frame, "Test Dialog");
                        postWindowClosingEvent(frame);
              button3.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        SwingUtilities.invokeLater(new Runnable() {
                             public void run() {
                                  JOptionPane.showMessageDialog(frame, "Test Dialog");
                        postWindowClosingEvent(frame);
              panel.add(button1);
              panel.add(button2);
              panel.add(button3);
              frame.setContentPane(panel);
              frame.pack();
              frame.setLocationRelativeTo(null);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.addWindowListener(new WindowAdapter() {
                   @Override
                   public void windowClosing(WindowEvent event) {
                        System.out.println("Received Window Closing Event");
              frame.setVisible(true);
         private static void postWindowClosingEvent(JFrame frame) {
              WindowEvent windowClosingEvent = new WindowEvent(frame, WindowEvent.WINDOW_CLOSING);
              frame.getToolkit().getSystemEventQueue().postEvent(windowClosingEvent);
    }An additional note not in the example -- if in the button 3 scenario you were to put the window closing event posting inside the invoke later, the app then again closes. However, as implemented, what is it that causes button 3 to not result in the application closing?
    Edited by: Skotty on Aug 11, 2009 5:08 PM -- Modified example code -- added the WindowAdapter to the frame as a window listener to show which buttons cause listeners to receive the window closing event.

    I'm not sure I understand why any "cleanup" code would need to use SwingUtilities.invokeLater() to do anything. Assuming this "cleanup method" was called in response to a WindowEvent, it's already being called on the EDT.
    IIRC, my approach to this "problem" was to set the JFrame to DO_NOTHING_ON_CLOSE. I create a "doExit()" method that does any cleanup and exits the application (and possibly allows the user to cancel the app closing, if so desired). Then I create a WindowListener that calls doExit() on windowClosingEvents, and have my "exit action" call doExit() as well. Seems to work fine for me.

  • Any pre-existing code to center windows/dialogs?

    Is there an easy way to center dialogs or frame you create?

    You can calculate the origin with the help of the screen size:
    import java.awt.Point;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension windowSize = getSize(); // when called in the window/dialog/frame
    Point centerLocation = new Point((screenSize.width-windowSize.width)/2, (screenSize.height-windowSize)/2);
    setLocation(centerLocation);Beginning with JDK 1.4, you can simplify this to
    window.setLocationRelativeTo(null);This method can be used to place a window centered on another.
    Fritz

Maybe you are looking for