Example usage for javax.swing JEditorPane JEditorPane

List of usage examples for javax.swing JEditorPane JEditorPane

Introduction

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

Prototype

public JEditorPane(String type, String text) 

Source Link

Document

Creates a JEditorPane that has been initialized to the given text.

Usage

From source file:de.jakop.ngcalsync.application.TrayStarter.java

private JFrame createAboutWindow() {
    final JFrame aboutWindow = new JFrame(UserMessage.get().TITLE_ABOUT_WINDOW());
    final JEditorPane textarea = new JEditorPane("text/html", getApplicationInformation()); //$NON-NLS-1$
    textarea.setEditable(false);/* w  w w  .  j a va  2  s  . c o m*/
    aboutWindow.getContentPane().add(new JScrollPane(textarea));
    aboutWindow.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
    aboutWindow.pack();
    aboutWindow.setSize(500, 400);
    return aboutWindow;
}

From source file:com.evanbelcher.DrillBook.display.DBMenuBar.java

/**
 * Displays about window.//w w w .  j  a v  a2 s . c  om
 */
private void about() {
    String msg = "<html>DrillBook " + State.VERSION
            + "<br>Created by Evan Belcher, 2016<br><a href=\"https://github.com/EbMinor3/DrillBook\">GitHub</a><br><a href=\"http://evanbelcher.com\">Website</a><br><br><a href=\"https://icons8.com\">Icon pack by Icons8</a></html>";
    JEditorPane editorPane = new JEditorPane("text/html", msg);
    editorPane.setEditable(false);
    editorPane.setBackground(new JLabel().getBackground());
    editorPane.addHyperlinkListener(e -> {
        if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
            try {
                Desktop.getDesktop().browse(e.getURL().toURI());
            } catch (IOException | URISyntaxException e1) {
                e1.printStackTrace();
            }
        }
    });

    if (!(Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE))) {
        editorPane.setContentType("text");
        editorPane.setText("DrillBook " + State.VERSION
                + "\nCreated by Evan Belcher, 2016\nGitHub: https://github.com/EbMinor3/DrillBook\nWebsite: http://evanbelcher.com\n\nIcon pack by Icons8: https://icons8.com");
    }

    JOptionPane.showMessageDialog(this, editorPane, "About", JOptionPane.PLAIN_MESSAGE);
}

From source file:edu.ku.brc.specify.config.init.secwiz.UserPanel.java

/**
 * /*from  ww w.  j  a  va 2  s. c  o  m*/
 */
protected void displayData() {
    StringBuilder sb = new StringBuilder();

    String[] headers = { "Username", "Passsword", "MasterKey", "Last Name", "First Name", "EMail",
            "New Password" };
    int i = 0;
    Object[][] pValueObjs = new Object[userModel.getUserData().size()][6];
    for (UserData ud : userModel.getUserData()) {
        pValueObjs[i++] = ud.getData();
    }

    /*for (Object[] row :pValueObjs)
    {
    sb.append("\n--------------------------------------\n");
    for (i=0;i<headers.length;i++)
    {
        sb.append(headers[i]);
        sb.append(": ");
        sb.append(row[i]);
        sb.append("\n");
    }
    }*/

    sb.append("<HTML><BODY><TABLE border=1><TR>");
    for (String hd : headers) {
        sb.append("<TH>");
        sb.append(hd);
        sb.append("</TH>");
    }
    sb.append("</TR>");
    for (Object[] row : pValueObjs) {
        sb.append("<TR>");
        for (i = 0; i < headers.length; i++) {
            sb.append("<TD>");
            sb.append(row[i] == null ? "&nbsp;" : row[i]);
            sb.append("</TD>");
        }
        sb.append("</TR>");
    }
    sb.append("</TABLE></BODY></HTML>");

    JEditorPane htmlPane = new JEditorPane("text/html", sb.toString()); //$NON-NLS-1$
    final JScrollPane scrollPane = UIHelper.createScrollPane(htmlPane);
    htmlPane.setEditable(false);

    JPanel p = new JPanel(new BorderLayout());
    p.add(scrollPane, BorderLayout.CENTER);
    p.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));

    CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getTopWindow(), "Summary", true, CustomDialog.OK_BTN,
            p);
    dlg.setOkLabel(UIRegistry.getResourceString("CLOSE"));
    dlg.createUI();
    dlg.setSize(dlg.getPreferredSize().width, 768);

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            scrollPane.getVerticalScrollBar().setValue(0);
        }
    });
    UIHelper.centerAndShow(dlg);
}

From source file:com.ejie.uda.jsonI18nEditor.Editor.java

