Example usage for javax.swing WindowConstants DO_NOTHING_ON_CLOSE

List of usage examples for javax.swing WindowConstants DO_NOTHING_ON_CLOSE

Introduction

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

Prototype

int DO_NOTHING_ON_CLOSE

To view the source code for javax.swing WindowConstants DO_NOTHING_ON_CLOSE.

Click Source Link

Document

The do-nothing default window close operation.

Usage

From source file:corelyzer.ui.CorelyzerApp.java

private void setupUI() {
    String versionNumber = CorelyzerApp.getApp().getCorelyzerVersion();
    if ((versionNumber == null) || versionNumber.equals("")) {
        versionNumber = "undetermined";
    }//from   w  w  w .  j  a v  a2  s.  c  om

    this.baseTitle = "Corelyzer " + versionNumber;

    mainFrame = new JFrame(baseTitle);
    mainFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    mainFrame.setSize(320, 100);
    mainFrame.setLocation(600, 100);
    mainFrame.addWindowListener(this);

    GridLayout layout = new GridLayout(1, 1);
    mainFrame.getContentPane().setLayout(layout);

    rootPanel = new JPanel(new GridLayout(1, 5));
    rootPanel.setBorder(BorderFactory.createTitledBorder("Main Panel"));

    // add lists/panels
    JPanel sessionPanel = new JPanel(new GridLayout(1, 1));
    sessionPanel.setBorder(BorderFactory.createTitledBorder("Session"));
    sessionList = new JList(getSessionListModel());
    sessionList.setName("SessionList");
    sessionList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    sessionList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(final ListSelectionEvent event) {
            int idx = sessionList.getSelectedIndex();
            if (idx >= 0) {
                CoreGraph cg = CoreGraph.getInstance();
                cg.setCurrentSessionIdx(idx);
            }
        }
    });
    sessionList.addMouseListener(this);
    JScrollPane sessionScrollPane = new JScrollPane(sessionList);
    sessionPanel.add(sessionScrollPane);
    rootPanel.add(sessionPanel);

    JPanel trackPanel = new JPanel(new GridLayout(1, 1));
    trackPanel.setBorder(BorderFactory.createTitledBorder("Track"));
    trackList = new JList(getTrackListModel());
    trackList.setName("TrackList");
    trackList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    trackList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(final ListSelectionEvent event) {
            int idx = trackList.getSelectedIndex();
            if (idx >= 0) {
                CoreGraph cg = CoreGraph.getInstance();
                cg.setCurrentTrackIdx(idx);
                updateHighlightedSections();
            }
        }
    });
    trackList.addMouseListener(this);
    JScrollPane trackScrollPane = new JScrollPane(trackList);
    trackPanel.add(trackScrollPane);
    rootPanel.add(trackPanel);

    JPanel sectionsPanel = new JPanel(new GridLayout(1, 1));
    sectionsPanel.setBorder(BorderFactory.createTitledBorder("Sections"));
    sectionList = new JList(getSectionListModel());
    sectionList.setName("SectionList");
    sectionList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(final ListSelectionEvent event) {
            if (event.getValueIsAdjusting())
                return;
            updateHighlightedSections();
        }
    });
    sectionList.addMouseListener(this);
    JScrollPane sectionsScrollPane = new JScrollPane(sectionList);
    sectionsPanel.add(sectionsScrollPane);
    rootPanel.add(sectionsPanel);

    JPanel dataFilesPanel = new JPanel(new GridLayout(1, 1));
    dataFilesPanel.setBorder(BorderFactory.createTitledBorder("Data Files"));
    dataFileList = new JList(getDataFileListModel());
    dataFileList.setName("DatafileList");
    dataFileList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    dataFileList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(final ListSelectionEvent event) {
            int idx = dataFileList.getSelectedIndex();
            if (idx >= 0) {
                CoreGraph cg = CoreGraph.getInstance();
                cg.setCurrentDatasetIdx(idx);
            }
        }
    });
    dataFileList.addMouseListener(this);
    JScrollPane dataFilesScrollPane = new JScrollPane(dataFileList);
    dataFilesPanel.add(dataFilesScrollPane);
    rootPanel.add(dataFilesPanel);

    JPanel fieldsPanel = new JPanel(new GridLayout(1, 1));
    fieldsPanel.setBorder(BorderFactory.createTitledBorder("Fields"));
    fieldList = new JList(getFieldListModel());
    fieldList.setName("FieldList");
    fieldList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    fieldList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(final ListSelectionEvent event) {
            int idx = fieldList.getSelectedIndex();
            if (idx >= 0) {
                CoreGraph cg = CoreGraph.getInstance();
                cg.setCurrentFieldIdx(idx);
            }
        }
    });
    JScrollPane fieldsScrollPane = new JScrollPane(fieldList);
    fieldsPanel.add(fieldsScrollPane);
    rootPanel.add(fieldsPanel);

    mainFrame.getContentPane().add(rootPanel);

    setupMenuStuff();
    setupPopupMenu();

    // init new mode tool frame
    toolFrame = new CRToolPalette();
    toolFrame.pack();
    int canvasWidth = preferences().screenWidth;
    Dimension mydim = toolFrame.getSize();
    int myLocX = canvasWidth / 2 - mydim.width / 2;
    toolFrame.setLocation(myLocX, 0);
    toolFrame.setVisible(true);

    // delete key listener on track and section list
    KeyListener listKeyListener = new KeyListener() {
        public void keyPressed(final KeyEvent keyEvent) {
        }

        public void keyReleased(final KeyEvent keyEvent) {

            int keyCode = keyEvent.getKeyCode();

            if (keyCode == KeyEvent.VK_DELETE) {
                Object actionSource = keyEvent.getSource();

                if (actionSource.equals(trackList)) {
                    controller.deleteSelectedTrack();
                } else if (actionSource.equals(sectionList)) {
                    int[] rows = getSectionList().getSelectedIndices();
                    onDeleteSelectedSections(rows);
                }
            }
        }

        public void keyTyped(final KeyEvent keyEvent) {
        }
    };

    trackList.addKeyListener(listKeyListener);
    sectionList.addKeyListener(listKeyListener);
}

