Example usage for java.awt.event WindowFocusListener WindowFocusListener

List of usage examples for java.awt.event WindowFocusListener WindowFocusListener

Introduction

In this page you can find the example usage for java.awt.event WindowFocusListener WindowFocusListener.

Prototype

WindowFocusListener

Source Link

Usage

From source file:Main.java

public Main(final Frame owner) {
    super(owner);
    JPanel pnl = new JPanel(new BorderLayout());
    pnl.add(new JLabel("Click outside this dialog in the parent frame to close it"), BorderLayout.NORTH);
    JButton btn = new JButton("Click Me");
    btn.addActionListener(e -> JOptionPane.showMessageDialog(Main.this, "New Child Window"));
    pnl.add(btn, BorderLayout.CENTER);
    this.setContentPane(pnl);
    this.pack();//  w  w  w.  j ava2  s .c o  m
    this.setLocationRelativeTo(owner);
    this.setAlwaysOnTop(true);
    this.addWindowFocusListener(new WindowFocusListener() {
        public void windowGainedFocus(WindowEvent e) {
        }

        public void windowLostFocus(WindowEvent e) {
            if (SwingUtilities.isDescendingFrom(e.getOppositeWindow(), Main.this)) {
                return;
            }
            Main.this.setVisible(false);
        }
    });
}

From source file:ec.ui.chart.ChartPopup.java

public ChartPopup(Frame owner, boolean modal) {
    super(owner, modal);
    setLayout(new BorderLayout());

    setType(Type.UTILITY);//from  w ww.j  a v  a 2 s .  c  om
    setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

    addWindowFocusListener(new WindowFocusListener() {
        @Override
        public void windowLostFocus(java.awt.event.WindowEvent evt) {
            dispose();
        }

        @Override
        public void windowGainedFocus(WindowEvent e) {
        }
    });

    panel = new RevisionChartPanel(createChart());

    add(panel, BorderLayout.CENTER);
    setPreferredSize(new Dimension(350, 200));
    setSize(new Dimension(350, 200));
}

From source file:com.edduarte.protbox.ui.windows.RestoreFileWindow.java