public void showVersionDialog() {
    GithubReleaseData data = GithubRepoUtils.getLatestRelease(GITHUB_REPO);
    String content = "";
    if (data != null && !VERSION.equals(data.getTagName())) {
        content = MessageBundle.get("dialogs.version.new", data.getTagName()) + "<br>" + "<a href=\""
                + data.getHtmlUrl() + "\">" + MessageBundle.get("dialogs.version.link") + "</a>";
    } else {/*from   www .j  a  va 2s.  c o  m*/
        content = MessageBundle.get("dialogs.version.uptodate");
    }
    Font font = getFont();
    JEditorPane pane = new JEditorPane("text/html",
            "<html><body style=\"font-family:" + font.getFamily() + ";font-size:" + font.getSize()
                    + "pt;text-align:center;width:200px;\">" + content + "</body></html>");
    pane.addHyperlinkListener(e -> {
        if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
            try {
                Desktop.getDesktop().browse(e.getURL().toURI());
            } catch (Exception e1) {
                //
            }
        }
    });
    pane.setBackground(getBackground());
    pane.setEditable(false);
    showMessage(MessageBundle.get("dialogs.version.title"), pane);
}

From source file:net.minelord.gui.panes.IRCPane.java

public void startClient(final String nick) {
    IRCLog = new ArrayList<String>();
    SwingUtilities.invokeLater(new Runnable() {
        @Override//from   w w  w . j  a  v a  2 s  .c  om
        public void run() {
            text = new JEditorPane("text/html", "<HTML>");
            text.setEditable(false);
            kit = new HTMLEditorKit();
            text.setEditorKit(kit);
            client.connect("irc.liberty-unleashed.co.uk", "#moomoohk", nick, instance);
            scroller = new JScrollPane(text);
            text.setEditable(false);
            connect();
            scroller.setBounds(20, 20, 810, 250);
            add(scroller);
            input = new JTextField();
            input.setBounds(20, 270, 810, 30);
            Color bgColor = Color.gray.darker().darker();
            UIDefaults defaults = new UIDefaults();
            defaults.put("EditorPane[Enabled].backgroundPainter", bgColor);
            text.putClientProperty("Nimbus.Overrides", defaults);
            text.putClientProperty("Nimbus.Overrides.InheritDefaults", true);
            text.setBackground(bgColor);
            input.setBackground(Color.gray);
            input.setForeground(Color.gray.darker().darker().darker());
            input.setEnabled(false);
            text.addHyperlinkListener(new HyperlinkListener() {
                @Override
                public void hyperlinkUpdate(HyperlinkEvent event) {
                    if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                        if (event.getDescription().charAt(0) == '#') {
                            String[] params = { event.getDescription() };
                            IRCCommand.getCommand("/join").execute(client, params);
                        } else
                            OSUtils.browse(event.getURL().toString());
                    }
                }
            });
            text.addFocusListener(new FocusListener() {

                @Override
                public void focusLost(FocusEvent paramFocusEvent) {
                }

                @Override
                public void focusGained(FocusEvent paramFocusEvent) {
                    input.requestFocus();
                }
            });
            scroller.setViewportView(text);
            add(input);
            input.addKeyListener(new KeyListener() {

                @Override
                public void keyTyped(KeyEvent arg0) {
                }

                @Override
                public void keyReleased(KeyEvent arg0) {
                    if (arg0.getKeyCode() == 10) {
                        if (input.getText().length() > 0) {
                            lastCommandSelector = lastCommands.size();
                            lastCommands.add(input.getText());
                        }
                        sendMessage(input.getText());
                        input.setText("");
                    }
                    if (arg0.getKeyCode() == 27)
                        input.setText("");
                    if (arg0.getKeyCode() == 17) {
                        int before = input.getText().length();
                        if (input.getText().charAt(0) == '/') {
                            input.setText(completeNick(input.getText()));
                            input.select(
                                    input.getText().length() - completeNick(input.getText()).length() + before,
                                    input.getText().length());
                        } else {
                            input.setText(completeCommand(input.getText()));
                            input.select(input.getText().length() - completeCommand(input.getText()).length()
                                    + before, input.getText().length());
                        }
                    }
                    if (arg0.getKeyCode() == 38)
                        if (lastCommandSelector > 0) {
                            lastCommandSelector--;
                            input.setText(lastCommands.get(lastCommandSelector));
                        }
                    if (arg0.getKeyCode() == 40)
                        if (lastCommandSelector < lastCommands.size()) {
                            lastCommandSelector++;
                            if (lastCommandSelector == lastCommands.size())
                                input.setText("");
                            if (lastCommandSelector < lastCommands.size())
                                input.setText(lastCommands.get(lastCommandSelector));
                            return;
                        }
                }

                @Override
                public void keyPressed(KeyEvent arg0) {
                }
            });
        }
    });
}

From source file:edu.ku.brc.specify.config.FixDBAfterLogin.java

/**
 * /* www  . j a v  a  2s. com*/
 */