From source file:edu.ku.brc.specify.Specify.java

/**
 * Restarts the app with a new or old database and user name and creates the core app UI.
 * @param window the login window//from  www  .j a v a  2 s . c o m
 * @param databaseNameArg the database name
 * @param userNameArg the user name
 * @param startOver tells the AppContext to start over
 * @param firstTime indicates this is the first time in the app and it should create all the UI for the core app
 */
public void restartApp(final Window window, final String databaseNameArg, final String userNameArg,
        final boolean startOver, final boolean firstTime) {
    log.debug("restartApp"); //$NON-NLS-1$
    if (dbLoginPanel != null) {
        dbLoginPanel.getStatusBar().setText(getResourceString("Specify.INITIALIZING_APP")); //$NON-NLS-1$
    }

    if (!firstTime) {
        checkAndSendStats();
    }

    UIRegistry.dumpPaths();

    try {
        AppPreferences.getLocalPrefs().flush();
    } catch (BackingStoreException ex) {
    }

    AppPreferences.shutdownRemotePrefs();
    AppPreferences.shutdownPrefs();
    AppPreferences.setConnectedToDB(false);

    // Moved here because context needs to be set before loading prefs, we need to know the SpecifyUser
    //
    // NOTE: AppPreferences.startup(); is called inside setContext's implementation.
    //
    AppContextMgr.reset();
    AppContextMgr.CONTEXT_STATUS status = AppContextMgr.getInstance().setContext(databaseNameArg, userNameArg,
            startOver, firstTime, !firstTime);
    if (status == AppContextMgr.CONTEXT_STATUS.OK) {
        // XXX Temporary Fix!
        SpecifyUser spUser = AppContextMgr.getInstance().getClassObject(SpecifyUser.class);

        if (spUser != null) {
            String dbPassword = spUser.getPassword();

            if (StringUtils.isNotEmpty(dbPassword) && (!StringUtils.isAlphanumeric(dbPassword)
                    || !UIHelper.isAllCaps(dbPassword) || dbPassword.length() < 25)) {
                String encryptedPassword = Encryption.encrypt(spUser.getPassword(), spUser.getPassword());
                spUser.setPassword(encryptedPassword);
                DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
                try {
                    session.beginTransaction();
                    session.saveOrUpdate(session.merge(spUser));
                    session.commit();

                } catch (Exception ex) {
                    session.rollback();
                    ex.printStackTrace();
                } finally {
                    session.close();
                }
            }
        }
    }

    UsageTracker.setUserInfo(databaseNameArg, userNameArg);

    SpecifyAppPrefs.initialPrefs();

    // Check Stats (this is mostly for the first time in.
    AppPreferences appPrefs = AppPreferences.getRemote();
    Boolean canSendStats = appPrefs.getBoolean(sendStatsPrefName, null); //$NON-NLS-1$
    Boolean canSendISAStats = appPrefs.getBoolean(sendISAStatsPrefName, null); //$NON-NLS-1$

    // Make sure we have the proper defaults
    if (canSendStats == null) {
        canSendStats = true;
        appPrefs.putBoolean("usage_tracking.send_stats", canSendStats); //$NON-NLS-1$
    }

    if (canSendISAStats == null) {
        canSendISAStats = true;
        appPrefs.putBoolean(sendISAStatsPrefName, canSendISAStats); //$NON-NLS-1$
    }

    if (status == AppContextMgr.CONTEXT_STATUS.OK) {
        // XXX Get the current locale from prefs PREF

        if (AppContextMgr.getInstance().getClassObject(Discipline.class) == null) {
            return;
        }

        // "false" means that it should use any cached values it can find to automatically initialize itself
        if (firstTime) {
            GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment()
                    .getDefaultScreenDevice().getDefaultConfiguration();

            initialize(gc);

            topFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
            UIRegistry.register(UIRegistry.FRAME, topFrame);
        } else {
            SubPaneMgr.getInstance().closeAll();
        }

        preInitializePrefs();

        initStartUpPanels(databaseNameArg, userNameArg);

        AppPrefsCache.addChangeListener("ui.formatting.scrdateformat", UIFieldFormatterMgr.getInstance());

        if (changeCollectionMenuItem != null) {
            changeCollectionMenuItem.setEnabled(
                    ((SpecifyAppContextMgr) AppContextMgr.getInstance()).getNumOfCollectionsForUser() > 1);
        }

        if (window != null) {
            window.setVisible(false);
        }

        // General DB Fixes independent of a release.
        if (!AppPreferences.getGlobalPrefs().getBoolean("CollectingEventsAndAttrsMaint1", false)) {
            // Temp Code to Fix issues with Release 6.0.9 and below
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    CollectingEventsAndAttrsMaint dbMaint = new CollectingEventsAndAttrsMaint();
                    dbMaint.performMaint();
                }
            });
        }

        /*if (!AppPreferences.getGlobalPrefs().getBoolean("FixAgentToDisciplinesV2", false))
        {
        // Temp Code to Fix issues with Release 6.0.9 and below
        SwingUtilities.invokeLater(new Runnable() 
        {
            @Override
            public void run()
            {
                FixDBAfterLogin fixer = new FixDBAfterLogin();
                fixer.fixAgentToDisciplines();
            }
        });
        }*/

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                performManualDBUdpatesAfterLogin();
            }
        });

        DataBuilder.mergeStandardGroups(AppContextMgr.getInstance().getClassObject(Collection.class));

    } else if (status == AppContextMgr.CONTEXT_STATUS.Error) {

        if (dbLoginPanel != null) {
            dbLoginPanel.getWindow().setVisible(false);
        }

        if (AppContextMgr.getInstance().getClassObject(Collection.class) == null) {

            // TODO This is really bad because there is a Database Login with no Specify login
            JOptionPane.showMessageDialog(null, getResourceString("Specify.LOGIN_USER_MISMATCH"), //$NON-NLS-1$
                    getResourceString("Specify.LOGIN_USER_MISMATCH_TITLE"), //$NON-NLS-1$
                    JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }

    }

    CommandDispatcher.dispatch(new CommandAction("App", firstTime ? "StartUp" : "AppRestart", null)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    TaskMgr.requestInitalContext();

    if (!UIRegistry.isRelease()) {
        DebugLoggerDialog dialog = new DebugLoggerDialog(null);
        dialog.configureLoggers();
    }

    showApp();

    if (dbLoginPanel != null) {
        dbLoginPanel.getWindow().setVisible(false);
        dbLoginPanel = null;
    }
    setDatabaseNameAndCollection();
}

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

/**
 * @param titleKey//  w w  w  .  j  a v a  2 s.c o  m
 * @param msgKey
 * @param logins
 * @param includeOverride whether to include asking the user to clear all logged in users
 * @return CustomDialog.NONE_BTN - no one on, CustomDialog.OK_BTN user are on do override, 
 * CustomDialog.OK_CANCEL users logged on, but don't override
 */
public int displayAgentsLoggedInDlg(final String titleKey, final String msgKey, final List<String> logins,
        final boolean includeOverride) {

    if (logins.size() > 0) {
        SpecifyUser currUser = AppContextMgr.getInstance().getClassObject(SpecifyUser.class);

        String sql = "SELECT Name, IsLoggedIn, IsLoggedInReport, LoginCollectionName, LoginDisciplineName FROM specifyuser WHERE IsLoggedIn <> 0 AND SpecifyUserID <> "
                + currUser.getId();
        Vector<Object[]> dataRows = BasicSQLUtils.query(sql);
        if (dataRows.size() > 0) {
            Object[][] rows = new Object[dataRows.size()][4];
            for (int i = 0; i < rows.length; i++) {
                rows[i] = dataRows.get(i);
            }
            DefaultTableModel model = new DefaultTableModel(rows, new Object[] { "User", "Is Logged In",
                    "Is Logged In to Report", "Login Collection", "Login Discipline" });
            JTable table = new JTable(model);
            UIHelper.calcColumnWidths(table, 5);
            UIHelper.makeTableHeadersCentered(table, true);

            JScrollPane scrollPane = UIHelper.createScrollPane(table);

            String rowDef = "f:p:g, 2dlu, f:p:g, 2dlu, f:p:g";
            int btns = includeOverride ? CustomDialog.OKCANCEL : CustomDialog.OK_BTN;
            String titleStr = UIRegistry.getResourceString(titleKey != null ? titleKey : L10N + "OU_TITLE");
            CellConstraints cc = new CellConstraints();
            PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", rowDef));

            pb.add(UIHelper.createI18NLabel(L10N + "OTHER_USERS"), cc.xy(1, 1));
            pb.add(scrollPane, cc.xy(1, 3));
            pb.add(UIHelper.createI18NLabel(msgKey), cc.xy(1, 5));

            pb.setDefaultDialogBorder();

            CustomDialog infoDlg = new CustomDialog((Dialog) null, titleStr, true, btns, pb.getPanel());

            if (includeOverride)
                infoDlg.setOkLabel(UIRegistry.getResourceString(L10N + "LOGIN_OVRDE"));

            infoDlg.createUI();
            infoDlg.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
            UIHelper.centerAndShow(infoDlg);
            return infoDlg.getBtnPressed();
        }
    }
    return CustomDialog.NONE_BTN;
}

From source file:com.osparking.osparking.Settings_System.java

private void tryToCloseSettingsForm() {
    if (SettingsSaveButton.isEnabled()) {
        JOptionPane.showMessageDialog(this, "Settings Changed.\n \n" + "Either [Save] or [Cancel], please.",
                "Confirm Request", JOptionPane.WARNING_MESSAGE);
        this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    } else {//from   w w  w . ja v  a 2  s  . c o  m
        if (mainForm != null) {
            mainForm.getTopForms()[TopForms.Settings.ordinal()] = null;
        }

        if (isStand_Alone) {
            this.setVisible(false);
            System.exit(0);
        } else {
            dispose();
        }
    }
}

From source file:nl.tudelft.goal.SimpleIDE.SimpleIDE.java

/**
 * Creates the IDE interface and related services.
 *//*  w ww. j  a va 2 s.  co m*/
public SimpleIDE() throws InstantiationException, IllegalAccessException {
    // Do not use InfoLog; nothing is subscribed yet.
    System.out.println("Launching IDE"); //$NON-NLS-1$

    /**
     * Checks whether logs should be rerouted to console as well. Set to
     * false by default. Only to be used for debugging purposes by
     * developers; change via settings file.
     */
    if (LoggingPreferences.getShowLogsInConsole()) {
        Loggers.addConsoleLogger();
    }

    // Initialize the action factory.
    ActionFactory.getFactory(this, new IDETempState());

    // Set look and feel.
    setLookAndFeel();

    /**
     * Set size first, otherwise it is not clear how the fractional values
     * e.g. for setDividerLocation work out.
     */
    setSize(IDEPreferences.getWinWidth(), IDEPreferences.getWinHeight());
    if (IDEPreferences.getRememberWinPos()) {
        setLocation(IDEPreferences.getWinX(), IDEPreferences.getWinY());
    }
    setTitle("GOAL IDE"); //$NON-NLS-1$

    setLayout(new BorderLayout());

    // Add center panel; do this before adding tool bar which depends on it
    // for initialization of buttons.
    this.mainPanel = new IDEMainPanel(this);
    add(this.mainPanel, BorderLayout.CENTER);
    this.statusBar = new StatusBar();
    add(this.statusBar, BorderLayout.SOUTH);

    // Add menu.
    setJMenuBar(new IDEMenuBar());

    // Add tool bar.
    add(new ToolBar(), BorderLayout.PAGE_START);
    setVisible(true);

    if (System.getProperty("os.name").equals("Mac OS X")) { //$NON-NLS-1$ //$NON-NLS-2$
        OSXAdapter.setQuitHandler(new Runnable() {
            @Override
            public void run() {
                try {
                    ActionFactory.getAction(QuitAction.class).Execute(null, null);
                } catch (IllegalAccessException | InstantiationException | GOALException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    // Disable default close operation and install quit "button" handler.
    setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            try {
                ActionFactory.getAction(QuitAction.class).Execute(null, null);
            } catch (Exception er) {
                System.out.println("BUG: QUIT FAILED"); //$NON-NLS-1$
                er.printStackTrace();
            }
        }
    });
    addComponentListener(new ComponentAdapter() {
        @Override
        public void componentMoved(ComponentEvent e) {
            IDEPreferences.setLastWinPos(getLocation());
        }

        @Override
        public void componentResized(ComponentEvent e) {
            IDEPreferences.setLastWinSize(getSize());
        }
    });

    // Set initial content of file panel.
    // TODO move application logic to platform manager.
    if (IDEPreferences.getReopenMASs()) {
        reopenMASs();
    }
    if (IDEPreferences.getReopenSpurious()) {
        reopenSpurious();
    }

    // IDE state has been configured. Broadcast the info.
    ActionFactory.broadcastStateChange(this);
}

From source file:ome.formats.importer.gui.FileQueueHandler.java

@SuppressWarnings("unchecked")
public void update(IObservable observable, ImportEvent event) {
    final OMEROMetadataStoreClient store = viewer.getLoginHandler().getMetadataStore();

    if (event instanceof ome.formats.importer.util.ErrorHandler.EXCEPTION_EVENT) {
        viewer.getErrorHandler().update(observable, event);

        if (event instanceof ome.formats.importer.util.ErrorHandler.UNKNOWN_FORMAT
                && fileChooser.getSelectedFiles().length == 1 && fileChooser.getSelectedFile().isFile()) {
            JOptionPane.showMessageDialog(viewer,
                    "This file's format is not recognized. \n" + "Perhaps the file is damaged?",
                    "Unknown Format", JOptionPane.WARNING_MESSAGE);
        }//from   w  ww  .j  av a 2s .  com

        if (event instanceof ome.formats.importer.util.ErrorHandler.FILE_EXCEPTION) {
            candidatesFormatException = true;
        }
    }

    if (event instanceof ome.formats.importer.util.ErrorHandler.MISSING_LIBRARY) {
        JOptionPane.showMessageDialog(viewer, "You appear to be missing a required library needed for \n"
                + "this file import. See the debug log messages for details.");
    }

    else if (event instanceof ImportCandidates.SCANNING) {
        addEnabled(false);

        ImportCandidates.SCANNING ev = (ImportCandidates.SCANNING) event;
        if (scanEx.isShutdown() || cancelScan) {
            log.info("Cancelling scan");
            ev.cancel();
            cancelScan = false;
        }

        if (ev.totalFiles < 0) {
            if (progressDialog == null) {
                double layoutTable[][] = { { 10, 180, 100, 10 }, // columns
                        { 5, 20, 5, 30, 5 } }; // rows

                progressDialog = new JDialog(viewer, "Processing Files");
                progressDialog.setSize(300, 90);
                progressDialog.setLocationRelativeTo(viewer);
                TableLayout layout = new TableLayout(layoutTable);
                progressDialog.setLayout(layout);
                directoryProgressBar = new JProgressBar();
                directoryProgressBar.setString("Please wait.");
                directoryProgressBar.setStringPainted(true);
                directoryProgressBar.setIndeterminate(true);
                progressDialog.add(directoryProgressBar, "1,1,2,1");
                JButton cancelBtn = new JButton("Cancel");

                progressDialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

                cancelBtn.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent event) {
                        cancelScan = true;
                        progressDialog.dispose();
                        progressDialog = null;
                        addEnabled(true);
                    }
                });

                progressDialog.add(cancelBtn, "2,3,R,C");
                progressDialog.getRootPane().setDefaultButton(cancelBtn);
                progressDialog.setVisible(true);
                progressDialog.toFront();
            }
        } else {
            if (progressDialog != null) {
                updateProgress(ev.totalFiles, ev.numFiles);
            }

            if (ev.totalFiles == ev.numFiles && progressDialog != null) {
                progressDialog.dispose();
                progressDialog = null;
                addEnabled(true);
            }
        }

        viewer.appendToOutput(
                "Processing files: Scanned " + ev.numFiles + " of " + ev.totalFiles + " total.\n");

        log.debug(ev.toLog());

    }

    else if (event instanceof ImportEvent.REIMPORT) {

        String objectName = "", projectName = "", fileName = "";
        Long objectID = 0L, projectID = 0L;
        File file = null;
        Integer finalCount = 0;
        IObject object;

        int[] selectedRows = null;

        if (historyTable != null)
            selectedRows = historyTable.eTable.getSelectedRows();

        for (int r : selectedRows) {
            Vector row = new Vector();

            objectID = (Long) historyTable.table.getValueAt(r, 5);
            projectID = (Long) historyTable.table.getValueAt(r, 6);

            fileName = (String) historyTable.table.getValueAt(r, 0);
            file = new File((String) historyTable.table.getValueAt(r, 4));

            if (projectID == null || projectID == 0) {
                object = null;

                try {
                    object = store.getTarget(Screen.class, objectID);
                    objectName = ((Screen) object).getName().getValue();
                } catch (Exception e) {
                    log.warn("Failed to retrieve screen: " + objectID, e);
                    continue;
                }
            } else {
                object = null;
                try {
                    object = store.getTarget(Dataset.class, objectID);
                    objectName = ((Dataset) object).getName().getValue();
                } catch (Exception e) {
                    log.warn("Failed to retrieve dataset: " + objectID, e);
                    continue;
                }

                try {
                    projectName = store.getProject(projectID).getName().getValue();
                } catch (Exception e) {
                    log.warn("Failed to retrieve project: " + projectID, e);
                    continue;
                }
            }

            // TODO: The 6th parameter should be 'format', not 'fileName'!
            ImportContainer container = new ImportContainer(file, projectID, object, cancelScan, null, fileName,
                    null, cancelScan);

            finalCount = finalCount + 1;

            Double[] pixelSizes = new Double[] { 1.0, 1.0, 1.0 };

            row.add(fileName);
            if (projectID == null || projectID == 0) {
                row.add(objectName);
            } else {
                row.add(projectName + "/" + objectName);
            }
            // WHY ISN'T THIS CODE USING addFiletoQueue?!!?
            row.add("added");
            row.add(container);
            row.add(file);
            row.add(false);
            row.add(projectID);
            row.add(pixelSizes);
            qTable.getTable().addRow(row);
        }

        if (finalCount == 0) {
            JOptionPane.showMessageDialog(viewer,
                    "None of the images in this history\n" + "list can be reimported.");
        } else if (finalCount == 1) {
            JOptionPane.showMessageDialog(viewer, "One of the images in this history list has been\n"
                    + "re-added to the import queue for reimport.");
        } else if (finalCount > 1) {
            JOptionPane.showMessageDialog(viewer,
                    finalCount + " images in this history list have been re-added\n"
                            + "to the import queue for reimport.");
        }

        if (qTable.getTable().getRowCount() > 0)
            qTable.importBtn.setEnabled(true);
        qTable.importBtn.doClick();
    }
}

