Example usage for javax.swing JMenuItem getText

List of usage examples for javax.swing JMenuItem getText

Introduction

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

Prototype

public String getText() 

Source Link

Document

Returns the button's text.

Usage

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

/**
 * Disables most menu items//from   w w w  .j  a  va  2  s .c om
 */
public void disableMost() {
    //      for (Component component : getComponents()) {
    //         if (component instanceof JMenu && ((JMenu) component).getText().equals("Settings")) {
    //            for (Component menuComponent : ((JMenu) component).getMenuComponents()) {
    //               if (!(menuComponent instanceof JMenuItem) || (!((JMenuItem) menuComponent).getText().equals("Toggle Gridlines") && !((JMenuItem) menuComponent).getText().equals("Toggle Dot Names")))
    //                  menuComponent.setEnabled(false);
    //            }
    //         } else {
    //            component.setEnabled(false);
    //         }
    //      }
    for (Component component : getComponents()) {
        if (component instanceof JMenu) {
            boolean enabled = false;
            for (Component menuComponent : ((JMenu) component).getMenuComponents()) {
                JMenuItem menuItem = (JMenuItem) menuComponent;
                switch (menuItem.getText()) {
                case "Quit":
                case "Toggle Gridlines":
                case "Toggle Dot Names":
                case "Help":
                case "About":
                    enabled = true;
                    break;
                default:
                    menuItem.setEnabled(false);
                }
            }
            if (!enabled)
                component.setEnabled(false);
        } else
            component.setEnabled(false);
    }
}

From source file:com.gele.tools.wow.wdbearmanager.WDBearManager.java