public static void fixUserPermissions(final boolean doSilently) {
    final String FIXED_USER_PERMS = "FIXED_USER_PERMS";
    boolean isAlreadyFixed = AppPreferences.getRemote().getBoolean(FIXED_USER_PERMS, false);
    if (isAlreadyFixed) {
        return;
    }

    String whereStr = " WHERE p.GroupSubClass = 'edu.ku.brc.af.auth.specify.principal.UserPrincipal' ";
    String whereStr2 = "AND p.userGroupScopeID IS NULL";

    String postSQL = " FROM specifyuser su "
            + "INNER JOIN specifyuser_spprincipal ss ON su.SpecifyUserID = ss.SpecifyUserID "
            + "INNER JOIN spprincipal p ON ss.SpPrincipalID = p.SpPrincipalID "
            + "LEFT JOIN spprincipal_sppermission pp ON p.SpPrincipalID = pp.SpPrincipalID "
            + "LEFT OUTER JOIN sppermission pm ON pp.SpPermissionID = pm.SpPermissionID " + whereStr;

    String sql = "SELECT COUNT(*)" + postSQL + whereStr2;
    log.debug(sql);
    if (BasicSQLUtils.getCountAsInt(sql) < 1) {
        sql = "SELECT COUNT(*)" + postSQL;
        log.debug(sql);
        if (BasicSQLUtils.getCountAsInt(sql) > 0) {
            return;
        }
    }

    final String updatePermSQL = "DELETE FROM %s WHERE SpPermissionID = %d";
    final String updatePrinSQL = "DELETE FROM %s WHERE SpPrincipalID = %d";

    sql = "SELECT p.SpPrincipalID, pp.SpPermissionID" + postSQL;
    log.debug(sql);

    HashSet<Integer> prinIds = new HashSet<Integer>();
    for (Object[] row : query(sql)) {
        Integer prinId = (Integer) row[0];
        if (prinId != null) {
            prinIds.add(prinId);
        }

        Integer permId = (Integer) row[1];
        if (permId != null) {
            update(String.format(updatePermSQL, "spprincipal_sppermission", permId));
            update(String.format(updatePermSQL, "sppermission", permId));
            log.debug("Removing PermId: " + permId);
        }
    }

    StringBuilder sb1 = new StringBuilder();
    for (Integer prinId : prinIds) {
        update(String.format(updatePrinSQL, "specifyuser_spprincipal", prinId));
        update(String.format(updatePrinSQL, "spprincipal", prinId));
        log.debug("Removing PrinId: " + prinId);
        if (sb1.length() > 0)
            sb1.append(",");
        sb1.append(prinId.toString());
    }
    log.debug("(" + sb1.toString() + ")");

    // Create all the necessary UperPrincipal records
    // Start by figuring out what group there are and then create one UserPrincipal record
    // for each one

    TreeSet<String> nameSet = new TreeSet<String>();
    sql = "SELECT su.Name, su.SpecifyUserID, p.userGroupScopeID, p.SpPrincipalID FROM specifyuser su "
            + "INNER JOIN specifyuser_spprincipal sp ON su.SpecifyUserID = sp.SpecifyUserID "
            + "INNER JOIN spprincipal p ON sp.SpPrincipalID = p.SpPrincipalID "
            + "WHERE p.GroupSubClass = 'edu.ku.brc.af.auth.specify.principal.GroupPrincipal'";

    String fields = "TimestampCreated, TimestampModified, Version, GroupSubClass, groupType, Name, Priority, Remarks, userGroupScopeID, CreatedByAgentID, ModifiedByAgentID";
    String insertSQL = "INSERT INTO spprincipal (" + fields + ") VALUES(?,?,?,?,?,?,?,?,?,?,?)";
    String insertSQL2 = "INSERT INTO specifyuser_spprincipal (SpecifyUserID, SpPrincipalID) VALUES(?,?)";

    String searchSql = "SELECT " + fields + " FROM spprincipal WHERE SpPrincipalID = ?";

    sb1 = new StringBuilder();

    PreparedStatement selStmt = null;
    PreparedStatement pStmt = null;
    PreparedStatement pStmt2 = null;
    try {
        Connection conn = DBConnection.getInstance().getConnection();

        pStmt = conn.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS);
        pStmt2 = conn.prepareStatement(insertSQL2);
        selStmt = conn.prepareStatement(searchSql);

        String adtSQL = "SELECT DISTINCT ca.AgentID FROM specifyuser AS su INNER Join agent AS ca ON su.CreatedByAgentID = ca.AgentID";
        Integer createdById = BasicSQLUtils.getCount(conn, adtSQL);
        if (createdById == null) {
            createdById = BasicSQLUtils.getCount(conn,
                    "SELECT AgentID FROM agent ORDER BY AgentID ASC LIMIT 0,1");
            if (createdById == null) {
                UIRegistry.showError("The permissions could not be fixed because there were no agents.");
                AppPreferences.shutdownAllPrefs();
                DBConnection.shutdownFinalConnection(true, true);
                return;
            }
        }

        for (Object[] row : query(sql)) {
            String usrName = (String) row[0];
            Integer userId = (Integer) row[1];
            Integer collId = (Integer) row[2];
            Integer prinId = (Integer) row[3];

            nameSet.add(usrName);

            log.debug("usrName: " + usrName + "  prinId: " + prinId);
            if (sb1.length() > 0)
                sb1.append(",");
            sb1.append(prinId.toString());

            selStmt.setInt(1, prinId);
            ResultSet rs = selStmt.executeQuery();
            if (rs.next()) {
                log.debug(String.format("%s - adding UserPrincipal for Collection  %d / %d", usrName,
                        rs.getInt(9), collId));
                Integer createdByAgentID = (Integer) rs.getObject(10);
                Integer modifiedByAgentID = (Integer) rs.getObject(11);

                pStmt.setTimestamp(1, rs.getTimestamp(1));
                pStmt.setTimestamp(2, rs.getTimestamp(2));
                pStmt.setInt(3, 1); // Version
                pStmt.setString(4, "edu.ku.brc.af.auth.specify.principal.UserPrincipal"); // GroupSubClass
                pStmt.setString(5, null); // groupType
                pStmt.setString(6, rs.getString(6)); // Name
                pStmt.setInt(7, 80); // Priority
                pStmt.setString(8, rs.getString(8)); // Remarks
                pStmt.setInt(9, rs.getInt(9)); // userGroupScopeID
                pStmt.setInt(10, createdByAgentID != null ? createdByAgentID : createdById);
                pStmt.setInt(11, modifiedByAgentID != null ? modifiedByAgentID : createdById);

                // Create UserPrincipal
                pStmt.executeUpdate();

                int newPrinId = BasicSQLUtils.getInsertedId(pStmt);

                // Join the new Principal to the SpecifyUser record
                pStmt2.setInt(1, userId);
                pStmt2.setInt(2, newPrinId);
                pStmt2.executeUpdate();

            } else {
                // error
            }
            rs.close();
        }

        log.debug("(" + sb1.toString() + ")");

        AppPreferences.getRemote().putBoolean(FIXED_USER_PERMS, true);

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (pStmt != null)
                pStmt.close();
            if (pStmt2 != null)
                pStmt2.close();
            if (selStmt != null)
                selStmt.close();
        } catch (Exception ex) {
        }
    }

    final StringBuilder sb = new StringBuilder();
    for (String nm : nameSet) {
        if (sb.length() > 0)
            sb.append('\n');
        sb.append(nm);
    }

    if (!doSilently) {
        JTextArea ta = UIHelper.createTextArea(15, 30);
        ta.setText(sb.toString());
        ta.setEditable(false);

        JEditorPane htmlPane = new JEditorPane("text/html", //$NON-NLS-1$
                UIRegistry.getResourceString("FDBAL_PERMFIXEDDESC"));
        htmlPane.setEditable(false);
        htmlPane.setOpaque(false);

        CellConstraints cc = new CellConstraints();
        PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "p:g,8px,f:p:g"));
        pb.add(htmlPane, cc.xy(1, 1));
        pb.add(UIHelper.createScrollPane(ta), cc.xy(1, 3));
        pb.setDefaultDialogBorder();

        CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getMostRecentWindow(),
                UIRegistry.getResourceString("FDBAL_PERMFIXED"), true, CustomDialog.OK_BTN, pb.getPanel());
        dlg.setOkLabel(UIRegistry.getResourceString("CLOSE"));
        UIHelper.centerAndShow(dlg);
    }
}