From source file:op.care.supervisor.DlgHOReport.java

/**
 * This method is called from within the constructor to
 * initialize the form./*w  w  w  . j a va 2s. co  m*/
 * WARNING: Do NOT modify this code. The content of this method is
 * always regenerated by the PrinterForm Editor.
 */
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
    jScrollPane1 = new JScrollPane();
    txtReport = new JTextPane();
    panel1 = new JPanel();
    btnCancel = new JButton();
    btnSave = new JButton();

    //======== this ========
    setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            thisWindowClosing(e);
        }
    });
    Container contentPane = getContentPane();
    contentPane.setLayout(new FormLayout("default, $lcgap, default:grow, $lcgap, default",
            "2*(default, $lgap), fill:default:grow, $lgap, fill:default, $lgap, default"));

    //======== jScrollPane1 ========
    {
        jScrollPane1.setViewportView(txtReport);
    }
    contentPane.add(jScrollPane1, CC.xy(3, 5));

    //======== panel1 ========
    {
        panel1.setLayout(new BoxLayout(panel1, BoxLayout.X_AXIS));

        //---- btnCancel ----
        btnCancel.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/cancel.png")));
        btnCancel.setText(null);
        btnCancel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                btnCancelActionPerformed(e);
            }
        });
        panel1.add(btnCancel);

        //---- btnSave ----
        btnSave.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/apply.png")));
        btnSave.setText(null);
        btnSave.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                btnSaveActionPerformed(e);
            }
        });
        panel1.add(btnSave);
    }
    contentPane.add(panel1, CC.xy(3, 7, CC.RIGHT, CC.DEFAULT));
    setSize(462, 379);
    setLocationRelativeTo(null);
}

