Example usage for javax.swing SwingUtilities getAncestorOfClass

List of usage examples for javax.swing SwingUtilities getAncestorOfClass

Introduction

In this page you can find the example usage for javax.swing SwingUtilities getAncestorOfClass.

Prototype

public static Container getAncestorOfClass(Class<?> c, Component comp) 

Source Link

Document

Convenience method for searching above comp in the component hierarchy and returns the first object of class c it finds.

Usage

From source file:net.chaosserver.timelord.swingui.CommonTaskPanel.java

/**
 * Hides the application window out of site and mind on Win and Mac.
 *///  w  w  w.  j a v  a 2s  .  co  m
protected void hideFrame() {
    JFrame frame = (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, this);
    frame.toBack();

    // Use reflection for compile-time avoidance.
    try {
        Class<?> nsApplicationClass = Class.forName("com.apple.cocoa.application.NSApplication");
        Method sharedAppMethod = nsApplicationClass.getDeclaredMethod("sharedApplication", new Class<?>[] {});

        Object nsApplicationObject = sharedAppMethod.invoke(null, new Object[] {});

        /*
        Field userAttentionRequestCriticalField =
        nsApplicationClass.getDeclaredField(
            "UserAttentionRequestCritical");
        */

        Method hideMethod = nsApplicationClass.getDeclaredMethod("hide", new Class[] { Object.class });

        hideMethod.invoke(nsApplicationObject, new Object[] { nsApplicationObject });
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Issue bouncing dock", e);
        }
    }
}

From source file:com.sshtools.sshterm.SshTermSessionPanel.java

/**
 *
 *
 * @throws IOException//from  w  w  w .  j  a  v  a 2 s  .  c om
 */
public boolean onOpenSession() throws IOException {
    Window w = (Window) SwingUtilities.getAncestorOfClass(Window.class, SshTermSessionPanel.this);

    if (w != null) {
        w.toFront();
    }

    terminal.requestFocus();

    SshToolsConnectionProfile profile = getCurrentConnectionProfile();
    setTerminalProperties(profile);

    // We are now connected
    statusBar.setStatusText("Connected");
    statusBar.setConnected(true);

    this.setContainerTitle(null);
    //If the eol setting is EOL_DEFAULT, then use the
    // value guessed by j2ssh
    if (eol == TerminalEmulation.EOL_DEFAULT) {
        if (manager.getRemoteEOL() == TransportProtocolCommon.EOL_CRLF) {
            emulation.setEOL(TerminalEmulation.EOL_CR_LF);
        } else {
            emulation.setEOL(TerminalEmulation.EOL_CR);
        }
    }

    if (profile.getOnceAuthenticatedCommand() != SshToolsConnectionProfile.DO_NOTHING) {
        if (profile.getOnceAuthenticatedCommand() == SshToolsConnectionProfile.EXECUTE_COMMANDS) {
            BufferedReader reader = new BufferedReader(new StringReader(profile.getCommandsToExecute() + "\n"));
            String cmd;

            while ((cmd = reader.readLine()) != null) {
                if (cmd.trim().length() > 0) {
                    log.info("Executing " + cmd);
                    session = createNewSession(false);

                    if (session.executeCommand(cmd)) {
                        session.bindInputStream(emulation.getTerminalInputStream());
                        session.bindOutputStream(emulation.getTerminalOutputStream());

                        try {
                            session.getState().waitForState(ChannelState.CHANNEL_CLOSED);
                        } catch (InterruptedException ex) {
                            JOptionPane.showMessageDialog(this, "The command was interrupted!",
                                    "Interrupted Exception", JOptionPane.OK_OPTION);
                        }
                    }
                }
            }
        } else {
            // Start the users shell
            session = createNewSession(true);

            if (session.startShell()) {
                session.bindInputStream(emulation.getTerminalInputStream());
                session.bindOutputStream(emulation.getTerminalOutputStream());
            }
        }
    }

    // Set the connection status
    setAvailableActions();

    return true;
}

From source file:com.sshtools.common.ui.SshToolsApplicationClientPanel.java