From source file:edu.ku.brc.specify.ui.AppBase.java

/**
 * Shows the About dialog.//w ww  .j a v a2 s .  c o m
 */
public void doAbout() {
    AppContextMgr acm = AppContextMgr.getInstance();
    boolean hasContext = acm.hasContext();

    int baseNumRows = 9;
    String serverName = AppPreferences.getLocalPrefs().get("login.servers_selected", null);
    if (serverName != null) {
        baseNumRows++;
    }

    CellConstraints cc = new CellConstraints();
    PanelBuilder infoPB = new PanelBuilder(new FormLayout("p,6px,f:p:g",
            "p,4px,p,4px," + UIHelper.createDuplicateJGoodiesDef("p", "2px", baseNumRows)));

    JLabel iconLabel = new JLabel(IconManager.getIcon("SpecifyLargeIcon"), SwingConstants.CENTER); //$NON-NLS-1$
    PanelBuilder iconPB = new PanelBuilder(new FormLayout("p", "20px,t:p,f:p:g"));
    iconPB.add(iconLabel, cc.xy(1, 2));

    if (hasContext) {
        DBTableIdMgr tableMgr = DBTableIdMgr.getInstance();
        boolean hasReged = !RegisterSpecify.isAnonymous() && RegisterSpecify.hasInstitutionRegistered();

        int y = 1;
        infoPB.addSeparator(getResourceString("Specify.SYS_INFO"), cc.xyw(1, y, 3));
        y += 2;

        JLabel lbl = UIHelper.createLabel(databaseName);
        infoPB.add(UIHelper.createI18NFormLabel("Specify.DB"), cc.xy(1, y));
        infoPB.add(lbl, cc.xy(3, y));
        y += 2;
        lbl.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    openLocalPrefs();
                }
            }
        });

        infoPB.add(UIHelper.createFormLabel(tableMgr.getTitleForId(Institution.getClassTableId())),
                cc.xy(1, y));
        infoPB.add(lbl = UIHelper.createLabel(acm.getClassObject(Institution.class).getName()), cc.xy(3, y));
        y += 2;
        lbl.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    openRemotePrefs();
                }
            }
        });
        infoPB.add(UIHelper.createFormLabel(tableMgr.getTitleForId(Division.getClassTableId())), cc.xy(1, y));
        infoPB.add(UIHelper.createLabel(acm.getClassObject(Division.class).getName()), cc.xy(3, y));
        y += 2;

        infoPB.add(UIHelper.createFormLabel(tableMgr.getTitleForId(Discipline.getClassTableId())), cc.xy(1, y));
        infoPB.add(UIHelper.createLabel(acm.getClassObject(Discipline.class).getName()), cc.xy(3, y));
        y += 2;

        infoPB.add(UIHelper.createFormLabel(tableMgr.getTitleForId(Collection.getClassTableId())), cc.xy(1, y));
        infoPB.add(UIHelper.createLabel(acm.getClassObject(Collection.class).getCollectionName()), cc.xy(3, y));
        y += 2;

        infoPB.add(UIHelper.createI18NFormLabel("Specify.BLD"), cc.xy(1, y));
        infoPB.add(UIHelper.createLabel(appBuildVersion), cc.xy(3, y));
        y += 2;

        infoPB.add(UIHelper.createI18NFormLabel("Specify.REG"), cc.xy(1, y));
        infoPB.add(UIHelper.createI18NLabel(hasReged ? "Specify.HASREG" : "Specify.NOTREG"), cc.xy(3, y));
        y += 2;

        String isaNumber = RegisterSpecify.getISANumber();
        infoPB.add(UIHelper.createI18NFormLabel("Specify.ISANUM"), cc.xy(1, y));
        infoPB.add(UIHelper.createLabel(StringUtils.isNotEmpty(isaNumber) ? isaNumber : ""), cc.xy(3, y));
        y += 2;

        if (serverName != null) {
            infoPB.add(UIHelper.createI18NFormLabel("Specify.SERVER"), cc.xy(1, y));
            infoPB.add(UIHelper.createLabel(StringUtils.isNotEmpty(serverName) ? serverName : ""), cc.xy(3, y));
            y += 2;
        }

        if (StringUtils.contains(DBConnection.getInstance().getConnectionStr(), "mysql")) {
            Vector<Object[]> list = BasicSQLUtils.query("select version() as ve");
            if (list != null && list.size() > 0) {
                infoPB.add(UIHelper.createFormLabel("MySQL Version"), cc.xy(1, y));
                infoPB.add(UIHelper.createLabel(list.get(0)[0].toString()), cc.xy(3, y));
                y += 2;
            }
        }

        infoPB.add(UIHelper.createFormLabel("Java Version"), cc.xy(1, y));
        infoPB.add(UIHelper.createLabel(System.getProperty("java.version")), cc.xy(3, y));
        y += 2;
    }

    String txt = getAboutText(appName, appVersion);
    JLabel txtLbl = createLabel(txt);
    txtLbl.setFont(UIRegistry.getDefaultFont());

    final JEditorPane txtPane = new JEditorPane("text/html", txt);
    txtPane.setEditable(false);
    txtPane.setBackground(new JPanel().getBackground());

    PanelBuilder pb = new PanelBuilder(new FormLayout("p,20px,f:min(400px;p):g,10px,8px,10px,p:g", "f:p:g"));

    pb.add(iconPB.getPanel(), cc.xy(1, 1));
    pb.add(txtPane, cc.xy(3, 1));
    Color bg = getBackground();

    if (hasContext) {
        pb.add(new VerticalSeparator(bg.darker(), bg.brighter()), cc.xy(5, 1));
        pb.add(infoPB.getPanel(), cc.xy(7, 1));
    }

    pb.setDefaultDialogBorder();

    String title = getResourceString("Specify.ABOUT");//$NON-NLS-1$
    CustomDialog aboutDlg = new CustomDialog(topFrame, title + " " + appName, true, CustomDialog.OK_BTN, //$NON-NLS-1$
            pb.getPanel());
    String okLabel = getResourceString("Specify.CLOSE");//$NON-NLS-1$
    aboutDlg.setOkLabel(okLabel);

    aboutDlg.createUI();
    aboutDlg.pack();

    // for some strange reason I can't get the dialog to size itself correctly
    Dimension size = aboutDlg.getSize();
    size.height += 120;
    aboutDlg.setSize(size);

    txtPane.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent event) {
            if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                try {
                    AttachmentUtils.openURI(event.getURL().toURI());

                } catch (Exception e) {
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                }
            }
        }
    });

    UIHelper.centerAndShow(aboutDlg);
}