private RestoreFileWindow(final PReg registry) {
    super();//from ww w  .  j  a  v  a2  s  .c  om
    setLayout(null);

    final JTextField searchField = new JTextField();
    searchField.setLayout(null);
    searchField.setBounds(2, 2, 301, 26);
    searchField.setBorder(new LineBorder(Color.lightGray));
    searchField.setFont(Constants.FONT);
    add(searchField);

    final JLabel noBackupFilesLabel = new JLabel("<html>No backups files were found!<br><br>"
            + "<font color=\"gray\">If you think there is a problem with the<br>"
            + "backup system, please create an issue here:<br>"
            + "<a href=\"#\">https://github.com/com.edduarte/protbox/issues</a></font></html>");
    noBackupFilesLabel.setLayout(null);
    noBackupFilesLabel.setBounds(20, 50, 300, 300);
    noBackupFilesLabel.setFont(Constants.FONT.deriveFont(14f));
    noBackupFilesLabel.addMouseListener((OnMouseClick) e -> {
        String urlPath = "https://github.com/com.edduarte/protbox/issues";

        try {

            if (Desktop.isDesktopSupported()) {
                Desktop.getDesktop().browse(new URI(urlPath));

            } else {
                if (SystemUtils.IS_OS_WINDOWS) {
                    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + urlPath);

                } else {
                    java.util.List<String> browsers = Lists.newArrayList("firefox", "opera", "safari",
                            "mozilla", "chrome");

                    for (String browser : browsers) {
                        if (Runtime.getRuntime().exec(new String[] { "which", browser }).waitFor() == 0) {

                            Runtime.getRuntime().exec(new String[] { browser, urlPath });
                            break;
                        }
                    }
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    });

    DefaultMutableTreeNode rootTreeNode = registry.buildEntryTree();
    final JTree tree = new JTree(rootTreeNode);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    if (rootTreeNode.getChildCount() == 0) {
        searchField.setEnabled(false);
        add(noBackupFilesLabel);
    }
    expandTree(tree);
    tree.setLayout(null);
    tree.setRootVisible(false);
    tree.setEditable(false);
    tree.setCellRenderer(new SearchableTreeCellRenderer(searchField));
    searchField.addKeyListener((OnKeyReleased) e -> {

        // update and expand tree
        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
        model.nodeStructureChanged((TreeNode) model.getRoot());
        expandTree(tree);
    });
    final JScrollPane scroll = new JScrollPane(tree, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scroll.setBorder(new DropShadowBorder());
    scroll.setBorder(new LineBorder(Color.lightGray));
    scroll.setBounds(2, 30, 334, 360);
    add(scroll);

    JLabel close = new JLabel(new ImageIcon(Constants.getAsset("close.png")));
    close.setLayout(null);
    close.setBounds(312, 7, 18, 18);
    close.setFont(Constants.FONT);
    close.setForeground(Color.gray);
    close.addMouseListener((OnMouseClick) e -> dispose());
    add(close);

    final JLabel permanentDeleteButton = new JLabel(new ImageIcon(Constants.getAsset("permanent.png")));
    permanentDeleteButton.setLayout(null);
    permanentDeleteButton.setBounds(91, 390, 40, 39);
    permanentDeleteButton.setBackground(Color.black);
    permanentDeleteButton.setEnabled(false);
    permanentDeleteButton.addMouseListener((OnMouseClick) e -> {
        if (permanentDeleteButton.isEnabled()) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            PbxEntry entry = (PbxEntry) node.getUserObject();

            if (JOptionPane.showConfirmDialog(null,
                    "Are you sure you wish to permanently delete '" + entry.realName()
                            + "'?\nThis file and its "
                            + "backup copies will be deleted immediately. You cannot undo this action.",
                    "Confirm Cancel", JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) {

                registry.permanentDelete(entry);
                dispose();
                RestoreFileWindow.getInstance(registry);

            } else {
                setVisible(true);
            }
        }
    });
    add(permanentDeleteButton);

    final JLabel configBackupsButton = new JLabel(new ImageIcon(Constants.getAsset("config.png")));
    configBackupsButton.setLayout(null);
    configBackupsButton.setBounds(134, 390, 40, 39);
    configBackupsButton.setBackground(Color.black);
    configBackupsButton.setEnabled(false);
    configBackupsButton.addMouseListener((OnMouseClick) e -> {
        if (configBackupsButton.isEnabled()) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            PbxEntry entry = (PbxEntry) node.getUserObject();
            if (entry instanceof PbxFile) {
                PbxFile pbxFile = (PbxFile) entry;

                JFrame frame = new JFrame("Choose backup policy");
                Object option = JOptionPane.showInputDialog(frame,
                        "Choose below the backup policy for this file:", "Choose backup",
                        JOptionPane.QUESTION_MESSAGE, null, PbxFile.BackupPolicy.values(),
                        pbxFile.getBackupPolicy());

                if (option == null) {
                    setVisible(true);
                    return;
                }
                PbxFile.BackupPolicy pickedPolicy = PbxFile.BackupPolicy.valueOf(option.toString());
                pbxFile.setBackupPolicy(pickedPolicy);
            }
            setVisible(true);
        }
    });
    add(configBackupsButton);

    final JLabel restoreBackupButton = new JLabel(new ImageIcon(Constants.getAsset("restore.png")));
    restoreBackupButton.setLayout(null);
    restoreBackupButton.setBounds(3, 390, 85, 39);
    restoreBackupButton.setBackground(Color.black);
    restoreBackupButton.setEnabled(false);
    restoreBackupButton.addMouseListener((OnMouseClick) e -> {
        if (restoreBackupButton.isEnabled()) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            PbxEntry entry = (PbxEntry) node.getUserObject();
            if (entry instanceof PbxFolder) {
                registry.restoreFolderFromEntry((PbxFolder) entry);

            } else if (entry instanceof PbxFile) {
                PbxFile pbxFile = (PbxFile) entry;
                java.util.List<String> snapshots = pbxFile.snapshotsToString();
                if (snapshots.isEmpty()) {
                    setVisible(true);
                    return;
                }

                JFrame frame = new JFrame("Choose backup");
                Object option = JOptionPane.showInputDialog(frame,
                        "Choose below what backup snapshot would you like restore:", "Choose backup",
                        JOptionPane.QUESTION_MESSAGE, null, snapshots.toArray(), snapshots.get(0));

                if (option == null) {
                    setVisible(true);
                    return;
                }
                int pickedIndex = snapshots.indexOf(option.toString());
                registry.restoreFileFromEntry((PbxFile) entry, pickedIndex);
            }
            dispose();
        }
    });
    add(restoreBackupButton);

    tree.addMouseListener((OnMouseClick) e -> {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (node != null) {
            PbxEntry entry = (PbxEntry) node.getUserObject();
            if ((entry instanceof PbxFolder && entry.areNativeFilesDeleted())) {
                permanentDeleteButton.setEnabled(true);
                restoreBackupButton.setEnabled(true);
                configBackupsButton.setEnabled(false);

            } else if (entry instanceof PbxFile) {
                permanentDeleteButton.setEnabled(true);
                restoreBackupButton.setEnabled(true);
                configBackupsButton.setEnabled(true);

            } else {
                permanentDeleteButton.setEnabled(false);
                restoreBackupButton.setEnabled(false);
                configBackupsButton.setEnabled(false);
            }
        }
    });

    final JLabel cancel = new JLabel(new ImageIcon(Constants.getAsset("cancel.png")));
    cancel.setLayout(null);
    cancel.setBounds(229, 390, 122, 39);
    cancel.setBackground(Color.black);
    cancel.addMouseListener((OnMouseClick) e -> dispose());
    add(cancel);

    addWindowFocusListener(new WindowFocusListener() {
        private boolean gained = false;

        @Override
        public void windowGainedFocus(WindowEvent e) {
            gained = true;
        }

        @Override
        public void windowLostFocus(WindowEvent e) {
            if (gained) {
                dispose();
            }
        }
    });

    setSize(340, 432);
    setUndecorated(true);
    getContentPane().setBackground(Color.white);
    setResizable(false);
    getRootPane().setBorder(BorderFactory.createLineBorder(new Color(100, 100, 100)));
    Utils.setComponentLocationOnCenter(this);
    setVisible(true);
}

From source file:corelyzer.ui.CorelyzerApp.java

/**
 * Called by the DisplayConfiguration dialog class to begin the creation of
 * the OpenGL windows given previously set parameters of rows and columns of
 * monitors, and the properties of each monitor
 *//*from   w  w w .  j  a  va2  s .c  o m*/
public void createGLWindows() {
    int nrows = preferences.numberOfRows;
    int ncols = preferences.numberOfColumns;
    int tileWidth = preferences.screenWidth;
    int tileHeight = preferences.screenHeight;

    float borderLeft = preferences.borderLeft;
    float borderRight = preferences.borderRight;
    float borderDown = preferences.borderDown;
    float borderUp = preferences.borderUp;

    float screenDpiX = preferences.dpix;
    float screenDpiY = preferences.dpiy;

    int row_offset, column_offset;

    try {
        row_offset = Integer.parseInt(preferences.getProperty("display.row_offset"));
        column_offset = Integer.parseInt(preferences.getProperty("display.column_offset"));
    } catch (NumberFormatException e) {
        row_offset = 0;
        column_offset = 0;
    }

    // brg 1/17/2012: In Windows Vista and 7, Z-order issues with tool windows and the main canvas
    // are abundant and beyond my abilities to fix. We discovered a workaround - reduce the
    // canvas size by a single row/column of pixels, and everything will work properly. Enforce
    // this programatically until we find a fix.
    final String osName = System.getProperty("os.name").toLowerCase();
    final boolean isWindowsCompositingOS = (osName.equals("windows 7") || osName.equals("windows vista"));
    if (isWindowsCompositingOS)
        tileHeight--; // remove one row

    SceneGraph.setCanvasRowcAndColumn(nrows, ncols);

    sharedContext = null;
    int r, c, canvasNum = 0;
    for (r = 0; r < nrows; r++) {
        for (c = 0; c < ncols; c++) {
            // Allow alpha GL context
            GLProfile profile = GLProfile.getDefault();
            GLCapabilities cap = new GLCapabilities(profile);//GLProfile.getDefault() );
            cap.setAlphaBits(8);
            // System.out.println("---> GL " + cap.toString());

            /*
             * if(MAC_OS_X) { win = new JFrame(); ((JFrame)
             * win).setUndecorated(true); } else { win = new JWindow(); }
             */

            Window win = new JFrame();
            ((JFrame) win).setUndecorated(true);

            win.setLocation(c * tileWidth + column_offset, r * tileHeight + row_offset);

            // brg 3/16/2012: Once we have a shared context, it must be passed in the constructor.
            // The setContext() method doesn't work. (JOGL bug?)
            GLCanvas cvs = null;
            if (sharedContext != null)
                cvs = new GLCanvas(cap, null, sharedContext, null);
            else
                cvs = new GLCanvas(cap);

            win.add(cvs);
            win.addWindowFocusListener(new WindowFocusListener() {
                public void windowGainedFocus(final WindowEvent event) {
                    // do nothing
                }

                public void windowLostFocus(final WindowEvent event) {
                    String isCanvasAlwaysBelow = preferences.getProperty("ui.canvas.alwaysBelow");

                    boolean b;
                    try {
                        b = Boolean.parseBoolean(isCanvasAlwaysBelow);
                    } catch (Exception e) {
                        b = true;
                    }

                    if (b) {
                        GLWindowsToBack();
                    }
                }
            });

            canvasNum++;

            windowVec.add(win);

            final float px = tileWidth * c + (borderLeft + borderRight) * screenDpiX * c;
            final float py = tileHeight * r + (borderUp + borderDown) * screenDpiY * r;
            final int id = SceneGraph.genCanvas(px, py, tileWidth, tileHeight, screenDpiX, screenDpiY);

            CorelyzerGLCanvas cglc = new CorelyzerGLCanvas(cvs, tileWidth, tileHeight, px, py, id);
            canvasVec.add(cglc);

            // if it's the bottom most screen or the first column,
            // then mark to draw depth scale
            if (c == 0) {
                SceneGraph.setCanvasFirstColumn(cglc.getCanvasID(), true);
            }

            if (r == nrows - 1) {
                SceneGraph.setCanvasBottomRow(cglc.getCanvasID(), true);
            }

            win.pack();
            win.setVisible(true);

            // brg 3/16/2012: In JOGL2, a GLCanvas's context is only usable after the
            // canvas has been made visible. Grab the context from the first canvas
            // and share with subsequent canvases at construction-time.
            if (sharedContext == null)
                sharedContext = cvs.getContext();

            win.toBack();
        }
    }

    createTrackMenuItem.setEnabled(true);
    loadDataMenuItem.setEnabled(true);
    loadStateFileMenuItem.setEnabled(true);

    isGLInited = true;
}

From source file:ca.phon.ipamap.IpaMap.java

public void showSearchFrame(ActionEvent ae) {
    if (searchFrame == null) {
        searchFrame = new JFrame("IPA Map : Search");
        searchFrame.setAlwaysOnTop(true);
        searchFrame.setUndecorated(true);
        searchFrame.getRootPane().putClientProperty("Window.shadow", Boolean.FALSE);

        searchField = createSearchField();
        searchFrame.add(searchField);//from w  w w .j a  va2 s. com

        searchField.getTextField().addKeyListener(new KeyListener() {

            @Override
            public void keyTyped(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                    searchFrame.setVisible(false);
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {

            }

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                    searchFrame.setVisible(false);
                }
            }
        });
        searchField.getEndButton().addActionListener(evt -> {
            searchFrame.setVisible(false);
        });

        searchFrame.addWindowFocusListener(new WindowFocusListener() {

            @Override
            public void windowLostFocus(WindowEvent e) {
                searchFrame.setVisible(false);
            }

            @Override
            public void windowGainedFocus(WindowEvent e) {

            }
        });

    }

    final JComponent source = (JComponent) ae.getSource();
    searchFrame.setSize(source.getWidth(), source.getHeight());

    Point sourcePt = ((JComponent) ae.getSource()).getLocationOnScreen();
    searchFrame.setLocation(sourcePt.x, sourcePt.y);
    searchFrame.setVisible(true);

    searchFrame.requestFocus();
    searchField.getTextField().requestFocus();
}

