Example usage for java.awt Frame NORMAL

List of usage examples for java.awt Frame NORMAL

Introduction

In this page you can find the example usage for java.awt Frame NORMAL.

Prototype

int NORMAL

To view the source code for java.awt Frame NORMAL.

Click Source Link

Document

Frame is in the "normal" state.

Usage

From source file:WindowEventDemo.java

private String convertStateToString(int state) {
    if (state == Frame.NORMAL) {
        return "NORMAL";
    }/*from   ww w .  ja  v  a  2 s  . c om*/
    String strState = " ";
    if ((state & Frame.ICONIFIED) != 0) {
        strState += "ICONIFIED";
    }
    // MAXIMIZED_BOTH is a concatenation of two bits, so
    // we need to test for an exact match.
    if ((state & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH) {
        strState += "MAXIMIZED_BOTH";
    } else {
        if ((state & Frame.MAXIMIZED_VERT) != 0) {
            strState += "MAXIMIZED_VERT";
        }
        if ((state & Frame.MAXIMIZED_HORIZ) != 0) {
            strState += "MAXIMIZED_HORIZ";
        }
    }
    if (" ".equals(strState)) {
        strState = "UNKNOWN";
    }
    return strState.trim();
}

From source file:edu.umd.cs.findbugs.gui2.GUISaveState.java

public static void loadInstance() {
    GUISaveState newInstance = new GUISaveState();
    newInstance.recentFiles = new ArrayList<File>();
    Preferences p = Preferences.userNodeForPackage(GUISaveState.class);

    newInstance.tabSize = p.getInt(TAB_SIZE, 4);

    newInstance.fontSize = p.getFloat(FONT_SIZE, 12.0f);

    newInstance.starterDirectoryForLoadBugs = new File(
            p.get(GUISaveState.STARTERDIRECTORY, SystemProperties.getProperty("user.dir")));

    int prevCommentsSize = p.getInt(GUISaveState.PREVCOMMENTSSIZE, 0);

    for (int x = 0; x < prevCommentsSize; x++) {
        String comment = p.get(GUISaveState.COMMENTKEYS[x], "");
        newInstance.previousComments.add(comment);
    }//  ww w  .j a v a2 s  . co  m

    int size = Math.min(MAXNUMRECENTPROJECTS, p.getInt(GUISaveState.NUMPROJECTS, 0));
    for (int x = 0; x < size; x++) {
        newInstance.addRecentFile(new File(p.get(GUISaveState.RECENTPROJECTKEYS[x], "")));
    }

    int sorterSize = p.getInt(GUISaveState.SORTERTABLELENGTH, -1);
    if (sorterSize != -1) {
        ArrayList<Sortables> sortColumns = new ArrayList<Sortables>();
        String[] sortKeys = GUISaveState.generateSorterKeys(sorterSize);
        for (int x = 0; x < sorterSize; x++) {
            Sortables s = Sortables.getSortableByPrettyName(p.get(sortKeys[x], "*none*"));

            if (s == null) {
                if (MainFrame.GUI2_DEBUG) {
                    System.err.println("Sort order was corrupted, using default sort order");
                }
                newInstance.useDefault = true;
                break;
            }
            sortColumns.add(s);
        }
        if (!newInstance.useDefault) {
            // add in default columns
            Set<Sortables> missingSortColumns = new HashSet<Sortables>(Arrays.asList(DEFAULT_COLUMN_HEADERS));
            missingSortColumns.removeAll(sortColumns);
            sortColumns.addAll(missingSortColumns);
            newInstance.sortColumns = sortColumns.toArray(new Sortables[sortColumns.size()]);
        }
    } else {
        newInstance.useDefault = true;
    }

    newInstance.dockingLayout = p.getByteArray(DOCKINGLAYOUT, new byte[0]);

    String boundsString = p.get(FRAME_BOUNDS, null);
    Rectangle r = new Rectangle(0, 0, 800, 650);
    if (boundsString != null) {
        String[] a = boundsString.split(",", 4);
        if (a.length > 0) {
            try {
                r.x = Math.max(0, Integer.parseInt(a[0]));
            } catch (NumberFormatException nfe) {
                assert true;
            }
        }
        if (a.length > 1) {
            try {
                r.y = Math.max(0, Integer.parseInt(a[1]));
            } catch (NumberFormatException nfe) {
                assert true;
            }
        }
        if (a.length > 2) {
            try {
                r.width = Math.max(40, Integer.parseInt(a[2]));
            } catch (NumberFormatException nfe) {
                assert true;
            }
        }
        if (a.length > 3) {
            try {
                r.height = Math.max(40, Integer.parseInt(a[3]));
            } catch (NumberFormatException nfe) {
                assert true;
            }
        }
    }
    newInstance.frameBounds = r;
    newInstance.extendedWindowState = p.getInt(EXTENDED_WINDOW_STATE, Frame.NORMAL);

    newInstance.splitMain = p.getInt(SPLIT_MAIN, 400);
    newInstance.splitSummary = p.getInt(SPLIT_SUMMARY_NEW, 400);
    newInstance.splitTop = p.getInt(SPLIT_TOP, -1);
    newInstance.splitTreeComments = p.getInt(SPLIT_TREE_COMMENTS, 250);
    newInstance.packagePrefixSegments = p.getInt(PACKAGE_PREFIX_SEGEMENTS, 3);

    String plugins = p.get(CUSTOM_PLUGINS, "");
    if (plugins.length() > 0) {
        for (String s : plugins.split(" ")) {
            try {
                URI u = new URI(s);
                Plugin.addCustomPlugin(u);
                newInstance.customPlugins.add(u);
            } catch (PluginException e) {
                assert true;
            } catch (URISyntaxException e) {
                assert true;
            }
        }
    }

    String enabledPluginsString = p.get(ENABLED_PLUGINS, "");
    String disabledPluginsString = p.get(DISABLED_PLUGINS, "");
    newInstance.enabledPlugins = new ArrayList<String>(Arrays.asList(enabledPluginsString.split(",")));
    newInstance.disabledPlugins = new ArrayList<String>(Arrays.asList(disabledPluginsString.split(",")));

    instance = newInstance;
}

From source file:com.mgmtp.perfload.loadprofiles.ui.ctrl.ConfigController.java

public int getFrameState() {
    try {//from ww  w  .  j  av a 2  s .c  om
        return Integer.parseInt(getAppProperties().getProperty("frame.state"));
    } catch (NumberFormatException ex) {
        log.warn("Could not read frame state from properties. Using default.");
        return Frame.NORMAL;
    }
}

From source file:mergedoc.ui.MergeDocFrame.java

/**
 *  Persister ????/*ww w. ja v  a  2s  .  c o  m*/
 * ?????
 */
private void persistent() {
    try {
        Persister psst = Persister.getInstance();
        int state = getExtendedState();
        psst.setInt(Persister.WINDOW_STATE, state);
        if (state == Frame.NORMAL) {
            psst.setInt(Persister.WINDOW_WIDTH, (int) getSize().getWidth());
            psst.setInt(Persister.WINDOW_HEIGHT, (int) getSize().getHeight());
            psst.setInt(Persister.WINDOW_X, (int) getLocation().getX());
            psst.setInt(Persister.WINDOW_Y, (int) getLocation().getY());
        }
    } catch (MergeDocException e) {
        dialog.showErrorMessage(e.getMessage());
    }
}

From source file:gmgen.GMGenSystem.java

private void setCloseSettings() {
    SettingsHandler.setGMGenOption(SETTING_WINDOW_X, this.getX());
    SettingsHandler.setGMGenOption(WINDOW_Y, this.getY());
    SettingsHandler.setGMGenOption(SETTING_WINDOW_WIDTH, this.getSize().width);
    SettingsHandler.setGMGenOption(SETTING_WINDOW_HEIGHT, this.getSize().height);

    // Maximized state of the window
    if ((getExtendedState() & Frame.MAXIMIZED_BOTH) != 0) {
        SettingsHandler.setGMGenOption(SETTING_WINDOW_STATE, Frame.MAXIMIZED_BOTH);
    } else if ((getExtendedState() & Frame.MAXIMIZED_HORIZ) != 0) {
        SettingsHandler.setGMGenOption(SETTING_WINDOW_STATE, Frame.MAXIMIZED_HORIZ);
    } else if ((getExtendedState() & Frame.MAXIMIZED_VERT) != 0) {
        SettingsHandler.setGMGenOption(SETTING_WINDOW_STATE, Frame.MAXIMIZED_VERT);
    } else {//from ww w  .  ja  v a  2s . c  om
        SettingsHandler.setGMGenOption(SETTING_WINDOW_STATE, Frame.NORMAL);
    }
}

From source file:gmgen.GMGenSystem.java

private void initSettings() {
    int iWinX = SettingsHandler.getGMGenOption(SETTING_WINDOW_X, 0);
    int iWinY = SettingsHandler.getGMGenOption(WINDOW_Y, 0);
    setLocation(iWinX, iWinY);//from w  ww . j  a va 2s .  c  o m

    int iWinWidth = SettingsHandler.getGMGenOption(SETTING_WINDOW_WIDTH, 750);
    int iWinHeight = SettingsHandler.getGMGenOption(SETTING_WINDOW_HEIGHT, 580);
    setSize(iWinWidth, iWinHeight);

    int windowState = SettingsHandler.getGMGenOption(SETTING_WINDOW_STATE, Frame.NORMAL);

    if (windowState != Frame.NORMAL) {
        setExtendedState(windowState);
    }

}

From source file:de.ailis.xadrian.frames.MainFrame.java

/**
 * Opens the specified files. If the main frame is already started then the
 * files are opened right away. Otherwise the file names are queued for
 * later processing./*from ww  w  .  j  a  v a  2s. c o  m*/
 *
 * @param directory
 *            The directory from which to open the files. Needed to resolve
 *            relative file names.
 * @param fileNames
 *            The names of the files to open.
 */
public static void open(final File directory, final String... fileNames) {
    synchronized (unprocessedFiles) {
        for (final String fileName : fileNames) {
            File file = new File(fileName);
            if (!file.isAbsolute())
                file = new File(directory, fileName);
            if (instance == null)
                unprocessedFiles.add(file);
            else
                instance.open(file);
        }
    }

    // If main frame is already open then do lot of stuff to try to get
    // it into the foreground.
    if (instance != null) {
        instance.setExtendedState(Frame.NORMAL);
        instance.toFront();
        instance.requestFocus();
        instance.setVisible(true);
    }
}

From source file:org.argouml.application.Main.java

/**
 * Do a part of the initialization that is very much GUI-stuff.
 *
 * @param splash the splash screeen//from  w w w  .  j a  v a 2  s .  c o  m
 */
private static ProjectBrowser initializeGUI(SplashScreen splash) {
    // make the projectbrowser
    JPanel todoPane = new ToDoPane();
    ProjectBrowser pb = ProjectBrowser.makeInstance(splash, true, todoPane);

    JOptionPane.setRootFrame(pb);

    pb.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    // Set the screen layout to what the user left it before, or
    // to reasonable defaults.
    Rectangle scrSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();

    int configFrameWidth = Configuration.getInteger(Argo.KEY_SCREEN_WIDTH, scrSize.width);
    int w = Math.min(configFrameWidth, scrSize.width);
    if (w == 0) {
        w = 600;
    }

    int configFrameHeight = Configuration.getInteger(Argo.KEY_SCREEN_HEIGHT, scrSize.height);
    int h = Math.min(configFrameHeight, scrSize.height);
    if (h == 0) {
        h = 400;
    }

    int x = Configuration.getInteger(Argo.KEY_SCREEN_LEFT_X, 0);
    int y = Configuration.getInteger(Argo.KEY_SCREEN_TOP_Y, 0);
    pb.setLocation(x, y);
    pb.setSize(w, h);
    pb.setExtendedState(
            Configuration.getBoolean(Argo.KEY_SCREEN_MAXIMIZED, false) ? Frame.MAXIMIZED_BOTH : Frame.NORMAL);

    UIManager.put("Button.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "ENTER", "pressed",
            "released ENTER", "released", "SPACE", "pressed", "released SPACE", "released" }));
    return pb;
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java