From source file:com.pironet.tda.TDA.java

/**
 * add a tree listener for enabling/disabling menu and toolbar ICONS.
 *
 * @param tree JTree//from  w  ww  . j a v  a2 s  .  c  om
 */
private void addTreeListener(JTree tree) {
    tree.addTreeSelectionListener(new TreeSelectionListener() {
        ViewScrollPane emptyView = null;

        public void valueChanged(TreeSelectionEvent e) {
            getMainMenu().getCloseMenuItem().setEnabled(e.getPath() != null);
            if (getMainMenu().getCloseToolBarButton() != null) {
                getMainMenu().getCloseToolBarButton().setEnabled(e.getPath() != null);
            }
            // reset right pane of the top view:

            if (emptyView == null) {
                JEditorPane emptyPane = new JEditorPane("text/html",
                        "<html><body bgcolor=\"ffffff\"></body></html>");
                emptyPane.setEditable(false);
                emptyPane.setSize(Const.EMPTY_DIMENSION);

                emptyView = new ViewScrollPane(emptyPane, runningAsVisualVMPlugin);
            }

            if (e.getPath() == null || !(((DefaultMutableTreeNode) e.getPath().getLastPathComponent())
                    .getUserObject() instanceof Category)) {
                resetPane();
            }
        }

        private void resetPane() {
            final Rectangle bounds = topSplitPane.getBounds();
            final int width = bounds.width;
            int dividerLocation = topSplitPane.getDividerLocation();
            if (width - dividerLocation < Const.MIN_RIGHT_PANE_SIZE
                    && width - Const.MIN_RIGHT_PANE_SIZE > 300) {
                dividerLocation = width - Const.MIN_RIGHT_PANE_SIZE;
            }
            topSplitPane.setRightComponent(emptyView);
            topSplitPane.setDividerLocation(dividerLocation);
        }

    });
}