public void actionPerformed(ActionEvent arg0) {
    JMenuItem source = (JMenuItem) (arg0.getSource());

    if (source.getText().equals(MENU_ABOUT)) {
        JOptionPane.showMessageDialog(this, WDBearManager.VERSION_INFO + "\n" + "by kizura\n"
                + WDBearManager.EMAIL + "\n\n" + "\n" + "Supports any WDB version\n" + "\n" + "Thanks to:\n"
                + "DarkMan for testing,\n" + "John for the 1.10 specs, Annunaki for helping with the header,\n"
                + "Andrikos for the 1.6.x WDB specs, Pyro's WDBViewer, WDDG Forum,\n"
                + "blizzhackers, etc etc\n\n" + "This program uses: \n"
                + "JGoodies from http://www.jgoodies.com/\n" + "Hypersonic SQL database 1.7.3\n"
                + "Apache Log4J, Xerces\n" + "Jakarta Commons Logging and CLI\n" + "Castor from ExoLab\n"
                + "MySQL JDBC connector 3.1.7\n" + "HTTPUNIT from Russell Gold\n" + "Jython 2.1\n"
                + "Refer to directory 'licenses' for more details about the software used\n" + "PLEASE:\n"
                + "If you like this program and find it usefull:\n"
                + "Please donate money to a charity oranization of your choice.\n"
                + "I recommend any organization that fights cancer.\n\n" + "License:\n"
                + "WDBearMgr is placed under the GNU GPL. \n" + "For further information, see the page :\n"
                + "http://www.gnu.org/copyleft/gpl.html.\n" + "See licenses/GPL_license.html\n" + "\n"
                + "For a different license please contact the author.", "Info " + VERSION_INFO,
                JOptionPane.INFORMATION_MESSAGE);
        return;//from   w  w  w .j  a va 2  s .  c om
    } else if (source.getText().equals(MENU_HELP)) {
        JFrame myFrame = new JFrame("doc/html/index.html");
        //myFrame.setFont(   );
        URL urlHTML = null;
        try {
            JEditorPane htmlPane = new JEditorPane();
            //htmlPane.setFont(sourceFont);
            // .out.println("/scripts/"+source.getName()+".py");
            File scriptFile = new File("doc/html/index.html");
            urlHTML = scriptFile.toURL();//this.getClass().getResource("/scripts/"+source.getName()+".py");
            //          .out.println( urlHTML );
            //          .out.println( urlHTML.toExternalForm() );
            htmlPane.setPage(urlHTML);
            htmlPane.setEditable(false);
            JEPyperlinkListener myJEPHL = new JEPyperlinkListener(htmlPane);
            htmlPane.addHyperlinkListener(myJEPHL);
            myFrame.getContentPane().add(new JScrollPane(htmlPane));
            myFrame.pack();
            myFrame.setSize(640, 480);
            myFrame.show();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this,
                    VERSION_INFO + "\n" + "by kizura\n" + WDBearManager.EMAIL + "\n\n"
                            + "Could not open 'doc/html/index.html'",
                    "Warning " + VERSION_INFO, JOptionPane.WARNING_MESSAGE);
        }
    } else if (source.getText().equals(MENU_JDOCS)) {
        JFrame myFrame = new JFrame("doc/javadoc/index.html");
        //myFrame.setFont(   );
        URL urlHTML = null;
        try {
            JEditorPane htmlPane = new JEditorPane();
            //htmlPane.setFont(sourceFont);
            // .out.println("/scripts/"+source.getName()+".py");
            File scriptFile = new File("doc/javadoc/index.html");
            urlHTML = scriptFile.toURL();
            htmlPane.setPage(urlHTML);
            htmlPane.setEditable(false);
            JEPyperlinkListener myJEPHL = new JEPyperlinkListener(htmlPane);
            htmlPane.addHyperlinkListener(myJEPHL);
            myFrame.getContentPane().add(new JScrollPane(htmlPane));
            myFrame.pack();
            myFrame.setSize(640, 480);
            myFrame.show();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this,
                    VERSION_INFO + "\n" + "by kizura\n" + WDBearManager.EMAIL + "\n\n"
                            + "Could not open 'doc/javadoc/index.html'",
                    "Warning " + VERSION_INFO, JOptionPane.WARNING_MESSAGE);
        }
    } else if (source.getText().equals(MENU_CHECKUPDATE)) {
        Properties dbProps = null;
        String filName = PROPS_CHECK_UPDATE;
        try {
            dbProps = ReadPropertiesFile.readProperties(filName);
            String updFile = dbProps.getProperty(KEY_UPD_FILE);
            if (updFile == null) {
                JOptionPane.showMessageDialog(this,
                        VERSION_INFO + "\n" + "by kizura\n" + WDBearManager.EMAIL + "\n\n"
                                + "Could not find update information",
                        "Warning " + VERSION_INFO, JOptionPane.WARNING_MESSAGE);
                return;
            }
            String updSite = dbProps.getProperty(KEY_WDBMGR_SITE);
            if (updFile == null) {
                JOptionPane.showMessageDialog(this,
                        VERSION_INFO + "\n" + "by kizura\n" + WDBearManager.EMAIL + "\n\n"
                                + "Could not find SITE information",
                        "Warning " + VERSION_INFO, JOptionPane.WARNING_MESSAGE);
                return;
            }

            URL urlUpdScript = new URL(updFile);
            BufferedReader in = new BufferedReader(new InputStreamReader(urlUpdScript.openStream()));

            String versionTXT = in.readLine();
            String downloadName = in.readLine();
            in.close();

            if (versionTXT.equals(WDBearManager.VERSION_INFO)) {
                JOptionPane.showMessageDialog(this,
                        VERSION_INFO + "\n" + "by kizura\n" + WDBearManager.EMAIL + "\n\n"
                                + "You are using the latest version, no updates available",
                        "Info " + VERSION_INFO, JOptionPane.INFORMATION_MESSAGE);
                return;
            } else {
                // Read version.txt
                String versionInfo = (String) dbProps.getProperty(KEY_VERSION_INFO);
                URL urlversionInfo = new URL(versionInfo);
                BufferedReader brVInfo = new BufferedReader(new InputStreamReader(urlversionInfo.openStream()));
                StringBuffer sbuVInfo = new StringBuffer();
                String strLine = "";
                boolean foundStart = false;
                while ((strLine = brVInfo.readLine()) != null) {
                    if (strLine.startsWith("---")) {
                        break;
                    }
                    if (foundStart == true) {
                        sbuVInfo.append(strLine);
                        sbuVInfo.append("\n");
                        continue;
                    }
                    if (strLine.startsWith(versionTXT)) {
                        foundStart = true;
                        continue;
                    }
                }
                brVInfo.close();

                int n = JOptionPane.showConfirmDialog(this,
                        "New version available - Please visit " + updSite + "\n\n" + versionTXT + "\n" + "\n"
                                + "You are using version:\n" + WDBearManager.VERSION_INFO + "\n" + "\n"
                                + "Do you want to download this version?\n\n" + "Version information:\n"
                                + sbuVInfo.toString(),
                        VERSION_INFO + "by kizura", JOptionPane.YES_NO_OPTION);
                //          JOptionPane.showMessageDialog(this, VERSION_INFO + "\n"
                //              + "by kizura\n" + WDBManager.EMAIL + "\n\n"
                //              + "New version available - Please visit " + updSite,
                //              "Warning "
                //              + VERSION_INFO, JOptionPane.WARNING_MESSAGE);
                if (n == 0) {
                    JFileChooser chooser = new JFileChooser(new File("."));
                    chooser.setDialogTitle("Please select download location");
                    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

                    int returnVal = chooser.showOpenDialog(this);
                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                        try {
                            URL urlUpd = new URL(downloadName);
                            BufferedInputStream bin = new BufferedInputStream(urlUpd.openStream());
                            System.out.println(
                                    new File(chooser.getSelectedFile(), urlUpd.getFile()).getAbsolutePath());
                            File thisFile = new File(chooser.getSelectedFile(), urlUpd.getFile());
                            BufferedOutputStream bout = new BufferedOutputStream(
                                    new FileOutputStream(thisFile));

                            byte[] bufFile = new byte[102400];
                            int bytesRead = 0;
                            while ((bytesRead = bin.read(bufFile)) != -1) {
                                bout.write(bufFile, 0, bytesRead);
                            }
                            bin.close();
                            bout.close();

                            JOptionPane.showMessageDialog(this,
                                    "Update downloaded successfully" + "\n" + "Please check '"
                                            + thisFile.getAbsolutePath() + "'",
                                    "Success " + WDBearManager.VERSION_INFO, JOptionPane.INFORMATION_MESSAGE);
                            //String msg = WriteCSV.writeCSV(chooser.getSelectedFile(), this.items);
                        } catch (Exception ex) {
                            String msg = ex.getMessage();
                            JOptionPane.showMessageDialog(this, msg + "\n" + "Error downloading update",
                                    "Error " + WDBearManager.VERSION_INFO, JOptionPane.ERROR_MESSAGE);
                        }
                    }
                } // user selected "download"
                return;
            }

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

    } else {
        System.exit(0);
    }

}