/**
 * Constructs the pane for the spreadsheet.
 * /*from w w w  .  j  a  v  a  2s  . c  o m*/
 * @param name the name of the pane
 * @param task the owning task
 * @param workbench the workbench to be edited
 * @param showImageView shows image window when first showing the window
 */
public WorkbenchPaneSS(final String name, final Taskable task, final Workbench workbenchArg,
        final boolean showImageView, final boolean isReadOnly) throws Exception {
    super(name, task);

    removeAll();

    if (workbenchArg == null) {
        return;
    }
    this.workbench = workbenchArg;

    this.isReadOnly = isReadOnly;

    headers.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems());
    Collections.sort(headers);

    boolean hasOneOrMoreImages = false;
    // pre load all the data
    for (WorkbenchRow wbRow : workbench.getWorkbenchRows()) {
        for (WorkbenchDataItem wbdi : wbRow.getWorkbenchDataItems()) {
            wbdi.getCellData();
        }

        if (wbRow.getWorkbenchRowImages() != null && wbRow.getWorkbenchRowImages().size() > 0) {
            hasOneOrMoreImages = true;
        }
    }

    model = new GridTableModel(this);
    spreadSheet = new WorkbenchSpreadSheet(model, this);
    spreadSheet.setReadOnly(isReadOnly);
    model.setSpreadSheet(spreadSheet);

    Highlighter simpleStriping = HighlighterFactory.createSimpleStriping();
    GridCellHighlighter hl = new GridCellHighlighter(
            new GridCellPredicate(GridCellPredicate.AnyPredicate, null));
    Short[] errs = { WorkbenchDataItem.VAL_ERROR, WorkbenchDataItem.VAL_ERROR_EDIT };
    ColorHighlighter errColorHighlighter = new ColorHighlighter(
            new GridCellPredicate(GridCellPredicate.ValidationPredicate, errs),
            CellRenderingAttributes.errorBackground, null);
    Short[] newdata = { WorkbenchDataItem.VAL_NEW_DATA };
    ColorHighlighter noDataHighlighter = new ColorHighlighter(
            new GridCellPredicate(GridCellPredicate.MatchingPredicate, newdata),
            CellRenderingAttributes.newDataBackground, null);
    Short[] multimatch = { WorkbenchDataItem.VAL_MULTIPLE_MATCH };
    ColorHighlighter multiMatchHighlighter = new ColorHighlighter(
            new GridCellPredicate(GridCellPredicate.MatchingPredicate, multimatch),
            CellRenderingAttributes.multipleMatchBackground, null);

    spreadSheet.setHighlighters(simpleStriping, hl, errColorHighlighter, noDataHighlighter,
            multiMatchHighlighter);

    //add key mappings for cut, copy, paste
    //XXX Note: these are shortcuts directly to the SpreadSheet cut,copy,paste methods, NOT to the Specify edit menu.
    addRecordKeyMappings(spreadSheet, KeyEvent.VK_C, "Copy", new AbstractAction() {
        public void actionPerformed(ActionEvent ae) {
            SwingUtilities.invokeLater(new Runnable() {

                /* (non-Javadoc)
                 * @see java.lang.Runnable#run()
                 */
                @Override
                public void run() {
                    spreadSheet.cutOrCopy(false);
                }
            });
        }
    }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
    addRecordKeyMappings(spreadSheet, KeyEvent.VK_X, "Cut", new AbstractAction() {
        public void actionPerformed(ActionEvent ae) {
            SwingUtilities.invokeLater(new Runnable() {

                /* (non-Javadoc)
                 * @see java.lang.Runnable#run()
                 */
                @Override
                public void run() {
                    spreadSheet.cutOrCopy(true);
                }
            });
        }
    }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
    addRecordKeyMappings(spreadSheet, KeyEvent.VK_V, "Paste", new AbstractAction() {
        public void actionPerformed(ActionEvent ae) {
            SwingUtilities.invokeLater(new Runnable() {

                /* (non-Javadoc)
                 * @see java.lang.Runnable#run()
                 */
                @Override
                public void run() {
                    spreadSheet.paste();
                }
            });
        }
    }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());

    findPanel = spreadSheet.getFindReplacePanel();
    UIRegistry.getLaunchFindReplaceAction().setSearchReplacePanel(findPanel);

    spreadSheet.setShowGrid(true);
    JTableHeader header = spreadSheet.getTableHeader();
    header.addMouseListener(new ColumnHeaderListener());
    header.setReorderingAllowed(false); // Turn Off column dragging

    // Put the model in image mode, and never change it.
    // Now we're showing/hiding the image column using JXTable's column hiding features.
    model.setInImageMode(true);
    int imageColIndex = model.getColumnCount() - 1;
    imageColExt = spreadSheet.getColumnExt(imageColIndex);
    imageColExt.setVisible(false);

    int sgrColIndex = model.getSgrHeading().getViewOrder();
    sgrColExt = spreadSheet.getColumnExt(sgrColIndex);
    sgrColExt.setComparator(((WorkbenchSpreadSheet) spreadSheet).new NumericColumnComparator());

    int cmpIdx = 0;
    for (Comparator<String> cmp : ((WorkbenchSpreadSheet) spreadSheet).getComparators()) {
        if (cmp != null) {
            spreadSheet.getColumnExt(cmpIdx++).setComparator(cmp);
        }
    }

    // Start off with the SGR score column hidden
    showHideSgrCol(false);

    model.addTableModelListener(new TableModelListener() {
        public void tableChanged(TableModelEvent e) {
            setChanged(true);
        }
    });

    spreadSheet.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            UIRegistry.enableCutCopyPaste(true);
            UIRegistry.enableFind(findPanel, true);
        }

        @Override
        public void focusLost(FocusEvent e) {
            UIRegistry.enableCutCopyPaste(true);
            UIRegistry.enableFind(findPanel, true);
        }
    });

    if (isReadOnly) {
        saveBtn = null;
    } else {
        saveBtn = createButton(getResourceString("SAVE"));
        saveBtn.setToolTipText(
                String.format(getResourceString("WB_SAVE_DATASET_TT"), new Object[] { workbench.getName() }));
        saveBtn.setEnabled(false);
        saveBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                UsageTracker.incrUsageCount("WB.SaveDataSet");

                UIRegistry.writeSimpleGlassPaneMsg(
                        String.format(getResourceString("WB_SAVING"), new Object[] { workbench.getName() }),
                        WorkbenchTask.GLASSPANE_FONT_SIZE);
                UIRegistry.getStatusBar().setIndeterminate(workbench.getName(), true);
                final SwingWorker worker = new SwingWorker() {
                    @SuppressWarnings("synthetic-access")
                    @Override
                    public Object construct() {
                        try {
                            saveObject();

                        } catch (Exception ex) {
                            UsageTracker.incrHandledUsageCount();
                            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(WorkbenchPaneSS.class,
                                    ex);
                            log.error(ex);
                            return ex;
                        }
                        return null;
                    }

                    // Runs on the event-dispatching thread.
                    @Override
                    public void finished() {
                        Object retVal = get();
                        if (retVal != null && retVal instanceof Exception) {
                            Exception ex = (Exception) retVal;
                            UIRegistry.getStatusBar().setErrorMessage(getResourceString("WB_ERROR_SAVING"), ex);
                        }

                        UIRegistry.clearSimpleGlassPaneMsg();
                        UIRegistry.getStatusBar().setProgressDone(workbench.getName());
                    }
                };
                worker.start();

            }
        });
    }

    Action delAction = addRecordKeyMappings(spreadSheet, KeyEvent.VK_F3, "DelRow", new AbstractAction() {
        public void actionPerformed(ActionEvent ae) {
            if (validationWorkerQueue.peek() == null) {
                deleteRows();
            }
        }
    }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());

    if (isReadOnly) {
        deleteRowsBtn = null;
    } else {
        deleteRowsBtn = createIconBtn("DelRec", "WB_DELETE_ROW", delAction);
        selectionSensitiveButtons.add(deleteRowsBtn);
        spreadSheet.setDeleteAction(delAction);
    }

    //XXX Using the wb ID in the prefname to do pref setting per wb, may result in a bloated prefs file?? 
    doIncrementalValidation = AppPreferences.getLocalPrefs()
            .getBoolean(wbAutoValidatePrefName + "." + workbench.getId(), true);
    doIncrementalMatching = AppPreferences.getLocalPrefs()
            .getBoolean(wbAutoMatchPrefName + "." + workbench.getId(), false);

    if (isReadOnly) {
        clearCellsBtn = null;
    } else {
        clearCellsBtn = createIconBtn("Eraser", "WB_CLEAR_CELLS", new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                spreadSheet.clearSorter();

                if (spreadSheet.getCellEditor() != null) {
                    spreadSheet.getCellEditor().stopCellEditing();
                }
                int[] rows = spreadSheet.getSelectedRowModelIndexes();
                int[] cols = spreadSheet.getSelectedColumnModelIndexes();
                model.clearCells(rows, cols);
            }
        });
        selectionSensitiveButtons.add(clearCellsBtn);
    }

    Action addAction = addRecordKeyMappings(spreadSheet, KeyEvent.VK_N, "AddRow", new AbstractAction() {
        public void actionPerformed(ActionEvent ae) {
            if (workbench.getWorkbenchRows().size() < WorkbenchTask.MAX_ROWS) {
                if (validationWorkerQueue.peek() == null) {
                    addRowAfter();
                }
            }
        }
    }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());

    if (isReadOnly) {
        addRowsBtn = null;
    } else {
        addRowsBtn = createIconBtn("AddRec", "WB_ADD_ROW", addAction);
        addRowsBtn.setEnabled(true);
        addAction.setEnabled(true);
    }

    if (isReadOnly) {
        carryForwardBtn = null;
    } else {
        carryForwardBtn = createIconBtn("CarryForward20x20", IconManager.IconSize.NonStd, "WB_CARRYFORWARD",
                false, new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        UsageTracker.getUsageCount("WBCarryForward");

                        configCarryFoward();
                    }
                });
        carryForwardBtn.setEnabled(true);
    }

    toggleImageFrameBtn = createIconBtn("CardImage", IconManager.IconSize.NonStd, "WB_SHOW_IMG_WIN", false,
            new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    toggleImageFrameVisible();
                }
            });
    toggleImageFrameBtn.setEnabled(true);

    importImagesBtn = createIconBtn("CardImage", IconManager.IconSize.NonStd, "WB_SHOW_IMG_WIN", false,
            new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    toggleImportImageFrameVisible();
                }
            });
    importImagesBtn.setEnabled(true);

    /*showMapBtn = createIconBtn("ShowMap", IconManager.IconSize.NonStd, "WB_SHOW_MAP", false, new ActionListener()
    {
    public void actionPerformed(ActionEvent ae)
    {
        showMapOfSelectedRecords();
    }
    });*/
    // enable or disable along with Google Earth and Geo Ref Convert buttons

    if (isReadOnly) {
        exportKmlBtn = null;
    } else {
        exportKmlBtn = createIconBtn("GoogleEarth", IconManager.IconSize.NonStd, "WB_SHOW_IN_GOOGLE_EARTH",
                false, new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                showRecordsInGoogleEarth();
                            }
                        });
                    }
                });
    }

    // 

    readRegisteries();

    // enable or disable along with Show Map and Geo Ref Convert buttons

    if (isReadOnly) {
        geoRefToolBtn = null;
    } else {
        AppPreferences remotePrefs = AppPreferences.getRemote();
        final String tool = remotePrefs.get("georef_tool", "geolocate");
        String iconName = "GEOLocate20"; //tool.equalsIgnoreCase("geolocate") ? "GeoLocate" : "BioGeoMancer";
        String toolTip = tool.equalsIgnoreCase("geolocate") ? "WB_DO_GEOLOCATE_LOOKUP"
                : "WB_DO_BIOGEOMANCER_LOOKUP";
        geoRefToolBtn = createIconBtn(iconName, IconManager.IconSize.NonStd, toolTip, false,
                new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        spreadSheet.clearSorter();

                        if (tool.equalsIgnoreCase("geolocate")) {
                            doGeoRef(new edu.ku.brc.services.geolocate.prototype.GeoCoordGeoLocateProvider(),
                                    "WB.GeoLocateRows");
                        } else {
                            doGeoRef(new GeoCoordBGMProvider(), "WB.BioGeomancerRows");
                        }
                    }
                });
        // only enable it if the workbench has the proper columns in it
        String[] missingColumnsForBG = getMissingButRequiredColumnsForGeoRefTool(tool);
        if (missingColumnsForBG.length > 0) {
            geoRefToolBtn.setEnabled(false);
            String ttText = "<p>" + getResourceString("WB_ADDITIONAL_FIELDS_REQD") + ":<ul>";
            for (String reqdField : missingColumnsForBG) {
                ttText += "<li>" + reqdField + "</li>";
            }
            ttText += "</ul>";
            String origTT = geoRefToolBtn.getToolTipText();
            geoRefToolBtn.setToolTipText("<html>" + origTT + ttText);
        } else {
            geoRefToolBtn.setEnabled(true);
        }
    }

    if (isReadOnly) {
        convertGeoRefFormatBtn = null;
    } else {
        convertGeoRefFormatBtn = createIconBtn("ConvertGeoRef", IconManager.IconSize.NonStd,
                "WB_CONVERT_GEO_FORMAT", false, new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        showGeoRefConvertDialog();
                    }
                });

        // now enable/disable the geo ref related buttons
        String[] missingGeoRefFields = getMissingGeoRefLatLonFields();
        if (missingGeoRefFields.length > 0) {
            convertGeoRefFormatBtn.setEnabled(false);
            exportKmlBtn.setEnabled(false);
            //showMapBtn.setEnabled(false);

            String ttText = "<p>" + getResourceString("WB_ADDITIONAL_FIELDS_REQD") + ":<ul>";
            for (String reqdField : missingGeoRefFields) {
                ttText += "<li>" + reqdField + "</li>";
            }
            ttText += "</ul>";
            String origTT1 = convertGeoRefFormatBtn.getToolTipText();
            convertGeoRefFormatBtn.setToolTipText("<html>" + origTT1 + ttText);
            String origTT2 = exportKmlBtn.getToolTipText();
            exportKmlBtn.setToolTipText("<html>" + origTT2 + ttText);
            //String origTT3 = showMapBtn.getToolTipText();
            //showMapBtn.setToolTipText("<html>" + origTT3 + ttText);
        } else {
            convertGeoRefFormatBtn.setEnabled(true);
            exportKmlBtn.setEnabled(true);
            //showMapBtn.setEnabled(true);
        }
    }

    if (AppContextMgr.isSecurityOn() && !task.getPermissions().canModify()) {
        exportExcelCsvBtn = null;
    } else {
        exportExcelCsvBtn = createIconBtn("Export", IconManager.IconSize.NonStd, "WB_EXPORT_DATA", false,
                new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        doExcelCsvExport();
                    }
                });
        exportExcelCsvBtn.setEnabled(true);
    }

    uploadDatasetBtn = createIconBtn("Upload", IconManager.IconSize.Std24, "WB_UPLOAD_DATA", false,
            new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    doDatasetUpload();
                }
            });
    uploadDatasetBtn.setVisible(isUploadPermitted() && !UIRegistry.isMobile());
    uploadDatasetBtn.setEnabled(canUpload());
    if (!uploadDatasetBtn.isEnabled()) {
        uploadDatasetBtn.setToolTipText(getResourceString("WB_UPLOAD_IN_PROGRESS"));
    }

    // listen to selection changes to enable/disable certain buttons
    spreadSheet.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                JStatusBar statusBar = UIRegistry.getStatusBar();
                statusBar.setText("");

                currentRow = spreadSheet.getSelectedRow();
                updateBtnUI();
            }
        }
    });

    for (int c = 0; c < spreadSheet.getTableHeader().getColumnModel().getColumnCount(); c++) {
        // TableColumn column =
        // spreadSheet.getTableHeader().getColumnModel().getColumn(spreadSheet.getTableHeader().getColumnModel().getColumnCount()-1);
        TableColumn column = spreadSheet.getTableHeader().getColumnModel().getColumn(c);
        column.setCellRenderer(new WbCellRenderer());
    }

    // setup the JFrame to show images attached to WorkbenchRows
    imageFrame = new ImageFrame(mapSize, this, this.workbench, task, isReadOnly);

    // setup the JFrame to show images attached to WorkbenchRows
    imageImportFrame = new ImageImportFrame(this, this.workbench);

    setupWorkbenchRowChangeListener();

    // setup window minimizing/maximizing listener
    JFrame topFrame = (JFrame) UIRegistry.getTopWindow();
    minMaxWindowListener = new WindowAdapter() {
        @Override
        public void windowDeiconified(WindowEvent e) {
            if (imageFrame != null && imageFrame.isVisible()) {
                imageFrame.setExtendedState(Frame.NORMAL);
            }
            if (mapFrame != null && mapFrame.isVisible()) {
                mapFrame.setExtendedState(Frame.NORMAL);
            }
        }

        @Override
        public void windowIconified(WindowEvent e) {
            if (imageFrame != null && imageFrame.isVisible()) {
                imageFrame.setExtendedState(Frame.ICONIFIED);
            }
            if (mapFrame != null && mapFrame.isVisible()) {
                mapFrame.setExtendedState(Frame.ICONIFIED);
            }
        }
    };
    topFrame.addWindowListener(minMaxWindowListener);

    if (!isReadOnly) {
        showHideUploadToolBtn = createIconBtn("ValidateWB", IconManager.IconSize.NonStd,
                "WB_HIDE_UPLOADTOOLPANEL", false, new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        if (uploadToolPanel.isExpanded()) {
                            hideUploadToolPanel();
                            showHideUploadToolBtn.setToolTipText(getResourceString("WB_SHOW_UPLOADTOOLPANEL"));
                        } else {
                            showUploadToolPanel();
                            showHideUploadToolBtn.setToolTipText(getResourceString("WB_HIDE_UPLOADTOOLPANEL"));
                        }
                    }
                });
        showHideUploadToolBtn.setEnabled(true);
    }

    // setup the mapping features
    mapFrame = new JFrame();
    mapFrame.setIconImage(IconManager.getImage("AppIcon").getImage());
    mapFrame.setTitle(getResourceString("WB_GEO_REF_DATA_MAP"));
    mapImageLabel = createLabel("");
    mapImageLabel.setSize(500, 500);
    mapFrame.add(mapImageLabel);
    mapFrame.setSize(500, 500);

    // start putting together the visible UI
    CellConstraints cc = new CellConstraints();

    JComponent[] compsArray = { addRowsBtn, deleteRowsBtn, clearCellsBtn, /*showMapBtn,*/ exportKmlBtn,
            geoRefToolBtn, convertGeoRefFormatBtn, exportExcelCsvBtn, uploadDatasetBtn, showHideUploadToolBtn };
    Vector<JComponent> availableComps = new Vector<JComponent>(
            compsArray.length + workBenchPluginSSBtns.size());
    for (JComponent c : compsArray) {
        if (c != null) {
            availableComps.add(c);
        }
    }
    for (JComponent c : workBenchPluginSSBtns) {
        availableComps.add(c);
    }

    PanelBuilder spreadSheetControlBar = new PanelBuilder(new FormLayout(
            "f:p:g,4px," + createDuplicateJGoodiesDef("p", "4px", availableComps.size()) + ",4px,", "c:p:g"));

    int x = 3;
    for (JComponent c : availableComps) {
        spreadSheetControlBar.add(c, cc.xy(x, 1));
        x += 2;
    }

    int h = 0;
    Vector<WorkbenchTemplateMappingItem> headers = new Vector<WorkbenchTemplateMappingItem>();
    headers.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems());
    Collections.sort(headers);
    for (WorkbenchTemplateMappingItem mi : headers) {
        //using the workbench data model table. Not the actual specify table the column is mapped to.
        //This MIGHT be less confusing
        //System.out.println("setting header renderer for " + mi.getTableName() + "." + mi.getFieldName()); 
        spreadSheet.getColumnModel().getColumn(h++)
                .setHeaderRenderer(new WbTableHeaderRenderer(mi.getTableName()));
    }

    // NOTE: This needs to be done after the creation of the saveBtn. And after the creation of the header renderes.
    initColumnSizes(spreadSheet, saveBtn);

    // Create the Form Pane  -- needs to be done after initColumnSizes - which also sets cell editors for collumns
    if (task instanceof SGRTask) {
        formPane = new SGRFormPane(this, workbench, isReadOnly);
    } else {
        formPane = new FormPane(this, workbench, isReadOnly);
    }

    // This panel contains just the ResultSetContoller, it's needed so the RSC gets centered
    PanelBuilder rsPanel = new PanelBuilder(new FormLayout("c:p:g", "c:p:g"));
    FormValidator dummy = new FormValidator(null);
    dummy.setEnabled(true);
    resultsetController = new ResultSetController(dummy, !isReadOnly, !isReadOnly, false,
            getResourceString("Record"), model.getRowCount(), true);
    resultsetController.addListener(formPane);
    if (!isReadOnly) {
        resultsetController.getDelRecBtn().addActionListener(delAction);
    }
    //        else
    //        {
    //            resultsetController.getDelRecBtn().setVisible(false);
    //        }
    rsPanel.add(resultsetController.getPanel(), cc.xy(1, 1));

    // This panel is a single row containing the ResultSetContoller and the other controls for the Form Panel
    String colspec = "f:p:g, p, f:p:g, p";
    for (int i = 0; i < workBenchPluginFormBtns.size(); i++) {
        colspec = colspec + ", f:p, p";
    }

    PanelBuilder resultSetPanel = new PanelBuilder(new FormLayout(colspec, "c:p:g"));
    // Now put the two panel into the single row panel
    resultSetPanel.add(rsPanel.getPanel(), cc.xy(2, 1));
    if (!isReadOnly) {
        resultSetPanel.add(formPane.getControlPropsBtn(), cc.xy(4, 1));
    }
    int ccx = 6;
    for (JComponent c : workBenchPluginFormBtns) {
        resultSetPanel.add(c, cc.xy(ccx, 1));
        ccx += 2;
    }

    // Create the main panel that uses card layout for the form and spreasheet
    mainPanel = new JPanel(cardLayout = new CardLayout());

    // Add the Form and Spreadsheet to the CardLayout
    mainPanel.add(spreadSheet.getScrollPane(), PanelType.Spreadsheet.toString());
    mainPanel.add(formPane.getPane(), PanelType.Form.toString());

    // The controllerPane is a CardLayout that switches between the Spreadsheet control bar and the Form Control Bar
    controllerPane = new JPanel(cpCardLayout = new CardLayout());
    controllerPane.add(spreadSheetControlBar.getPanel(), PanelType.Spreadsheet.toString());
    controllerPane.add(resultSetPanel.getPanel(), PanelType.Form.toString());

    JLabel sep1 = new JLabel(IconManager.getIcon("Separator"));
    JLabel sep2 = new JLabel(IconManager.getIcon("Separator"));
    ssFormSwitcher = createSwitcher();

    // This works
    setLayout(new BorderLayout());

    boolean doDnDImages = AppPreferences.getLocalPrefs().getBoolean("WB_DND_IMAGES", false);
    JComponent[] ctrlCompArray1 = { importImagesBtn, toggleImageFrameBtn, carryForwardBtn, sep1, saveBtn, sep2,
            ssFormSwitcher };
    JComponent[] ctrlCompArray2 = { toggleImageFrameBtn, carryForwardBtn, sep1, saveBtn, sep2, ssFormSwitcher };
    JComponent[] ctrlCompArray = doDnDImages ? ctrlCompArray1 : ctrlCompArray2;

    Vector<Pair<JComponent, Integer>> ctrlComps = new Vector<Pair<JComponent, Integer>>();
    for (JComponent c : ctrlCompArray) {
        ctrlComps.add(new Pair<JComponent, Integer>(c, null));
    }

    String layoutStr = "";
    int compCount = 0;
    int col = 1;
    int pos = 0;
    for (Pair<JComponent, Integer> c : ctrlComps) {
        JComponent comp = c.getFirst();
        if (comp != null) {
            boolean addComp = !(comp == sep1 || comp == sep2) || compCount > 0;
            if (!addComp) {
                c.setFirst(null);
            } else {
                if (!StringUtils.isEmpty(layoutStr)) {
                    layoutStr += ",";
                    col++;
                    if (pos < ctrlComps.size() - 1) {
                        //this works because we know ssFormSwitcher is last and always non-null.
                        layoutStr += "6px,";
                        col++;
                    }
                }
                c.setSecond(col);
                if (comp == sep1 || comp == sep2) {
                    layoutStr += "6px";
                    compCount = 0;
                } else {
                    layoutStr += "p";
                    compCount++;
                }
            }
        }
        pos++;
    }
    PanelBuilder ctrlBtns = new PanelBuilder(new FormLayout(layoutStr, "c:p:g"));
    for (Pair<JComponent, Integer> c : ctrlComps) {
        if (c.getFirst() != null) {
            ctrlBtns.add(c.getFirst(), cc.xy(c.getSecond(), 1));
        }
    }

    add(mainPanel, BorderLayout.CENTER);

    FormLayout formLayout = new FormLayout("f:p:g,4px,p", "2px,f:p:g,p:g,p:g");
    PanelBuilder builder = new PanelBuilder(formLayout);

    builder.add(controllerPane, cc.xy(1, 2));
    builder.add(ctrlBtns.getPanel(), cc.xy(3, 2));

    if (!isReadOnly) {
        uploadToolPanel = new UploadToolPanel(this, UploadToolPanel.EXPANDED);
        uploadToolPanel.createUI();
        //            showHideUploadToolBtn = createIconBtn("ValidateWB", IconManager.IconSize.NonStd, "WB_HIDE_UPLOADTOOLPANEL", false, new ActionListener()
        //            {
        //                public void actionPerformed(ActionEvent ae)
        //                {
        //                    if (uploadToolPanel.isExpanded())
        //                    {
        //                       hideUploadToolPanel();
        //                       showHideUploadToolBtn.setToolTipText(getResourceString("WB_SHOW_UPLOADTOOLPANEL"));
        //                    } else
        //                    {
        //                       showUploadToolPanel();
        //                       showHideUploadToolBtn.setToolTipText(getResourceString("WB_HIDE_UPLOADTOOLPANEL"));
        //                   }
        //                }
        //            });
        //            showHideUploadToolBtn.setEnabled(true);
    }

    builder.add(uploadToolPanel, cc.xywh(1, 3, 3, 1));
    builder.add(findPanel, cc.xywh(1, 4, 3, 1));

    add(builder.getPanel(), BorderLayout.SOUTH);

    resultsetController.addListener(new ResultSetControllerListener() {
        public boolean indexAboutToChange(int oldIndex, int newIndex) {
            return true;
        }

        public void indexChanged(int newIndex) {
            if (imageFrame != null) {
                if (newIndex > -1) {
                    int index = spreadSheet.convertRowIndexToModel(newIndex);
                    imageFrame.setRow(workbench.getRow(index));
                } else {
                    imageFrame.setRow(null);
                }
            }
        }

        public void newRecordAdded() {
            // do nothing
        }
    });
    //compareSchemas();
    if (getIncremental() && workbenchValidator == null) {
        buildValidator();
    }

    //        int c = 0;
    //        Vector<WorkbenchTemplateMappingItem> headers = new Vector<WorkbenchTemplateMappingItem>();
    //        headers.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems());
    //        Collections.sort(headers);
    //        for (WorkbenchTemplateMappingItem mi : headers)
    //        {
    //           //using the workbench data model table. Not the actual specify table the column is mapped to.
    //           //This MIGHT be less confusing
    //           //System.out.println("setting header renderer for " + mi.getTableName() + "." + mi.getFieldName()); 
    //           spreadSheet.getColumnModel().getColumn(c++).setHeaderRenderer(new WbTableHeaderRenderer(mi.getTableName()));
    //        }
    //        
    //        // NOTE: This needs to be done after the creation of the saveBtn. And after the creation of the header renderes.
    //        initColumnSizes(spreadSheet, saveBtn);

    // See if we need to make the Image Frame visible
    // Commenting this out for now because it is so annoying.

    if (showImageView || hasOneOrMoreImages) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                toggleImageFrameVisible();

                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        final Frame f = (Frame) UIRegistry.get(UIRegistry.FRAME);
                        f.toFront();
                        f.requestFocus();
                    }
                });
            }
        });
    }

    ((WorkbenchTask) ContextMgr.getTaskByClass(WorkbenchTask.class)).opening(this);
    ((SGRTask) ContextMgr.getTaskByClass(SGRTask.class)).opening(this);
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java