From source file:userinterface.properties.GUIGraphHandler.java

public void plotNewFunction() {

    JDialog dialog;/*from www . ja  v a 2  s  .co m*/
    JRadioButton radio2d, radio3d, newGraph, existingGraph;
    JTextField functionField, seriesName;
    JButton ok, cancel;
    JComboBox<String> chartOptions;
    JLabel example;

    //init all the fields of the dialog
    dialog = new JDialog(GUIPrism.getGUI());
    radio2d = new JRadioButton("2D");
    radio3d = new JRadioButton("3D");
    newGraph = new JRadioButton("New Graph");
    existingGraph = new JRadioButton("Exisiting");
    chartOptions = new JComboBox<String>();
    functionField = new JTextField();
    ok = new JButton("Plot");
    cancel = new JButton("Cancel");
    seriesName = new JTextField();
    example = new JLabel("<html><font size=3 color=red>Example:</font><font size=3>x/2 + 5</font></html>");
    example.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseEntered(MouseEvent e) {
            example.setCursor(new Cursor(Cursor.HAND_CURSOR));
            example.setForeground(Color.BLUE);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            example.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            example.setForeground(Color.BLACK);
        }

        @Override
        public void mouseClicked(MouseEvent e) {

            if (e.getButton() == MouseEvent.BUTTON1) {

                if (radio2d.isSelected()) {
                    functionField.setText("x/2 + 5");
                } else {
                    functionField.setText("x+y+5");
                }

                functionField.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
                functionField.setForeground(Color.BLACK);

            }
        }

    });

    //set dialog properties
    dialog.setSize(400, 350);
    dialog.setTitle("Plot a new function");
    dialog.setModal(true);
    dialog.setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS));
    dialog.setLocationRelativeTo(GUIPrism.getGUI());

    //add every component to their dedicated panels
    JPanel graphTypePanel = new JPanel(new FlowLayout());
    graphTypePanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Function type"));
    graphTypePanel.add(radio2d);
    graphTypePanel.add(radio3d);

    JPanel functionFieldPanel = new JPanel(new BorderLayout());
    functionFieldPanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Function"));
    functionFieldPanel.add(functionField, BorderLayout.CENTER);
    functionFieldPanel.add(example, BorderLayout.SOUTH);

    JPanel chartSelectPanel = new JPanel();
    chartSelectPanel.setLayout(new BoxLayout(chartSelectPanel, BoxLayout.Y_AXIS));
    chartSelectPanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Plot function to"));
    JPanel radioPlotPanel = new JPanel(new FlowLayout());
    radioPlotPanel.add(newGraph);
    radioPlotPanel.add(existingGraph);
    JPanel chartOptionsPanel = new JPanel(new FlowLayout());
    chartOptionsPanel.add(chartOptions);
    chartSelectPanel.add(radioPlotPanel);
    chartSelectPanel.add(chartOptionsPanel);

    JPanel bottomControlPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    bottomControlPanel.add(ok);
    bottomControlPanel.add(cancel);

    JPanel seriesNamePanel = new JPanel(new BorderLayout());
    seriesNamePanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Series name"));
    seriesNamePanel.add(seriesName, BorderLayout.CENTER);

    // add all the panels to the dialog

    dialog.add(graphTypePanel);
    dialog.add(functionFieldPanel);
    dialog.add(chartSelectPanel);
    dialog.add(seriesNamePanel);
    dialog.add(bottomControlPanel);

    // do all the enables and set properties

    radio2d.setSelected(true);
    newGraph.setSelected(true);
    chartOptions.setEnabled(false);
    functionField.setText("Add function expression here....");
    functionField.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 15));
    functionField.setForeground(Color.GRAY);
    seriesName.setText("New function");
    ok.setMnemonic('P');
    cancel.setMnemonic('C');
    example.setToolTipText("click to try out");

    ok.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ok");
    ok.getActionMap().put("ok", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            ok.doClick();
        }
    });

    cancel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
            "cancel");
    cancel.getActionMap().put("cancel", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            cancel.doClick();
        }
    });

    boolean found = false;

    for (int i = 0; i < theTabs.getTabCount(); i++) {

        if (theTabs.getComponentAt(i) instanceof Graph) {
            chartOptions.addItem(getGraphName(i));
            found = true;
        }
    }

    if (!found) {

        existingGraph.setEnabled(false);
        chartOptions.setEnabled(false);
    }

    //add all the action listeners

    radio2d.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (radio2d.isSelected()) {

                radio3d.setSelected(false);

                if (chartOptions.getItemCount() > 0) {
                    existingGraph.setEnabled(true);
                    chartOptions.setEnabled(true);
                }

                example.setText(
                        "<html><font size=3 color=red>Example:</font><font size=3>x/2 + 5</font></html>");
            }
        }
    });

    radio3d.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (radio3d.isSelected()) {

                radio2d.setSelected(false);
                newGraph.setSelected(true);
                existingGraph.setEnabled(false);
                chartOptions.setEnabled(false);
                example.setText("<html><font size=3 color=red>Example:</font><font size=3>x+y+5</font></html>");

            }

        }
    });

    newGraph.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (newGraph.isSelected()) {
                existingGraph.setSelected(false);
                chartOptions.setEnabled(false);
            }
        }
    });

    existingGraph.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (existingGraph.isSelected()) {

                newGraph.setSelected(false);
                chartOptions.setEnabled(true);
            }
        }
    });

    ok.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            String function = functionField.getText();

            Expression expr = null;

            try {

                expr = GUIPrism.getGUI().getPrism().parseSingleExpressionString(function);
                expr = (Expression) expr.accept(new ASTTraverseModify() {

                    @Override
                    public Object visit(ExpressionIdent e) throws PrismLangException {
                        return new ExpressionConstant(e.getName(), TypeDouble.getInstance());
                    }

                });

                expr.typeCheck();
                expr.semanticCheck();

            } catch (PrismLangException e1) {

                // for copying style
                JLabel label = new JLabel();

                // html content in our case the error we want to show
                JEditorPane ep = new JEditorPane("text/html",
                        "<html> There was an error parsing the function. To read about what built-in"
                                + " functions are supported <br>and some more information on the functions, visit "
                                + "<a href='http://www.prismmodelchecker.org/manual/ThePRISMLanguage/Expressions'>Prism expressions site</a>."
                                + "<br><br><font color=red>Error: </font>" + e1.getMessage() + " </html>");

                // handle link events
                ep.addHyperlinkListener(new HyperlinkListener() {
                    @Override
                    public void hyperlinkUpdate(HyperlinkEvent e) {
                        if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
                            try {
                                Desktop.getDesktop().browse(e.getURL().toURI());
                            } catch (IOException | URISyntaxException e1) {

                                e1.printStackTrace();
                            }
                        }
                    }
                });
                ep.setEditable(false);
                ep.setBackground(label.getBackground());

                // show the error dialog
                JOptionPane.showMessageDialog(dialog, ep, "Parse Error", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (radio2d.isSelected()) {

                ParametricGraph graph = null;

                if (newGraph.isSelected()) {

                    graph = new ParametricGraph("");
                } else {

                    for (int i = 0; i < theTabs.getComponentCount(); i++) {

                        if (theTabs.getTitleAt(i).equals(chartOptions.getSelectedItem())) {

                            graph = (ParametricGraph) theTabs.getComponent(i);
                        }
                    }

                }

                dialog.dispose();
                defineConstantsAndPlot(expr, graph, seriesName.getText(), newGraph.isSelected(), true);

            } else if (radio3d.isSelected()) {

                try {

                    expr = (Expression) expr.accept(new ASTTraverseModify() {
                        @Override
                        public Object visit(ExpressionIdent e) throws PrismLangException {
                            return new ExpressionConstant(e.getName(), TypeDouble.getInstance());
                        }

                    });

                    expr.semanticCheck();
                    expr.typeCheck();

                } catch (PrismLangException e1) {
                    e1.printStackTrace();
                }

                if (expr.getAllConstants().size() < 2) {

                    JOptionPane.showMessageDialog(dialog,
                            "There are not enough variables in the function to plot a 3D chart!", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // its always a new graph
                ParametricGraph3D graph = new ParametricGraph3D(expr);
                dialog.dispose();
                defineConstantsAndPlot(expr, graph, seriesName.getText(), true, false);
            }

            dialog.dispose();
        }
    });

    cancel.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialog.dispose();
        }
    });

    // we will show info about the function when field is out of focus
    functionField.addFocusListener(new FocusListener() {

        @Override
        public void focusLost(FocusEvent e) {

            if (!functionField.getText().equals("")) {
                return;
            }

            functionField.setText("Add function expression here....");
            functionField.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 15));
            functionField.setForeground(Color.GRAY);
        }

        @Override
        public void focusGained(FocusEvent e) {

            if (!functionField.getText().equals("Add function expression here....")) {
                return;
            }

            functionField.setForeground(Color.BLACK);
            functionField.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
            functionField.setText("");
        }
    });

    // show the dialog
    dialog.setVisible(true);
}