From source file:org.apache.log4j.chainsaw.LogUI.java

/**
 * Constructor which builds up all the visual elements of the frame including
 * the Menu bar/*from ww w.  ja va2  s. c o m*/
 */
public LogUI() {
    super("Chainsaw");
    setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

    if (ChainsawIcons.WINDOW_ICON != null) {
        setIconImage(new ImageIcon(ChainsawIcons.WINDOW_ICON).getImage());
    }
}

From source file:org.apache.log4j.chainsaw.LogUI.java

/**
 * Displays a dialog which will provide options for selecting a configuration
 *//*w w w .  j ava2  s .c  o  m*/
private void showReceiverConfigurationPanel() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            final JDialog dialog = new JDialog(LogUI.this, true);
            dialog.setTitle("Load events into Chainsaw");
            dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

            dialog.setResizable(false);

            receiverConfigurationPanel.setCompletionActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dialog.setVisible(false);

                    if (receiverConfigurationPanel.getModel().isCancelled()) {
                        return;
                    }
                    applicationPreferenceModel
                            .setShowNoReceiverWarning(!receiverConfigurationPanel.isDontWarnMeAgain());
                    //remove existing plugins
                    List plugins = pluginRegistry.getPlugins();
                    for (Iterator iter = plugins.iterator(); iter.hasNext();) {
                        Plugin plugin = (Plugin) iter.next();
                        //don't stop ZeroConfPlugin if it is registered
                        if (!plugin.getName().toLowerCase(Locale.ENGLISH).contains("zeroconf")) {
                            pluginRegistry.stopPlugin(plugin.getName());
                        }
                    }
                    URL configURL = null;

                    if (receiverConfigurationPanel.getModel().isNetworkReceiverMode()) {
                        int port = receiverConfigurationPanel.getModel().getNetworkReceiverPort();

                        try {
                            Class receiverClass = receiverConfigurationPanel.getModel()
                                    .getNetworkReceiverClass();
                            Receiver networkReceiver = (Receiver) receiverClass.newInstance();
                            networkReceiver.setName(receiverClass.getSimpleName() + "-" + port);

                            Method portMethod = networkReceiver.getClass().getMethod("setPort",
                                    new Class[] { int.class });
                            portMethod.invoke(networkReceiver, new Object[] { new Integer(port) });

                            networkReceiver.setThreshold(Level.TRACE);

                            pluginRegistry.addPlugin(networkReceiver);
                            networkReceiver.activateOptions();
                            receiversPanel.updateReceiverTreeInDispatchThread();
                        } catch (Exception e3) {
                            MessageCenter.getInstance().getLogger().error("Error creating Receiver", e3);
                            MessageCenter.getInstance().getLogger()
                                    .info("An error occurred creating your Receiver");
                        }
                    } else if (receiverConfigurationPanel.getModel().isLog4jConfig()) {
                        File log4jConfigFile = receiverConfigurationPanel.getModel().getLog4jConfigFile();
                        if (log4jConfigFile != null) {
                            try {
                                Map entries = LogFilePatternLayoutBuilder
                                        .getAppenderConfiguration(log4jConfigFile);
                                for (Iterator iter = entries.entrySet().iterator(); iter.hasNext();) {
                                    try {
                                        Map.Entry entry = (Map.Entry) iter.next();
                                        String name = (String) entry.getKey();
                                        Map values = (Map) entry.getValue();
                                        //values: conversion, file
                                        String conversionPattern = values.get("conversion").toString();
                                        File file = new File(values.get("file").toString());
                                        URL fileURL = file.toURI().toURL();
                                        String timestampFormat = LogFilePatternLayoutBuilder
                                                .getTimeStampFormat(conversionPattern);
                                        String receiverPattern = LogFilePatternLayoutBuilder
                                                .getLogFormatFromPatternLayout(conversionPattern);
                                        VFSLogFilePatternReceiver fileReceiver = new VFSLogFilePatternReceiver();
                                        fileReceiver.setName(name);
                                        fileReceiver.setAutoReconnect(true);
                                        fileReceiver.setContainer(LogUI.this);
                                        fileReceiver.setAppendNonMatches(true);
                                        fileReceiver.setFileURL(fileURL.toURI().toString());
                                        fileReceiver.setTailing(true);
                                        fileReceiver.setLogFormat(receiverPattern);
                                        fileReceiver.setTimestampFormat(timestampFormat);
                                        fileReceiver.setThreshold(Level.TRACE);
                                        pluginRegistry.addPlugin(fileReceiver);
                                        fileReceiver.activateOptions();
                                        receiversPanel.updateReceiverTreeInDispatchThread();
                                    } catch (URISyntaxException e1) {
                                        e1.printStackTrace();
                                    }
                                }
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                        }
                    } else if (receiverConfigurationPanel.getModel().isLoadConfig()) {
                        configURL = receiverConfigurationPanel.getModel().getConfigToLoad();
                    } else if (receiverConfigurationPanel.getModel().isLogFileReceiverConfig()) {
                        try {
                            URL fileURL = receiverConfigurationPanel.getModel().getLogFileURL();
                            if (fileURL != null) {
                                VFSLogFilePatternReceiver fileReceiver = new VFSLogFilePatternReceiver();
                                fileReceiver.setName(fileURL.getFile());
                                fileReceiver.setAutoReconnect(true);
                                fileReceiver.setContainer(LogUI.this);
                                fileReceiver.setAppendNonMatches(true);
                                fileReceiver.setFileURL(fileURL.toURI().toString());
                                fileReceiver.setTailing(true);
                                if (receiverConfigurationPanel.getModel().isPatternLayoutLogFormat()) {
                                    fileReceiver.setLogFormat(
                                            LogFilePatternLayoutBuilder.getLogFormatFromPatternLayout(
                                                    receiverConfigurationPanel.getModel().getLogFormat()));
                                } else {
                                    fileReceiver
                                            .setLogFormat(receiverConfigurationPanel.getModel().getLogFormat());
                                }
                                fileReceiver.setTimestampFormat(
                                        receiverConfigurationPanel.getModel().getLogFormatTimestampFormat());
                                fileReceiver.setThreshold(Level.TRACE);

                                pluginRegistry.addPlugin(fileReceiver);
                                fileReceiver.activateOptions();
                                receiversPanel.updateReceiverTreeInDispatchThread();
                            }
                        } catch (Exception e2) {
                            MessageCenter.getInstance().getLogger().error("Error creating Receiver", e2);
                            MessageCenter.getInstance().getLogger()
                                    .info("An error occurred creating your Receiver");
                        }
                    }
                    if (configURL == null && receiverConfigurationPanel.isDontWarnMeAgain()) {
                        //use the saved config file as the config URL if defined
                        if (receiverConfigurationPanel.getModel().getSaveConfigFile() != null) {
                            try {
                                configURL = receiverConfigurationPanel.getModel().getSaveConfigFile().toURI()
                                        .toURL();
                            } catch (MalformedURLException e1) {
                                e1.printStackTrace();
                            }
                        } else {
                            //no saved config defined but don't warn me is checked - use default config
                            configURL = receiverConfigurationPanel.getModel().getDefaultConfigFileURL();
                        }
                    }
                    if (configURL != null) {
                        MessageCenter.getInstance().getLogger()
                                .debug("Initialiazing Log4j with " + configURL.toExternalForm());
                        final URL finalURL = configURL;
                        new Thread(new Runnable() {
                            public void run() {
                                if (receiverConfigurationPanel.isDontWarnMeAgain()) {
                                    applicationPreferenceModel.setConfigurationURL(finalURL.toExternalForm());
                                } else {
                                    try {
                                        if (new File(finalURL.toURI()).exists()) {
                                            loadConfigurationUsingPluginClassLoader(finalURL);
                                        }
                                    } catch (URISyntaxException e) {
                                        //ignore
                                    }
                                }

                                receiversPanel.updateReceiverTreeInDispatchThread();
                            }
                        }).start();
                    }
                    File saveConfigFile = receiverConfigurationPanel.getModel().getSaveConfigFile();
                    if (saveConfigFile != null) {
                        ReceiversHelper.getInstance().saveReceiverConfiguration(saveConfigFile);
                    }
                }
            });

            receiverConfigurationPanel.setDialog(dialog);
            dialog.getContentPane().add(receiverConfigurationPanel);

            dialog.pack();

            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            dialog.setLocation((screenSize.width / 2) - (dialog.getWidth() / 2),
                    (screenSize.height / 2) - (dialog.getHeight() / 2));

            dialog.setVisible(true);
        }
    });
}