/**
 *
 *
 * @param instance/*from   w w w . j  a va 2 s.  c om*/
 *
 * @return
 *
 * @throws IOException
 */
protected int showAuthenticationPrompt(SshAuthenticationClient instance)
        throws IOException, IllegalArgumentException {
    instance.setUsername(getCurrentConnectionProfile().getUsername());

    if (instance instanceof PasswordAuthenticationClient) {
        PasswordAuthenticationDialog dialog = new PasswordAuthenticationDialog(
                (Frame) SwingUtilities.getAncestorOfClass(Frame.class, SshToolsApplicationClientPanel.this));
        instance.setAuthenticationPrompt(dialog);
        ((PasswordAuthenticationClient) instance).setPasswordChangePrompt(PasswordChange.getInstance());
        PasswordChange.getInstance().setParentComponent(SshToolsApplicationClientPanel.this);
    } else if (instance instanceof PublicKeyAuthenticationClient) {
        PublicKeyAuthenticationPrompt prompt = new PublicKeyAuthenticationPrompt(
                SshToolsApplicationClientPanel.this);
        instance.setAuthenticationPrompt(prompt);
    } else if (instance instanceof KBIAuthenticationClient) {
        KBIAuthenticationClient kbi = new KBIAuthenticationClient();
        ((KBIAuthenticationClient) instance).setKBIRequestHandler(new KBIRequestHandlerDialog(
                (Frame) SwingUtilities.getAncestorOfClass(Frame.class, SshToolsApplicationClientPanel.this)));
    }
    return ssh.authenticate(instance, getCurrentConnectionProfile().getHost());
}

From source file:de.codesourcery.jasm16.utils.ASTInspector.java

public void centerCurrentLineInScrollPane() {
    final Container container = SwingUtilities.getAncestorOfClass(JViewport.class, editorPane);

    if (container == null) {
        return;/*ww  w . j  av a2  s. com*/
    }

    try {
        final Rectangle r = editorPane.modelToView(editorPane.getCaretPosition());
        final JViewport viewport = (JViewport) container;
        final int extentHeight = viewport.getExtentSize().height;
        final int viewHeight = viewport.getViewSize().height;

        int y = Math.max(0, r.y - (extentHeight / 2));
        y = Math.min(y, viewHeight - extentHeight);

        viewport.setViewPosition(new Point(0, y));
    } catch (BadLocationException ble) {
    }
}

From source file:com.isencia.passerelle.hmi.generic.GenericHMI.java

public JFrame getParentFrame() {

    // Container parentComponent = UIScrollPane.getParent();
    ////  ww w  .  j ava 2 s  .  c om
    // if (parentComponent != null) {
    // while (!(parentComponent instanceof JFrame)) {
    // parentComponent = parentComponent.getParent();
    // }
    //
    // parentFrame = (JFrame) parentComponent;
    // }
    parentFrame = (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, parameterScrollPane);
    return parentFrame;
}

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

/**
 * Create the context menu based on source component
 */// w w  w.  j a va 2s  . c o m