From source file:es.darkhogg.hazelnutt.EditorFrame.java

private void updateRecentFiles() {
    // Clean/*from   w w  w  . j  av a 2  s.  c  om*/
    menuRecentFiles.removeAll();

    // Remove while recentFiles > N
    while (recentFiles.size() >= 8) {
        recentFiles.removeLast();
    }

    // Add every menu item
    if (recentFiles != null) {
        for (String str : recentFiles) {
            final JMenuItem mi = new JMenuItem(str);
            menuRecentFiles.add(mi);
            mi.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    String fileName = mi.getText();
                    actionOpenRom(fileName);
                }
            });
        }
    }
}

From source file:edu.ku.brc.af.ui.db.TextFieldWithQuery.java

/**
 * @param mi/* ww  w .j a  va 2 s.c  om*/
 * @param advanceFocus
 * @param idListClosure
 */
protected void itemSelected(final JMenuItem mi, final int advanceFocus, Vector<Integer> idListClosure) {
    hasNewText = false;
    //log.debug("setting hasNewText to true");
    if (advanceFocus != 0)
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                transferFocus(advanceFocus);
            }
        });

    String selectedStr = mi.getText();
    int inx = popupMenu.getComponentIndex(mi);
    if (inx > -1) {
        if (idListClosure.size() > 0 && (!doAddAddItem || inx > 0)) {
            selectedId = idListClosure.get(doAddAddItem ? inx - 1 : inx);
            setText(selectedStr);
        }

        if (listSelectionListeners != null) {
            String value = StringUtils.isEmpty(prevEnteredText) ? cachedPrevText : prevEnteredText;
            notifyListenersOfChange(mi.getText().equals(UIRegistry.getResourceString("TFWQ_ADD_LABEL"))
                    ? new AddItemEvent(value)
                    : mi);
        }
    }
}

From source file:net.sourceforge.entrainer.gui.EntrainerFX.java

private JMenuItem getFileMenuItem(String text) {
    JMenu file = getJMenuBar().getMenu(0);

    Component[] comps = file.getMenuComponents();
    JMenuItem jmi;
    for (Component c : comps) {
        if (c instanceof JMenuItem) {
            jmi = (JMenuItem) c;/*w  w w.  j a  va  2 s  .c  o m*/
            if (jmi.getText().equals(text)) {
                return jmi;
            }
        }
    }

    return null;
}

From source file:mondrian.gui.Workbench.java

private void saveAsMenuItemActionPerformed(ActionEvent evt) {
    JInternalFrame jf = desktopPane.getSelectedFrame();

    if (jf != null && jf.getContentPane().getComponent(0) instanceof SchemaExplorer) {
        SchemaExplorer se = (SchemaExplorer) jf.getContentPane().getComponent(0);
        java.io.File schemaFile = se.getSchemaFile();
        java.io.File oldSchemaFile = schemaFile;
        java.io.File suggSchemaFile = new File(
                schemaFile == null ? se.getSchema().name.trim() + ".xml" : schemaFile.getName());
        MondrianGuiDef.Schema schema = se.getSchema();
        JFileChooser jfc = new JFileChooser();
        MondrianProperties.instance();//from  w  ww. j av a 2s .  co m

        jfc.setSelectedFile(suggSchemaFile);

        if (!isSchemaValid(schema)) {
            // the schema would not be re-loadable.  Abort save.
            return;
        }

        if (jfc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            try {
                schemaFile = jfc.getSelectedFile();
                if (!oldSchemaFile.equals(schemaFile) && schemaFile.exists()) { // new file already exists, check for overwrite
                    int answer = JOptionPane.showConfirmDialog(null,
                            getResourceConverter().getFormattedString("workbench.saveAs.schema.confirm",
                                    "{0} schema file already exists. Do you want to replace it?",
                                    schemaFile.getAbsolutePath()),
                            getResourceConverter().getString("workbench.saveAs.schema.confirm.title",
                                    "Save As"),
                            JOptionPane.YES_NO_OPTION);
                    if (answer == 1) { //  no=1 ; yes=0
                        return;
                    }
                }

                if (se.isNewFile() && !oldSchemaFile.equals(schemaFile)) {
                    oldSchemaFile.delete();
                }

                if (se.isNewFile()) {
                    se.setNewFile(false);
                }
                se.setDirty(false);
                se.setDirtyFlag(false);

                XMLOutput out = new XMLOutput(new java.io.FileWriter(jfc.getSelectedFile()));
                out.setAlwaysQuoteCData(true);
                out.setIndentString("  ");
                schema.displayXML(out);
                se.setSchemaFile(schemaFile);
                se.setTitle(); // sets title of iframe
                setLastUsed(jfc.getSelectedFile().getName(), jfc.getSelectedFile().toURI().toURL().toString());

                // Update menu item with new file name, then update catalog
                // list for mdx queries
                JMenuItem sMenuItem = schemaWindowMap.get(jf);
                String mtexttokens[] = sMenuItem.getText().split(" ");
                sMenuItem.setText(mtexttokens[0] + " " + se.getSchemaFile().getName());
                // Schema menu item updated, now update mdx query windows
                // with updated catalog list.
                updateMDXCatalogList();
            } catch (Exception ex) {
                LOGGER.error(ex);
            }
        }
    }
}

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

/**
 * check menu and button events.//from   w  w  w .  j  av  a  2  s  . co m
 */