From source file:net.sradonia.gui.SplashScreen.java

/**
 * Creates a new splash screen.//from   w  w w .  ja  va  2s .  c  om
 * 
 * @param image
 *            the image to display
 * @param title
 *            the title of the window
 */
public SplashScreen(Image image, String title) {
    log.debug("initializing splash screen");

    if (image == null)
        throw new IllegalArgumentException("null image");

    // create the frame
    window = new JFrame(title) {
        private static final long serialVersionUID = 2193620921531262633L;

        @Override
        public void paint(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.drawImage(splash, 0, 0, this);
        }
    };
    window.setUndecorated(true);

    // wait for the image to load
    MediaTracker mt = new MediaTracker(window);
    mt.addImage(image, 0);
    try {
        mt.waitForID(0);
    } catch (InterruptedException e1) {
        log.debug("interrupted while waiting for image loading");
    }

    // check for loading errors
    if (mt.isErrorID(0))
        throw new IllegalArgumentException("couldn't load the image");
    if (image.getHeight(null) <= 0 || image.getWidth(null) <= 0)
        throw new IllegalArgumentException("illegal image size");

    setImage(image);

    window.addWindowFocusListener(new WindowFocusListener() {
        public void windowGainedFocus(WindowEvent e) {
            updateSplash();
        }

        public void windowLostFocus(WindowEvent e) {
        }
    });

    timer = new SimpleTimer(new Runnable() {
        public void run() {
            log.debug(timer.getDelay() + "ms timeout reached");
            timer.setRunning(false);
            setVisible(false);
        }
    }, 5000, false);
    timeoutActive = false;
}