public void setupContextMenu(JPopupMenu menu, JComponent comp) {
    final CommonModuleFrame parentFrame = (CommonModuleFrame) SwingUtilities
            .getAncestorOfClass(CommonModuleFrame.class, comp);
    if (parentFrame != null) {
        final PhonUIAction toggleAlwaysOnTopAct = new PhonUIAction(parentFrame, "setAlwaysOnTop",
                !parentFrame.isAlwaysOnTop());
        toggleAlwaysOnTopAct.putValue(PhonUIAction.NAME, "Always on top");
        toggleAlwaysOnTopAct.putValue(PhonUIAction.SELECTED_KEY, parentFrame.isAlwaysOnTop());
        final JCheckBoxMenuItem toggleAlwaysOnTopItem = new JCheckBoxMenuItem(toggleAlwaysOnTopAct);
        menu.add(toggleAlwaysOnTopItem);
    }

    // button options first
    if (comp instanceof CellButton) {
        CellButton btn = (CellButton) comp;
        Cell cell = btn.cell;

        // copy to clipboard options
        String cellData = cell.getText().replaceAll("" + (char) 0x25cc, "");
        PhonUIAction copyToClipboardAct = new PhonUIAction(this, "onCopyToClipboard", cellData);
        copyToClipboardAct.putValue(PhonUIAction.NAME, "Copy character (" + cell.getText() + ")");
        JMenuItem copyToClipboardItem = new JMenuItem(copyToClipboardAct);
        menu.add(copyToClipboardItem);

        String htmlVal = new String();
        for (Character c : cellData.toCharArray()) {
            htmlVal += "&#" + (int) c + ";";
        }
        PhonUIAction copyHTMLToClipboardAct = new PhonUIAction(this, "onCopyToClipboard", htmlVal);
        copyHTMLToClipboardAct.putValue(PhonUIAction.NAME, "Copy as HTML (" + htmlVal + ")");
        JMenuItem copyHTMLToClipboardItem = new JMenuItem(copyHTMLToClipboardAct);
        menu.add(copyHTMLToClipboardItem);

        String hexVal = new String();
        for (Character c : cellData.toCharArray()) {
            hexVal += (hexVal.length() > 0 ? " " : "") + Integer.toHexString((int) c);
        }
        hexVal = hexVal.toUpperCase();
        PhonUIAction copyHEXToClipboardAct = new PhonUIAction(this, "onCopyToClipboard", hexVal);
        copyHEXToClipboardAct.putValue(PhonUIAction.NAME, "Copy as Unicode HEX (" + hexVal + ")");
        JMenuItem copyHEXToClipboardItem = new JMenuItem(copyHEXToClipboardAct);
        menu.add(copyHEXToClipboardItem);

        menu.addSeparator();
        if (isInFavorites(cell)) {
            PhonUIAction removeFromFavAct = new PhonUIAction(this, "onRemoveCellFromFavorites", cell);
            removeFromFavAct.putValue(Action.NAME, "Remove from favorites");
            removeFromFavAct.putValue(Action.SHORT_DESCRIPTION, "Remove button from list of favorites");
            JMenuItem removeFromFavItem = new JMenuItem(removeFromFavAct);
            menu.add(removeFromFavItem);
        } else {
            PhonUIAction addToFavAct = new PhonUIAction(this, "onAddCellToFavorites", cell);
            addToFavAct.putValue(Action.NAME, "Add to favorites");
            addToFavAct.putValue(Action.SHORT_DESCRIPTION, "Add button to list of favorites");
            JMenuItem addToFavItem = new JMenuItem(addToFavAct);
            menu.add(addToFavItem);
        }
        menu.addSeparator();
    }

    // section scroll-tos
    JMenuItem gotoTitleItem = new JMenuItem("Scroll to:");
    gotoTitleItem.setEnabled(false);
    menu.add(gotoTitleItem);

    for (JXButton toggleBtn : toggleButtons) {
        PhonUIAction gotoAct = new PhonUIAction(this, "onGoto", toggleBtn);
        gotoAct.putValue(Action.NAME, toggleBtn.getText());
        gotoAct.putValue(Action.SHORT_DESCRIPTION, "Scroll to " + toggleBtn.getText());
        JMenuItem gotoItem = new JMenuItem(gotoAct);
        menu.add(gotoItem);
    }

    menu.addSeparator();

    // setup font scaler
    final JLabel smallLbl = new JLabel("A");
    smallLbl.setFont(getFont().deriveFont(12.0f));
    smallLbl.setHorizontalAlignment(SwingConstants.CENTER);
    JLabel largeLbl = new JLabel("A");
    largeLbl.setFont(getFont().deriveFont(24.0f));
    largeLbl.setHorizontalAlignment(SwingConstants.CENTER);

    final JSlider scaleSlider = new JSlider(1, 101);
    scaleSlider.setValue((int) (scale * 100));
    scaleSlider.setMajorTickSpacing(20);
    scaleSlider.setMinorTickSpacing(10);
    scaleSlider.setSnapToTicks(true);
    scaleSlider.setPaintTicks(true);
    scaleSlider.addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent arg0) {
            int sliderVal = scaleSlider.getValue();

            float scale = (float) sliderVal / (float) 100;

            _cFont = null;

            setSavedScale(scale);
            setScale(scale);

        }
    });

    FormLayout scaleLayout = new FormLayout("3dlu, center:pref, fill:pref:grow, center:pref, 3dlu", "pref");
    CellConstraints cc = new CellConstraints();
    JPanel scalePanel = new JPanel(scaleLayout) {
        @Override
        public Insets getInsets() {
            Insets retVal = super.getInsets();

            retVal.left += UIManager.getIcon("Tree.collapsedIcon").getIconWidth();

            return retVal;
        }
    };
    scalePanel.add(smallLbl, cc.xy(2, 1));
    scalePanel.add(scaleSlider, cc.xy(3, 1));
    scalePanel.add(largeLbl, cc.xy(4, 1));

    JMenuItem scaleItem = new JMenuItem("Font size");
    scaleItem.setEnabled(false);
    menu.add(scaleItem);
    menu.add(scalePanel);

    menu.addSeparator();

    // highlighting
    PhonUIAction onToggleHighlightAct = new PhonUIAction(this, "onToggleHighlightRecent");
    onToggleHighlightAct.putValue(PhonUIAction.NAME, "Highlight recently used");
    onToggleHighlightAct.putValue(PhonUIAction.SELECTED_KEY, isHighlightRecent());
    JCheckBoxMenuItem onToggleHighlightItm = new JCheckBoxMenuItem(onToggleHighlightAct);
    menu.add(onToggleHighlightItm);
}