public void actionPerformed(ActionEvent e) {
    if (e.getSource() instanceof JMenuItem) {
        JMenuItem source = (JMenuItem) (e.getSource());
        if (source.getText().substring(1).startsWith(":\\") || source.getText().startsWith("/")) {
            if (source.getText().endsWith(".tsf")) {
                try {
                    loadSession(new File(source.getText()), true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            } else {
                dumpFile = source.getText();
                openFiles(new File[] { new File(dumpFile) }, true);
            }
        } else if ("Open...".equals(source.getText())) {
            chooseFile();
        } else if ("Open loggc file...".equals(source.getText())) {
            openLoggcFile();
        } else if ("Save Logfile...".equals(source.getText())) {
            saveLogFile();
        } else if ("Save Session...".equals(source.getText())) {
            saveSession();
        } else if ("Open Session...".equals(source.getText())) {
            openSession();
        } else if ("Preferences".equals(source.getText())) {
            showPreferencesDialog();
        } else if ("Filters".equals(source.getText())) {
            showFilterDialog();
        } else if ("Categories".equals(source.getText())) {
            showCategoriesDialog();
        } else if ("Get Logfile from clipboard".equals(source.getText())) {
            getLogfileFromClipboard();
        } else if ("Exit TDA".equals(source.getText())) {
            saveState();
            frame.dispose();
        } else if (ResourceManager.translate("help.contents").equals(source.getText())) {
            showHelp();
        } else if ("Help".equals(source.getText())) {
            showHelp();
        } else if ("Release Notes".equals(source.getText())) {
            showInfoFile("Release Notes", "doc/README", Const.ICON_DOCUMENT);
        } else if ("License".equals(source.getText())) {
            showInfoFile("License Information", "doc/COPYING", Const.ICON_DOCUMENT);
        } else if ("Forum".equals(source.getText())) {
            try {
                Browser.open("https://tda.dev.java.net/servlets/ForumMessageList?forumID=1967");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this.getRootPane(),
                        "Error opening TDA Online Forum\nPlease open https://tda.dev.java.net/servlets/ForumMessageList?forumID=1967 in your browser!",
                        "Error", JOptionPane.ERROR_MESSAGE);
            }
        } else if ("About TDA".equals(source.getText())) {
            showInfo();
        } else if ("Search...".equals(source.getText())) {
            showSearchDialog();
        } else if ("Parse loggc-logfile...".equals(source.getText())) {
            parseLoggcLogfile();
        } else if ("Find long running threads...".equals(source.getText())) {
            findLongRunningThreads();
        } else if (("Close logfile...".equals(source.getText())) || ("Close...".equals(source.getText()))) {
            closeCurrentDump();
        } else if ("Close all...".equals(source.getText())) {
            closeAllDumps();
        } else if ("Diff Selection".equals(source.getText())) {
            final TreePath[] paths = tree.getSelectionPaths();
            if (paths != null) {
                if ((paths.length < 2)) {
                    JOptionPane.showMessageDialog(this.getRootPane(),
                            "You must select at least two dumps for getting a diff!\n", "Error",
                            JOptionPane.ERROR_MESSAGE);

                } else {
                    DefaultMutableTreeNode mergeRoot = fetchTop(tree.getSelectionPath());
                    Map dumpMap = dumpStore.getFromDumpFiles(mergeRoot.getUserObject().toString());
                    ((Logfile) mergeRoot.getUserObject()).getUsedParser().mergeDumps(mergeRoot, dumpMap, paths,
                            paths.length, null);
                    createTree();
                    this.getRootPane().revalidate();
                }
            }
        } else if ("Show selected Dump in logfile".equals(source.getText())) {
            navigateToDumpInLogfile();
        } else if ("Show Toolbar".equals(source.getText())) {
            setShowToolbar(((JCheckBoxMenuItem) source).getState());
        } else if ("Request Thread Dump...".equals(source.getText())) {
            addMXBeanDump();
        } else if ("Expand all nodes".equals(source.getText())) {
            expandAllCatNodes(true);
        } else if ("Collapse all nodes".equals(source.getText())) {
            expandAllCatNodes(false);
        } else if ("Sort by thread count".equals(source.getText())) {
            sortCatByThreads();
        } else if ("Expand all Dump nodes".equals(source.getText())) {
            expandAllDumpNodes(true);
        } else if ("Collapse all Dump nodes".equals(source.getText())) {
            expandAllDumpNodes(false);
        }
    } else if (e.getSource() instanceof JButton) {
        JButton source = (JButton) e.getSource();
        if ("Open Logfile".equals(source.getToolTipText())) {
            chooseFile();
        } else if ("Close selected Logfile".equals(source.getToolTipText())) {
            closeCurrentDump();
        } else if ("Get Logfile from clipboard".equals(source.getToolTipText())) {
            getLogfileFromClipboard();
        } else if ("Preferences".equals(source.getToolTipText())) {
            showPreferencesDialog();
        } else if ("Find long running threads".equals(source.getToolTipText())) {
            findLongRunningThreads();
        } else if ("Expand all nodes".equals(source.getToolTipText())) {
            expandAllDumpNodes(true);
        } else if ("Collapse all nodes".equals(source.getToolTipText())) {
            expandAllDumpNodes(false);
        } else if ("Find long running threads".equals(source.getToolTipText())) {
            findLongRunningThreads();
        } else if ("Filters".equals(source.getToolTipText())) {
            showFilterDialog();
        } else if ("Custom Categories".equals(source.getToolTipText())) {
            showCategoriesDialog();
        } else if ("Request a Thread Dump".equals(source.getToolTipText())) {
            addMXBeanDump();
        } else if ("Help".equals(source.getToolTipText())) {
            showHelp();
        }
        source.setSelected(false);
    }
}

From source file:org.jets3t.apps.cockpit.Cockpit.java

/**
 * Logs out of the S3 service by clearing all listed objects and buckets and resetting
 * the s3ServiceMulti member variable.//from  w w w  . j  av  a 2s .  c  o  m
 *
 * This method should always be invoked within the event dispatching thread.
 */
private void logoutEvent() {
    log.debug("Logging out");
    try {
        ProviderCredentials credentials = s3ServiceMulti.getAWSCredentials();
        String loginName = (credentials.hasFriendlyName() ? credentials.getFriendlyName()
                : credentials.getAccessKey());
        if (loginAwsCredentialsMap.containsKey(loginName)) {
            Component[] components = loginSwitchMenu.getMenuComponents();
            for (int i = 0; i < components.length; i++) {
                JMenuItem menuItem = (JMenuItem) components[i];
                if (loginName.equals(menuItem.getText())) {
                    loginSwitchMenu.remove(components[i]);
                    break;
                }
            }
            loginAwsCredentialsMap.remove(loginName);
            loginSwitchMenu.setEnabled(loginAwsCredentialsMap.size() > 0);
        }

        // Revert to anonymous service.
        s3ServiceMulti = new S3ServiceMulti(getRestS3Service(null), this);
        cloudFrontService = null;

        bucketsTable.clearSelection();
        bucketTableModel.removeAllBuckets();
        objectTableModel.removeAllObjects();

        objectsSummaryLabel.setText(" ");

        ownerFrame.setTitle(APPLICATION_TITLE);
        logoutMenuItem.setEnabled(false);

        refreshBucketMenuItem.setEnabled(false);
        createBucketMenuItem.setEnabled(false);
        bucketLoggingMenuItem.setEnabled(false);

        manageDistributionsMenuItem.setEnabled(false);
    } catch (Exception e) {
        String message = "Unable to log out from S3";
        log.error(message, e);
        ErrorDialog.showDialog(ownerFrame, this, message, e);
    }
}

From source file:mondrian.gui.Workbench.java

private void newQueryMenuItemActionPerformed(ActionEvent evt) {
    JMenuItem schemaMenuItem = schemaWindowMap.get(desktopPane.getSelectedFrame());

    final JInternalFrame jf = new JInternalFrame();
    jf.setTitle(getResourceConverter().getString("workbench.new.MDXQuery.title", "MDX Query"));
    QueryPanel qp = new QueryPanel(this);

    jf.getContentPane().add(qp);//from ww w.j  a  v a  2s.  c  om
    jf.setBounds(0, 0, 500, 480);
    jf.setClosable(true);
    jf.setIconifiable(true);
    jf.setMaximizable(true);
    jf.setResizable(true);
    jf.setVisible(true);

    desktopPane.add(jf);
    jf.show();
    try {
        jf.setSelected(true);
    } catch (Exception ex) {
        // do nothing
        LOGGER.error("newQueryMenuItemActionPerformed.setSelected", ex);
    }

    // add the mdx frame to this set of mdx frames for cascading method
    mdxWindows.add(jf);

    // create mdx menu item
    final javax.swing.JMenuItem queryMenuItem = new javax.swing.JMenuItem();
    queryMenuItem.setText(getResourceConverter().getFormattedString("workbench.new.MDXQuery.menuitem",
            "{0} MDX", Integer.toString(windowMenuMapIndex)));
    queryMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            try {
                if (jf.isIcon()) {
                    jf.setIcon(false);
                } else {
                    jf.setSelected(true);
                }
            } catch (Exception ex) {
                LOGGER.error("queryMenuItem", ex);
            }
        }
    });

    // disable mdx frame close operation to provide our handler
    // to remove frame object from mdxframeset before closing
    jf.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

    jf.addInternalFrameListener(new InternalFrameAdapter() {
        public void internalFrameClosing(InternalFrameEvent e) {
            mdxWindows.remove(jf);
            jf.dispose();
            // follow this by removing file from schemaWindowMap
            windowMenu.remove(queryMenuItem);
            return;
        }
    });

    windowMenu.add(queryMenuItem, -1);
    windowMenu.add(jSeparator3, -1);
    windowMenu.add(cascadeMenuItem, -1);
    windowMenu.add(tileMenuItem, -1);
    windowMenu.add(minimizeMenuItem, -1);
    windowMenu.add(maximizeMenuItem, -1);
    windowMenu.add(closeAllMenuItem, -1);

    qp.setMenuItem(queryMenuItem);
    qp.setSchemaWindowMap(schemaWindowMap);
    qp.setWindowMenuIndex(windowMenuMapIndex++);

    if (schemaMenuItem != null) {
        qp.initConnection(schemaMenuItem.getText());
    } else {
        JOptionPane.showMessageDialog(this,
                getResourceConverter().getString("workbench.new.MDXQuery.no.selection",
                        "No Mondrian connection. Select a Schema to connect."),
                getResourceConverter().getString("workbench.new.MDXQuery.no.selection.title", "Alert"),
                JOptionPane.WARNING_MESSAGE);
    }
}