/**
 * Shows / Hides the Image Window. //from   www.  j a  v a  2  s .co  m
 */
public void setImageFrameVisible(final boolean visible, final JFrame imgFrame, final JButton toolBtn,
        final String ttHelpVisible, final String ttHelpHidden, final String helpContext) {
    if (visible == imgFrame.isVisible()) {
        return;
    }

    if (spreadSheet.getCellEditor() != null) {
        spreadSheet.getCellEditor().stopCellEditing();
    }

    // and add or remove the ListSelectionListener (to avoid loading images when not visible)
    if (!visible) {
        spreadSheet.setTransferHandler(null);

        // hide the image window

        // turn off alwaysOnTop for Swing repaint reasons (prevents a lock up)
        if (imgFrame.isAlwaysOnTop()) {
            imgFrame.setAlwaysOnTop(false);
        }
        // if the image frame is minimized or iconified, set it to fully visible before doing anything else
        if (imgFrame.getState() == Frame.ICONIFIED) {
            imgFrame.setState(Frame.NORMAL);
        }
        toolBtn.setToolTipText(getResourceString(ttHelpVisible));

        spreadSheet.getSelectionModel().removeListSelectionListener(workbenchRowChangeListener);

        // set the image window and the image column invisible
        imgFrame.setVisible(false);
        imageColExt.setVisible(false);
    } else {
        spreadSheet.setTransferHandler(new WBImageTransferable());

        // show the image window

        UIHelper.positionFrameRelativeToTopFrame(imgFrame);

        // when a user hits the "show image" button, for some reason the selection gets nullified
        // so we'll grab it here, then set it at the end of this method

        toolBtn.setToolTipText(getResourceString(ttHelpHidden));

        spreadSheet.getSelectionModel().addListSelectionListener(workbenchRowChangeListener);
        HelpMgr.setHelpID(this, helpContext);

        // set the image window and the image column visible
        imgFrame.setVisible(true);
        imageColExt.setVisible(true);

        // if the image frame is minimized or iconified, set it to fully visible before doing anything else
        if (imgFrame.getState() == Frame.ICONIFIED) {
            imgFrame.setState(Frame.NORMAL);
        }

        showCardImageForSelectedRow();

        // Without this code below the Image Column doesn't get selected
        // when toggling 
        if (currentPanelType == PanelType.Spreadsheet && currentRow != -1) {
            spreadSheet.setRowSelectionInterval(currentRow, currentRow);
            spreadSheet.setColumnSelectionInterval(0, spreadSheet.getColumnCount() - 1);
            spreadSheet.scrollToRow(Math.min(currentRow + 4, model.getRowCount()));
        }

        TableColumn column = spreadSheet.getTableHeader().getColumnModel()
                .getColumn(spreadSheet.getTableHeader().getColumnModel().getColumnCount() - 1);
        column.setCellRenderer(new WbCellRenderer());
        spreadSheet.repaint();
    }
}