From source file:de.codesourcery.jasm16.ide.ui.views.SourceCodeView.java

public final void centerCurrentLineInScrollPane() {
    final Runnable r = new Runnable() {
        @Override/*from  w w  w.  j ava 2 s.co m*/
        public void run() {

            final Container container = SwingUtilities.getAncestorOfClass(JViewport.class, editorPane);

            if (container == null) {
                return;
            }

            try {
                final Rectangle r = editorPane.modelToView(editorPane.getCaretPosition());
                if (r == null) {
                    return;
                }
                final JViewport viewport = (JViewport) container;
                final int extentHeight = viewport.getExtentSize().height;
                final int viewHeight = viewport.getViewSize().height;

                int y = Math.max(0, r.y - (extentHeight / 2));
                y = Math.min(y, viewHeight - extentHeight);

                viewport.setViewPosition(new Point(0, y));
            } catch (BadLocationException ble) {
                LOG.error("centerCurrentLineInScrollPane(): ", ble);
            }
        }

    };

    UIUtils.invokeLater(r);
}

From source file:com.sshtools.sshterm.SshTerminalPanel.java

public boolean postConnection() {
    Window w = (Window) SwingUtilities.getAncestorOfClass(Window.class, SshTerminalPanel.this);

    if (w != null) {
        w.toFront();//from  ww w .j  a v a  2 s .c  o  m
    }

    terminal.requestFocus();

    return true;
}

From source file:org.apache.log4j.chainsaw.vfs.VFSLogFilePatternReceiver.java

/**
 * Read and process the log file.// ww w. j a  va  2  s.  c o  m
 */