From source file:net.panthema.BispanningGame.GamePanel.java

public void addPopupActions(JPopupMenu popup) {

    popup.add(new AbstractAction("Center Graph") {
        private static final long serialVersionUID = 571719411574657791L;

        public void actionPerformed(ActionEvent e) {
            centerAndScaleGraph();/* www .j ava2 s.  c  o  m*/
        }
    });

    popup.add(new AbstractAction("Relayout Graph") {
        private static final long serialVersionUID = 571719411573657791L;

        public void actionPerformed(ActionEvent e) {
            relayoutGraph();
        }
    });

    popup.add(new AbstractAction("Reset Board Colors") {
        private static final long serialVersionUID = 571719411573657796L;

        public void actionPerformed(ActionEvent e) {
            mGraph.updateOriginalColor();
            mTurnNum = 0;
            putLog("Resetting game graph's colors.");
            updateGraphMessage();
            mVV.repaint();
        }
    });

    popup.add(new AbstractAction(
            allowFreeExchange ? "Restrict to Unique Exchanges" : "Allow Free Edge Exchanges") {
        private static final long serialVersionUID = 571719411573657798L;

        public void actionPerformed(ActionEvent e) {
            allowFreeExchange = !allowFreeExchange;
            mVV.repaint();
        }
    });

    popup.add(new AbstractAction((mAutoPlayBob ? "Disable" : "Enable") + " Autoplay of Bob's Moves") {
        private static final long serialVersionUID = 571719413573657798L;

        public void actionPerformed(ActionEvent e) {
            mAutoPlayBob = !mAutoPlayBob;
        }
    });

    popup.addSeparator();

    JMenu newGraph = new JMenu("New Random Graph");
    for (int i = 0; i < actionRandomGraph.length; ++i) {
        if (actionRandomGraph[i] != null)
            newGraph.add(actionRandomGraph[i]);
    }
    newGraph.addSeparator();
    newGraph.add(getActionNewGraphType());
    popup.add(newGraph);

    JMenu newNamedGraph = new JMenu("New Named Graph");
    for (int i = 0; i < actionNamedGraph.size(); ++i) {
        if (actionNamedGraph.get(i) != null)
            newNamedGraph.add(actionNamedGraph.get(i));
    }
    popup.add(newNamedGraph);

    popup.add(new AbstractAction("Show GraphString") {
        private static final long serialVersionUID = 545719411573657792L;

        public void actionPerformed(ActionEvent e) {
            JEditorPane text = new JEditorPane("text/plain",
                    GraphString.write_graph(mGraph, mVV.getModel().getGraphLayout()));
            text.setEditable(false);
            text.setPreferredSize(new Dimension(300, 125));
            JOptionPane.showMessageDialog(null, text, "GraphString Serialization",
                    JOptionPane.INFORMATION_MESSAGE);
        }
    });

    popup.add(new AbstractAction("Load GraphString") {
        private static final long serialVersionUID = 8636579131902717983L;

        public void actionPerformed(ActionEvent e) {
            String input = JOptionPane.showInputDialog(null, "Enter GraphString:", "");
            if (input == null)
                return;
            loadGraphString(input);
        }
    });

    popup.add(new AbstractAction("Show graph6") {
        private static final long serialVersionUID = 571719411573657792L;

        public void actionPerformed(ActionEvent e) {
            JTextArea text = new JTextArea(Graph6.write_graph6(mGraph));
            JOptionPane.showMessageDialog(null, text, "graph6 Serialization", JOptionPane.INFORMATION_MESSAGE);
        }
    });

    popup.add(new AbstractAction("Load graph6/sparse6") {
        private static final long serialVersionUID = 571719411573657792L;

        public void actionPerformed(ActionEvent e) {
            String input = JOptionPane.showInputDialog(null, "Enter graph6/sparse6 string:", "");
            if (input == null)
                return;
            MyGraph g = Graph6.read_graph6(input);
            setNewGraph(g);
        }
    });

    popup.add(new AbstractAction("Read GraphML") {
        private static final long serialVersionUID = 571719411573657794L;

        public void actionPerformed(ActionEvent e) {
            try {
                readGraphML();
            } catch (IOException e1) {
                showStackTrace(e1);
            } catch (GraphIOException e1) {
                showStackTrace(e1);
            }
        }
    });

    popup.add(new AbstractAction("Write GraphML") {
        private static final long serialVersionUID = 571719411573657795L;

        public void actionPerformed(ActionEvent e) {
            try {
                writeGraphML();
            } catch (IOException e1) {
                showStackTrace(e1);
            }
        }
    });

    popup.add(new AbstractAction("Write PDF") {
        private static final long serialVersionUID = 571719411573657793L;

        public void actionPerformed(ActionEvent e) {
            try {
                writePdf();
            } catch (FileNotFoundException e1) {
                showStackTrace(e1);
            } catch (DocumentException de) {
                System.err.println(de.getMessage());
            }
        }
    });
}