From source file:lu.fisch.unimozer.Diagram.java

@Override
public void actionPerformed(ActionEvent e) {

    if (isEnabled()) {
        if (e.getSource() instanceof JMenuItem) {
            JMenuItem item = (JMenuItem) e.getSource();
            if (item.getText().equals("Compile")) {
                compile();//from w w w  .j  a v a  2 s.  c o  m
            } else if (item.getText().equals("Remove class") && mouseClass != null) {
                int answ = JOptionPane.showConfirmDialog(frame,
                        "Are you sure to remove the class " + mouseClass.getFullName() + "",
                        "Remove a class", JOptionPane.YES_NO_OPTION);
                if (answ == JOptionPane.YES_OPTION) {
                    cleanAll();// clean(mouseClass);
                    removedClasses.add(mouseClass.getFullName());
                    classes.remove(mouseClass.getFullName());
                    mouseClass = null;
                    updateEditor();
                    repaint();
                    objectizer.repaint();
                }
            } else if (mouseClass.getName().contains("abstract")) {
                JOptionPane.showMessageDialog(frame, "Can't create an object of an abstract class ...",
                        "Instatiation error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR);
            } else if (item.getText().startsWith("new")) // we have constructor
            {
                Logger.getInstance().log("Click on <new> registered");
                // get full signature
                String fSign = item.getText();
                if (fSign.startsWith("new"))
                    fSign = fSign.substring(3).trim();
                // get signature
                final String fullSign = fSign;
                Logger.getInstance().log("fullSign = " + fSign);
                final String sign = mouseClass.getSignatureByFullSignature(fullSign);
                Logger.getInstance().log("sign = " + sign);

                Logger.getInstance().log("Creating runnable ...");
                Runnable r = new Runnable() {
                    @Override
                    public void run() {
                        //System.out.println("Calling method (full): "+fullSign);
                        //System.out.println("Calling method       : "+sign);
                        try {
                            Logger.getInstance().log("Loading the class <" + mouseClass.getName() + ">");
                            Class<?> cla = Runtime5.getInstance().load(mouseClass.getFullName()); //mouseClass.load();
                            Logger.getInstance().log("Loaded!");

                            // check if we need to specify a generic class
                            boolean cont = true;
                            String generics = "";
                            TypeVariable[] tv = cla.getTypeParameters();
                            Logger.getInstance().log("Got TypeVariables with length = " + tv.length);
                            if (tv.length > 0) {
                                LinkedHashMap<String, String> gms = new LinkedHashMap<String, String>();
                                for (int i = 0; i < tv.length; i++) {
                                    gms.put(tv[i].getName(), "");
                                }
                                MethodInputs gi = new MethodInputs(frame, gms, "Generic type declaration",
                                        "Please specify the generic types");
                                cont = gi.OK;

                                // build the string
                                generics = "<";
                                Object[] keys = gms.keySet().toArray();
                                mouseClass.generics.clear();
                                for (int in = 0; in < keys.length; in++) {
                                    String kname = (String) keys[in];
                                    // save generic type to myClass
                                    mouseClass.generics.put(kname, gi.getValueFor(kname));
                                    generics += gi.getValueFor(kname) + ",";
                                }
                                generics = generics.substring(0, generics.length() - 1);
                                generics += ">";
                            }

                            if (cont == true) {
                                Logger.getInstance().log("Getting the constructors.");

                                Constructor[] constr = cla.getConstructors();
                                for (int c = 0; c < constr.length; c++) {
                                    // get signature
                                    String full = objectizer.constToFullString(constr[c]);
                                    Logger.getInstance().log("full = " + full);
                                    /*
                                    String full = constr[c].getName();
                                    full+="(";
                                    Class<?>[] tvm = constr[c].getParameterTypes();
                                    for(int t=0;t<tvm.length;t++)
                                    {
                                        String sn = tvm[t].toString();
                                        sn=sn.substring(sn.lastIndexOf('.')+1,sn.length());
                                        if(sn.startsWith("class")) sn=sn.substring(5).trim();
                                        // array is shown as ";"  ???
                                        if(sn.endsWith(";"))
                                        {
                                            sn=sn.substring(0,sn.length()-1)+"[]";
                                        }
                                        full+= sn+", ";
                                    }
                                    if(tvm.length>0) full=full.substring(0,full.length()-2);
                                    full+= ")";
                                    */
                                    /*System.out.println("Loking for S : "+sign);
                                    System.out.println("Loking for FS: "+fullSign);
                                    System.out.println("Found: "+full);*/

                                    if (full.equals(sign) || full.equals(fullSign)) {
                                        Logger.getInstance().log("We are in!");
                                        //editor.setEnabled(false);
                                        //Logger.getInstance().log("Editor disabled");
                                        String name;
                                        Logger.getInstance().log("Ask user for a name.");
                                        do {
                                            String propose = mouseClass.getShortName().substring(0, 1)
                                                    .toLowerCase() + mouseClass.getShortName().substring(1);
                                            int count = 0;
                                            String prop = propose + count;
                                            while (objectizer.hasObject(prop) == true) {
                                                count++;
                                                prop = propose + count;
                                            }

                                            name = (String) JOptionPane.showInputDialog(frame,
                                                    "Please enter the name for you new instance of "
                                                            + mouseClass.getShortName() + "",
                                                    "Create object", JOptionPane.QUESTION_MESSAGE, null, null,
                                                    prop);
                                            if (Java.isIdentifierOrNull(name) == false) {
                                                JOptionPane.showMessageDialog(frame,
                                                        "" + name + " is not a correct identifier.",
                                                        "Error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR);
                                            } else if (objectizer.hasObject(name) == true) {
                                                JOptionPane.showMessageDialog(frame,
                                                        "An object with the name " + name
                                                                + " already exists.\nPlease choose another name ...",
                                                        "Error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR);
                                            }
                                        } while (Java.isIdentifierOrNull(name) == false
                                                || objectizer.hasObject(name) == true);
                                        Logger.getInstance().log("name = " + name);

                                        if (name != null) {
                                            Logger.getInstance().log("Need to get inputs ...");
                                            LinkedHashMap<String, String> inputs = mouseClass
                                                    .getInputsBySignature(sign);
                                            if (inputs.size() == 0)
                                                inputs = mouseClass.getInputsBySignature(fullSign);

                                            //System.out.println("1) "+sign);
                                            //System.out.println("2) "+fullSign);

                                            MethodInputs mi = null;
                                            boolean go = true;
                                            if (inputs.size() > 0) {
                                                mi = new MethodInputs(frame, inputs, full,
                                                        mouseClass.getJavaDocBySignature(sign));
                                                go = mi.OK;
                                            }
                                            Logger.getInstance().log("go = " + go);
                                            if (go == true) {
                                                Logger.getInstance().log("Building string ...");
                                                //Object arglist[] = new Object[inputs.size()];
                                                String constructor = "new " + mouseClass.getFullName()
                                                        + generics + "(";
                                                if (inputs.size() > 0) {
                                                    Object[] keys = inputs.keySet().toArray();
                                                    for (int in = 0; in < keys.length; in++) {
                                                        String kname = (String) keys[in];
                                                        //String type = inputs.get(kname);

                                                        //if(type.equals("int"))  { arglist[in] = Integer.valueOf(mi.getValueFor(kname)); }
                                                        //else if(type.equals("short"))  { arglist[in] = Short.valueOf(mi.getValueFor(kname)); }
                                                        //else if(type.equals("byte"))  { arglist[in] = Byte.valueOf(mi.getValueFor(kname)); }
                                                        //else if(type.equals("long"))  { arglist[in] = Long.valueOf(mi.getValueFor(kname)); }
                                                        //else if(type.equals("float"))  { arglist[in] = Float.valueOf(mi.getValueFor(kname)); }
                                                        //else if(type.equals("double"))  { arglist[in] = Double.valueOf(mi.getValueFor(kname)); }
                                                        //else if(type.equals("boolean"))  { arglist[in] = Boolean.valueOf(mi.getValueFor(kname)); }
                                                        //else arglist[in] = mi.getValueFor(kname);

                                                        String val = mi.getValueFor(kname);
                                                        if (val.equals(""))
                                                            val = "null";
                                                        else {
                                                            String type = mi.getTypeFor(kname);
                                                            if (type.toLowerCase().equals("byte"))
                                                                constructor += "Byte.valueOf(\"" + val + "\"),";
                                                            else if (type.toLowerCase().equals("short"))
                                                                constructor += "Short.valueOf(\"" + val
                                                                        + "\"),";
                                                            else if (type.toLowerCase().equals("float"))
                                                                constructor += "Float.valueOf(\"" + val
                                                                        + "\"),";
                                                            else if (type.toLowerCase().equals("long"))
                                                                constructor += "Long.valueOf(\"" + val + "\"),";
                                                            else if (type.toLowerCase().equals("double"))
                                                                constructor += "Double.valueOf(\"" + val
                                                                        + "\"),";
                                                            else if (type.toLowerCase().equals("char"))
                                                                constructor += "'" + val + "',";
                                                            else
                                                                constructor += val + ",";
                                                        }

                                                        //constructor+=mi.getValueFor(kname)+",";
                                                    }
                                                    constructor = constructor.substring(0,
                                                            constructor.length() - 1);
                                                }
                                                //System.out.println(arglist);
                                                constructor += ")";
                                                //System.out.println(constructor);
                                                Logger.getInstance().log("constructor = " + constructor);

                                                //LOAD: 
                                                //addLibs();
                                                Object obj = Runtime5.getInstance().getInstance(name,
                                                        constructor); //mouseClass.getInstance(name, constructor);
                                                Logger.getInstance().log("Objet is now instantiated!");
                                                //Runtime.getInstance().interpreter.getNameSpace().i
                                                //System.out.println(obj.getClass().getSimpleName());
                                                //Object obj = constr[c].newInstance(arglist);
                                                MyObject myo = objectizer.addObject(name, obj);
                                                myo.setMyClass(mouseClass);
                                                obj = null;
                                                cla = null;
                                            }

                                            objectizer.repaint();
                                            Logger.getInstance().log("Objectizer repainted ...");
                                            repaint();
                                            Logger.getInstance().log("Diagram repainted ...");
                                        }
                                        //editor.setEnabled(true);
                                        //Logger.getInstance().log("Editor enabled again ...");

                                    }
                                }
                            }
                        } catch (Exception ex) {
                            //ex.printStackTrace();
                            MyError.display(ex);
                            JOptionPane.showMessageDialog(frame, ex.toString(), "Instantiation error",
                                    JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR);
                        }
                    }
                };
                Thread t = new Thread(r);
                t.start();
            } else // we have a static method
            {
                try {
                    // get full signature
                    String fullSign = ((JMenuItem) e.getSource()).getText();
                    // get signature
                    String sign = mouseClass.getSignatureByFullSignature(fullSign).replace(", ", ",");
                    String complete = mouseClass.getCompleteSignatureBySignature(sign).replace(", ", ",");

                    /*System.out.println("Calling method (full): "+fullSign);
                    System.out.println("Calling method       : "+sign);
                    System.out.println("Calling method (comp): "+complete);/**/

                    // find method
                    Class c = Runtime5.getInstance().load(mouseClass.getFullName());
                    Method m[] = c.getMethods();
                    for (int i = 0; i < m.length; i++) {
                        /*String full = "";
                        full+= m[i].getReturnType().getSimpleName();
                        full+=" ";
                        full+= m[i].getName();
                        full+= "(";
                        Class<?>[] tvm = m[i].getParameterTypes();
                        LinkedHashMap<String,String> genericInputs = new LinkedHashMap<String,String>();
                        for(int t=0;t<tvm.length;t++)
                        {
                        String sn = tvm[t].toString();
                        //System.out.println(sn);
                        if(sn.startsWith("class")) sn=sn.substring(5).trim();
                        sn=sn.substring(sn.lastIndexOf('.')+1,sn.length());
                        // array is shown as ";"  ???
                        if(sn.endsWith(";"))
                        {
                            sn=sn.substring(0,sn.length()-1)+"[]";
                        }
                        full+= sn+", ";
                        genericInputs.put("param"+t,sn);
                        }
                        if(tvm.length>0) full=full.substring(0,full.length()-2);
                        full+= ")";*/
                        String full = objectizer.toFullString(m[i]);
                        LinkedHashMap<String, String> genericInputs = objectizer.getInputsReplaced(m[i], null);

                        /*System.out.println("Looking for S : "+sign);
                        System.out.println("Looking for FS: "+fullSign);
                        System.out.println("Found         : "+full);*/

                        if (full.equals(sign) || full.equals(fullSign)) {
                            LinkedHashMap<String, String> inputs = mouseClass.getInputsBySignature(sign);
                            //Objectizer.printLinkedHashMap("inputs", inputs);
                            if (inputs.size() != genericInputs.size()) {
                                inputs = genericInputs;
                            }
                            //Objectizer.printLinkedHashMap("inputs", inputs);
                            MethodInputs mi = null;
                            boolean go = true;
                            if (inputs.size() > 0) {
                                mi = new MethodInputs(frame, inputs, full,
                                        mouseClass.getJavaDocBySignature(sign));
                                go = mi.OK;
                            }
                            if (go == true) {
                                try {
                                    String method = mouseClass.getFullName() + "." + m[i].getName() + "(";
                                    if (inputs.size() > 0) {
                                        Object[] keys = inputs.keySet().toArray();
                                        //int cc = 0;
                                        for (int in = 0; in < keys.length; in++) {
                                            String name = (String) keys[in];
                                            String val = mi.getValueFor(name);

                                            if (val.equals(""))
                                                method += val + "null,";
                                            else {
                                                String type = mi.getTypeFor(name);
                                                if (type.toLowerCase().equals("byte"))
                                                    method += "Byte.valueOf(\"" + val + "\"),";
                                                else if (type.toLowerCase().equals("short"))
                                                    method += "Short.valueOf(\"" + val + "\"),";
                                                else if (type.toLowerCase().equals("float"))
                                                    method += "Float.valueOf(\"" + val + "\"),";
                                                else if (type.toLowerCase().equals("long"))
                                                    method += "Long.valueOf(\"" + val + "\"),";
                                                else if (type.toLowerCase().equals("double"))
                                                    method += "Double.valueOf(\"" + val + "\"),";
                                                else if (type.toLowerCase().equals("char"))
                                                    method += "'" + val + "',";
                                                else
                                                    method += val + ",";
                                            }

                                            //if (val.equals("")) val="null";
                                            //method+=val+",";
                                        }
                                        if (!method.endsWith("("))
                                            method = method.substring(0, method.length() - 1);
                                    }
                                    method += ")";

                                    //System.out.println(method);

                                    // Invoke method in a new thread
                                    final String myMeth = method;
                                    Runnable r = new Runnable() {
                                        public void run() {
                                            try {
                                                Object retobj = Runtime5.getInstance().executeMethod(myMeth);
                                                if (retobj != null)
                                                    JOptionPane.showMessageDialog(frame, retobj.toString(),
                                                            "Result", JOptionPane.INFORMATION_MESSAGE,
                                                            Unimozer.IMG_INFO);
                                            } catch (EvalError ex) {
                                                JOptionPane.showMessageDialog(frame, ex.toString(),
                                                        "Invokation error", JOptionPane.ERROR_MESSAGE,
                                                        Unimozer.IMG_ERROR);
                                                MyError.display(ex);
                                            }
                                        }
                                    };
                                    Thread t = new Thread(r);
                                    t.start();

                                    //System.out.println(method);
                                    //Object retobj = Runtime5.getInstance().executeMethod(method);
                                    //if(retobj!=null) JOptionPane.showMessageDialog(frame, retobj.toString(), "Result", JOptionPane.INFORMATION_MESSAGE,Unimozer.IMG_INFO);
                                } catch (Throwable ex) {
                                    JOptionPane.showMessageDialog(frame, ex.toString(), "Execution error",
                                            JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR);
                                    MyError.display(ex);
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(frame, ex.toString(), "Execution error",
                            JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR);
                    MyError.display(ex);
                }
            }
        }
    }
}