public void activateOptions() {
    //we don't want to call super.activateOptions, but we do want active to be set to true
    active = true;
    //on receiver restart, only prompt for credentials if we don't already have them
    if (promptForUserInfo && getFileURL().indexOf("@") == -1) {
        /*
        if promptforuserinfo is true, wait for a reference to the container
        (via the VisualReceiver callback).
                
        We need to display a login dialog on top of the container, so we must then
        wait until the container has been added to a frame
        */

        //get a reference to the container
        new Thread(new Runnable() {
            public void run() {
                synchronized (waitForContainerLock) {
                    while (container == null) {
                        try {
                            waitForContainerLock.wait(1000);
                            getLogger().debug("waiting for setContainer call");
                        } catch (InterruptedException ie) {
                        }
                    }
                }

                Frame containerFrame1;
                if (container instanceof Frame) {
                    containerFrame1 = (Frame) container;
                } else {
                    synchronized (waitForContainerLock) {
                        //loop until the container has a frame
                        while ((containerFrame1 = (Frame) SwingUtilities.getAncestorOfClass(Frame.class,
                                container)) == null) {
                            try {
                                waitForContainerLock.wait(1000);
                                getLogger().debug("waiting for container's frame to be available");
                            } catch (InterruptedException ie) {
                            }
                        }
                    }
                }
                final Frame containerFrame = containerFrame1;
                //create the dialog
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        Frame owner = null;
                        if (container != null) {
                            owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, containerFrame);
                        }
                        final UserNamePasswordDialog f = new UserNamePasswordDialog(owner);
                        f.pack();
                        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
                        f.setLocation(d.width / 2, d.height / 2);
                        f.setVisible(true);
                        if (null == f.getUserName() || null == f.getPassword()) {
                            getLogger().info("Username and password not both provided, not using credentials");
                        } else {
                            String oldURL = getFileURL();
                            int index = oldURL.indexOf("://");
                            String firstPart = oldURL.substring(0, index);
                            String lastPart = oldURL.substring(index + "://".length());
                            setFileURL(firstPart + "://" + f.getUserName() + ":" + new String(f.getPassword())
                                    + "@" + lastPart);

                            setHost(oldURL.substring(0, index + "://".length()));
                            setPath(oldURL.substring(index + "://".length()));
                        }
                        vfsReader = new VFSReader();
                        new Thread(vfsReader).start();
                    }
                });
            }
        }).start();
    } else {
        //starts with protocol:/  but not protocol://
        String oldURL = getFileURL();
        if (oldURL != null && oldURL.indexOf(":/") > -1 && oldURL.indexOf("://") == -1) {
            int index = oldURL.indexOf(":/");
            String lastPart = oldURL.substring(index + ":/".length());
            int passEndIndex = lastPart.indexOf("@");
            if (passEndIndex > -1) { //we have a username/password
                setHost(oldURL.substring(0, index + ":/".length()));
                setPath(lastPart.substring(passEndIndex + 1));
            }
            vfsReader = new VFSReader();
            new Thread(vfsReader).start();
        } else if (oldURL != null && oldURL.indexOf("://") > -1) {
            //starts with protocol://
            int index = oldURL.indexOf("://");
            String lastPart = oldURL.substring(index + "://".length());
            int passEndIndex = lastPart.indexOf("@");
            if (passEndIndex > -1) { //we have a username/password
                setHost(oldURL.substring(0, index + "://".length()));
                setPath(lastPart.substring(passEndIndex + 1));
            }
            vfsReader = new VFSReader();
            new Thread(vfsReader).start();
        } else {
            getLogger().info("null URL - unable to parse file");
        }
    }
}

From source file:org.executequery.components.FileChooserDialog.java

protected JDialog createDialog(Component parent) throws HeadlessException {

    Frame frame = parent instanceof Frame ? (Frame) parent
            : (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);

    String title = getUI().getDialogTitle(this);

    JDialog dialog = new JDialog(frame, title, true);

    Container contentPane = dialog.getContentPane();
    contentPane.setLayout(new BorderLayout());
    contentPane.add(this, BorderLayout.CENTER);

    setPreferredSize(new Dimension(700, getPreferredSize().height));

    // add any custom panel
    if (customPanel != null) {
        contentPane.add(customPanel, BorderLayout.SOUTH);
    }/*from w w w . j  av a2s.c om*/

    if (JDialog.isDefaultLookAndFeelDecorated()) {
        boolean supportsWindowDecorations = UIManager.getLookAndFeel().getSupportsWindowDecorations();

        if (supportsWindowDecorations) {
            dialog.getRootPane().setWindowDecorationStyle(JRootPane.FILE_CHOOSER_DIALOG);
        }

    }

    setFileView(new DefaultFileView());
    dialog.pack();

    dialog.setLocation(GUIUtilities.getLocationForDialog(dialog.getSize()));
    return dialog;
}