From source file:org.deegree.tools.rendering.viewer.File3dImporter.java

public static List<WorldRenderableObject> open(Frame parent, String fileName) {

    if (fileName == null || "".equals(fileName.trim())) {
        throw new InvalidParameterException("the file name may not be null or empty");
    }/*w w  w.j  a v  a2 s.c  om*/
    fileName = fileName.trim();

    CityGMLImporter openFile2;
    XMLInputFactory fac = XMLInputFactory.newInstance();
    InputStream in = null;
    try {
        XMLStreamReader reader = fac.createXMLStreamReader(in = new FileInputStream(fileName));
        reader.next();
        String ns = "http://www.opengis.net/citygml/1.0";
        openFile2 = new CityGMLImporter(null, null, null, reader.getNamespaceURI().equals(ns));
    } catch (Throwable t) {
        openFile2 = new CityGMLImporter(null, null, null, false);
    } finally {
        IOUtils.closeQuietly(in);
    }

    final CityGMLImporter openFile = openFile2;

    final JDialog dialog = new JDialog(parent, "Loading", true);

    dialog.getContentPane().setLayout(new BorderLayout());
    dialog.getContentPane().add(
            new JLabel("<HTML>Loading file:<br>" + fileName + "<br>Please wait!</HTML>", SwingConstants.CENTER),
            BorderLayout.NORTH);
    final JProgressBar progressBar = new JProgressBar();
    progressBar.setStringPainted(true);
    progressBar.setIndeterminate(false);
    dialog.getContentPane().add(progressBar, BorderLayout.CENTER);

    dialog.pack();
    dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    dialog.setResizable(false);
    dialog.setLocationRelativeTo(parent);

    final Thread openThread = new Thread() {
        /**
         * Opens the file in a separate thread.
         */
        @Override
        public void run() {
            // openFile.openFile( progressBar );
            if (dialog.isDisplayable()) {
                dialog.setVisible(false);
                dialog.dispose();
            }
        }
    };
    openThread.start();

    dialog.setVisible(true);
    List<WorldRenderableObject> result = null;
    try {
        result = openFile.importFromFile(fileName, 6, 2);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    gm = openFile.getQmList();

    //
    // if ( result != null ) {
    // openGLEventListener.addDataObjectToScene( result );
    // File f = new File( fileName );
    // setTitle( WIN_TITLE + f.getName() );
    // } else {
    // showExceptionDialog( "The file: " + fileName
    // + " could not be read,\nSee error log for detailed information." );
    // }
    return result;
}