From source file:org.apache.oodt.cas.workflow.gui.WorkflowGUI.java

public WorkflowGUI() throws IOException, IllegalAccessException, InstantiationException {

    this.addWindowFocusListener(new WindowFocusListener() {

        public void windowGainedFocus(WindowEvent e) {
            if (menu != null) {
                menu.revalidate();/*from   w  ww  . ja  va2  s  . c  om*/
            }
            if (toolbox != null) {
                toolbox.revalidate();
            }
            if (perspective != null) {
                perspective.refresh();
            }
        }

        public void windowLostFocus(WindowEvent e) {
        }

    });

    this.setLayout(new BorderLayout());
    this.setPreferredSize(new Dimension(1000, 800));

    Vector<Tool> tools = new Vector<Tool>();
    Tool editTool = new Tool(IconLoader.getIcon(IconLoader.EDIT),
            IconLoader.getIcon(IconLoader.EDIT_SELECTED)) {
        private static final long serialVersionUID = 1682845263796161282L;

        @Override
        public void onClick() {
            WorkflowGUI.this.perspective.setMode(View.Mode.EDIT);
        }
    };
    tools.add(editTool);
    Tool deleteTool = new Tool(IconLoader.getIcon(IconLoader.DELETE),
            IconLoader.getIcon(IconLoader.DELETE_SELECTED)) {
        private static final long serialVersionUID = 5050127713254634783L;

        @Override
        public void onClick() {
            WorkflowGUI.this.perspective.setMode(View.Mode.DELETE);
        }
    };
    tools.add(deleteTool);
    Tool moveTool = new Tool(IconLoader.getIcon(IconLoader.MOVE),
            IconLoader.getIcon(IconLoader.MOVE_SELECTED)) {
        private static final long serialVersionUID = 1682845263796161282L;

        @Override
        public void onClick() {
            WorkflowGUI.this.perspective.setMode(View.Mode.MOVE);
        }
    };
    tools.add(moveTool);
    Tool zoomInTool = new Tool(IconLoader.getIcon(IconLoader.ZOOM_IN),
            IconLoader.getIcon(IconLoader.ZOOM_IN_SELECTED)) {
        private static final long serialVersionUID = 1682845263796161282L;

        @Override
        public void onClick() {
            WorkflowGUI.this.perspective.setMode(View.Mode.ZOOM_IN);
        }
    };
    tools.add(zoomInTool);
    Tool zoomOutTool = new Tool(IconLoader.getIcon(IconLoader.ZOOM_OUT),
            IconLoader.getIcon(IconLoader.ZOOM_OUT_SELECTED)) {
        private static final long serialVersionUID = 1682845263796161282L;

        @Override
        public void onClick() {
            WorkflowGUI.this.perspective.setMode(View.Mode.ZOOM_OUT);
        }
    };
    tools.add(zoomOutTool);
    toolbox = new ToolBox(tools);
    toolbox.setSelected(editTool);
    this.add(toolbox, BorderLayout.NORTH);

    this.setJMenuBar(menu = this.generateMenuBar());
    perspective = new BuildPerspective();
    perspective.refresh();
    this.add(perspective, BorderLayout.CENTER);
}