Example usage for javax.swing JPanel setBackground

List of usage examples for javax.swing JPanel setBackground

Introduction

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

Prototype

@BeanProperty(preferred = true, visualUpdate = true, description = "The background color of the component.")
public void setBackground(Color bg) 

Source Link

Document

Sets the background color of this component.

Usage

From source file:org.isatools.isacreator.wizard.GeneralCreationAlgorithm.java

public JPanel instantiatePanel() {
    final JPanel generalQuestionCont = new JPanel();
    generalQuestionCont.setLayout(new BoxLayout(generalQuestionCont, BoxLayout.PAGE_AXIS));
    generalQuestionCont.setBackground(UIHelper.BG_COLOR);

    JLabel info = new JLabel("<html><b>" + assay.getMeasurementEndpoint() + "</b> using <b>"
            + assay.getTechnologyType() + "</b></html>", JLabel.LEFT);
    UIHelper.renderComponent(info, UIHelper.VER_12_PLAIN, UIHelper.GREY_COLOR, false);

    if (assay.getTechnologyType().equals("")) {
        info.setText("<html><b>" + assay.getMeasurementEndpoint() + "</html>");
    }//from   w w w .j av  a  2s.  c o  m

    info.setPreferredSize(new Dimension(300, 40));

    JPanel infoPanel = new JPanel(new GridLayout(1, 1));
    infoPanel.setBackground(UIHelper.BG_COLOR);

    infoPanel.add(info);

    generalQuestionCont.add(infoPanel);

    JPanel labelPanel = new JPanel(new GridLayout(1, 2));
    labelPanel.setBackground(UIHelper.BG_COLOR);

    labelCapture = new LabelCapture("Label");
    labelCapture.setVisible(false);

    labelUsed = new JCheckBox("Label used?", false);
    UIHelper.renderComponent(labelUsed, UIHelper.VER_12_BOLD, UIHelper.DARK_GREEN_COLOR, UIHelper.BG_COLOR);

    labelUsed.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            labelCapture.setVisible(labelUsed.isSelected());

        }
    });

    labelPanel.add(labelUsed);
    labelPanel.add(labelCapture);

    generalQuestionCont.add(labelPanel);

    final JPanel extractPanel = new JPanel(new GridLayout(2, 2));
    extractPanel.setBackground(UIHelper.BG_COLOR);

    extractDetails.clear();

    JLabel extractsUsedLab = UIHelper.createLabel("Sample(s) used *");
    extractsUsedLab.setHorizontalAlignment(JLabel.LEFT);
    extractsUsedLab.setVerticalAlignment(JLabel.TOP);

    final JPanel extractNameContainer = new JPanel();
    extractNameContainer.setLayout(new BoxLayout(extractNameContainer, BoxLayout.PAGE_AXIS));
    extractNameContainer.setBackground(UIHelper.BG_COLOR);

    extract = new ExtractDetailsCapture("Sample " + (extractDetails.size() + 1),
            ApplicationManager.getUserInterfaceForISASection(study).getDataEntryEnvironment());

    extractDetails.add(extract);
    extractNameContainer.add(extract);

    JLabel addButton = new JLabel("add sample", addRecordIcon, JLabel.RIGHT);
    UIHelper.renderComponent(addButton, UIHelper.VER_12_BOLD, UIHelper.DARK_GREEN_COLOR, false);

    addButton.setVerticalAlignment(JLabel.TOP);
    addButton.addMouseListener(new MouseAdapter() {

        public void mousePressed(MouseEvent event) {
            extract = new ExtractDetailsCapture("Sample " + (extractDetails.size() + 1),
                    ApplicationManager.getUserInterfaceForISASection(study).getDataEntryEnvironment());
            extractDetails.add(extract);
            extractNameContainer.add(extract);

            extractNameContainer.revalidate();
            generalQuestionCont.revalidate();
        }

    });

    addButton.setToolTipText(
            "<html><b>add new sample</b><p>add another sample (e.g. Liver, Heart, Urine, Blood)</p></html>");

    JLabel removeButton = new JLabel("remove sample", removeIcon, JLabel.RIGHT);
    removeButton.setVerticalAlignment(JLabel.TOP);
    UIHelper.renderComponent(removeButton, UIHelper.VER_12_BOLD, UIHelper.DARK_GREEN_COLOR, false);
    removeButton.addMouseListener(new MouseAdapter() {

        public void mousePressed(MouseEvent event) {
            if (extractDetails.size() > 1) {
                extract = extractDetails.get(extractDetails.size() - 1);
                extractDetails.remove(extract);
                extractNameContainer.remove(extract);
                generalQuestionCont.revalidate();
            }
        }

    });
    removeButton.setToolTipText(
            "<html><b>remove previously added sample</b><p>remove the sample field last added</p></html>");

    extractPanel.add(extractsUsedLab);
    extractPanel.add(extractNameContainer);

    JPanel buttonContainer = new JPanel(new GridLayout(1, 2));
    buttonContainer.setBackground(UIHelper.BG_COLOR);

    buttonContainer.add(addButton);
    buttonContainer.add(removeButton);

    extractPanel.add(new JLabel());
    extractPanel.add(buttonContainer);

    generalQuestionCont.add(extractPanel);

    generalQuestionCont.add(Box.createVerticalStrut(5));
    generalQuestionCont.add(Box.createHorizontalGlue());

    generalQuestionCont.setBorder(new TitledBorder(new RoundedBorder(UIHelper.DARK_GREEN_COLOR, 9),
            assay.getAssayReference(), TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION,
            UIHelper.VER_12_BOLD, UIHelper.DARK_GREEN_COLOR));

    return generalQuestionCont;
}

From source file:org.isatools.isacreator.wizard.MicroarrayCreationAlgorithm.java

private JPanel instantiatePanel() {
    final JPanel microArrayQuestionCont = new JPanel();
    microArrayQuestionCont.setLayout(new BoxLayout(microArrayQuestionCont, BoxLayout.PAGE_AXIS));
    microArrayQuestionCont.setOpaque(false);

    StringBuilder text = new StringBuilder("<html><b>" + assay.getMeasurementEndpoint() + "</b> using <b>"
            + assay.getTechnologyType() + "</b>");

    if (!StringUtils.isEmpty(assay.getAssayPlatform())) {
        text.append(" on <b>").append(assay.getAssayPlatform()).append("</b>");
    }//  w w  w  .  j a  v  a 2  s  . co m

    JLabel info = new JLabel(text.append("</html>").toString(), JLabel.LEFT);

    UIHelper.renderComponent(info, UIHelper.VER_12_PLAIN, UIHelper.GREY_COLOR, false);
    info.setPreferredSize(new Dimension(300, 40));

    JPanel infoPanel = new JPanel(new GridLayout(1, 1));
    infoPanel.setOpaque(false);

    infoPanel.add(info);

    microArrayQuestionCont.add(infoPanel);

    // create reference sample used checkbox

    JPanel labelPanel = new JPanel(new GridLayout(2, 2));
    labelPanel.setBackground(UIHelper.BG_COLOR);

    final DataEntryForm studyUISection = ApplicationManager.getUserInterfaceForISASection(study);
    System.out.println("Study user interface is null? " + (studyUISection == null));
    System.out
            .println("Study user interface dep is null? " + (studyUISection.getDataEntryEnvironment() == null));

    label1Capture = new LabelCapture("Label (e.g. Cy3)");
    label2Capture = new LabelCapture("Label (e.g. Cy5)");
    label2Capture.setVisible(false);

    // create dye swap check box
    dyeSwapUsed = new JCheckBox("dye-swap performed?", false);
    UIHelper.renderComponent(dyeSwapUsed, UIHelper.VER_12_BOLD, UIHelper.DARK_GREEN_COLOR, false);

    dyeSwapUsed.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            label2Capture.setVisible(dyeSwapUsed.isSelected());

        }
    });

    labelPanel.add(UIHelper.createLabel("Label(s) used"));
    labelPanel.add(label1Capture);
    labelPanel.add(dyeSwapUsed);
    labelPanel.add(label2Capture);

    microArrayQuestionCont.add(labelPanel);

    final JPanel extractPanel = new JPanel(new GridLayout(2, 2));
    extractPanel.setOpaque(false);

    extractDetails.clear();

    JLabel extractsUsedLab = UIHelper.createLabel("sample(s) used *");
    extractsUsedLab.setHorizontalAlignment(JLabel.LEFT);
    extractsUsedLab.setVerticalAlignment(JLabel.TOP);

    final JPanel extractNameContainer = new JPanel();
    extractNameContainer.setLayout(new BoxLayout(extractNameContainer, BoxLayout.PAGE_AXIS));
    extractNameContainer.setOpaque(false);

    extract = new ExtractDetailsCapture("Sample " + (extractDetails.size() + 1),
            studyUISection.getDataEntryEnvironment());

    extractDetails.add(extract);
    extractNameContainer.add(extract);

    JLabel addExtractButton = new JLabel("add sample", addRecordIcon, JLabel.RIGHT);
    UIHelper.renderComponent(addExtractButton, UIHelper.VER_12_BOLD, UIHelper.DARK_GREEN_COLOR, false);

    addExtractButton.setVerticalAlignment(JLabel.TOP);
    addExtractButton.addMouseListener(new MouseAdapter() {

        public void mousePressed(MouseEvent event) {
            extract = new ExtractDetailsCapture("Sample " + (extractDetails.size() + 1),
                    studyUISection.getDataEntryEnvironment());
            extractDetails.add(extract);
            extractNameContainer.add(extract);

            extractNameContainer.revalidate();
            microArrayQuestionCont.revalidate();
        }
    });

    addExtractButton.setToolTipText(
            "<html><b>add new sample</b><p>add another sample (e.g. Liver, Heart, Urine, Blood)</p></html>");

    JLabel removeExtractButton = new JLabel("remove sample", removeIcon, JLabel.RIGHT);
    removeExtractButton.setVerticalAlignment(JLabel.TOP);
    UIHelper.renderComponent(removeExtractButton, UIHelper.VER_12_BOLD, UIHelper.DARK_GREEN_COLOR, false);
    removeExtractButton.addMouseListener(new MouseAdapter() {

        public void mousePressed(MouseEvent event) {
            if (extractDetails.size() > 1) {
                extract = extractDetails.get(extractDetails.size() - 1);
                extractDetails.remove(extract);
                extractNameContainer.remove(extract);
                microArrayQuestionCont.revalidate();
            }
        }
    });
    removeExtractButton.setToolTipText(
            "<html><b>remove previously added sample</b><p>remove the array design field last added</p></html>");

    extractPanel.add(extractsUsedLab);
    extractPanel.add(extractNameContainer);

    JPanel extractButtonContainer = new JPanel(new GridLayout(1, 2));
    extractButtonContainer.setOpaque(false);

    extractButtonContainer.add(addExtractButton);
    extractButtonContainer.add(removeExtractButton);

    extractPanel.add(new JLabel());
    extractPanel.add(extractButtonContainer);

    microArrayQuestionCont.add(extractPanel);

    // ask for array designs used...
    // create array designs panel
    final JPanel arrayDesignPanel = new JPanel(new GridLayout(2, 2));
    arrayDesignPanel.setOpaque(false);

    arrayDesignsUsed.clear();

    JLabel arrayDesignLab = UIHelper.createLabel("array design(s) used *");
    arrayDesignLab.setVerticalAlignment(JLabel.TOP);
    // the array designs container must adjust to an unknown number of fields. therefore, a JPanel with a BoxLayout
    // will be used since it is flexible!
    final JPanel arrayDesignsContainer = new JPanel();
    arrayDesignsContainer.setLayout(new BoxLayout(arrayDesignsContainer, BoxLayout.PAGE_AXIS));
    arrayDesignsContainer.setOpaque(false);

    newArrayDesign = new AutoFilterCombo(arrayDesigns, true);

    UIHelper.renderComponent(newArrayDesign, UIHelper.VER_11_PLAIN, UIHelper.DARK_GREEN_COLOR, false);
    newArrayDesign.setPreferredSize(new Dimension(70, 30));

    arrayDesignsContainer.add(newArrayDesign);
    arrayDesignsUsed.add(newArrayDesign);

    JLabel addButton = new JLabel("add design", addRecordIcon, JLabel.RIGHT);

    UIHelper.renderComponent(addButton, UIHelper.VER_10_PLAIN, UIHelper.DARK_GREEN_COLOR, false);
    addButton.setVerticalAlignment(JLabel.TOP);
    addButton.addMouseListener(new MouseAdapter() {

        public void mousePressed(MouseEvent event) {
            newArrayDesign = new AutoFilterCombo(arrayDesigns, true);
            UIHelper.renderComponent(newArrayDesign, UIHelper.VER_11_PLAIN, UIHelper.DARK_GREEN_COLOR, false);
            newArrayDesign.setPreferredSize(new Dimension(70, 30));
            arrayDesignsUsed.add(newArrayDesign);
            arrayDesignsContainer.add(newArrayDesign);
            arrayDesignsContainer.revalidate();
            microArrayQuestionCont.revalidate();
        }

    });
    addButton.setToolTipText("<html><b>add new array design</b><p>add another array design</p></html>");

    JLabel removeButton = new JLabel("remove design", removeIcon, JLabel.RIGHT);
    removeButton.setVerticalAlignment(JLabel.TOP);
    UIHelper.renderComponent(removeButton, UIHelper.VER_12_BOLD, UIHelper.DARK_GREEN_COLOR, false);
    removeButton.addMouseListener(new MouseAdapter() {

        public void mousePressed(MouseEvent event) {
            if (arrayDesignsUsed.size() > 1) {
                newArrayDesign = arrayDesignsUsed.get(arrayDesignsUsed.size() - 1);
                arrayDesignsUsed.remove(newArrayDesign);
                arrayDesignsContainer.remove(newArrayDesign);
                arrayDesignPanel.revalidate();
                microArrayQuestionCont.validate();
            }
        }

    });
    removeButton.setToolTipText(
            "<html><b>remove previously added array design</b><p>remove the array design field last added</p></html>");

    arrayDesignPanel.add(arrayDesignLab);
    arrayDesignPanel.add(arrayDesignsContainer);

    JPanel buttonContainer = new JPanel(new GridLayout(1, 2));
    buttonContainer.setOpaque(false);

    buttonContainer.add(addButton);
    buttonContainer.add(removeButton);

    arrayDesignPanel.add(new JLabel());
    arrayDesignPanel.add(buttonContainer);

    microArrayQuestionCont.add(arrayDesignPanel);

    microArrayQuestionCont.add(Box.createVerticalStrut(5));
    microArrayQuestionCont.add(Box.createHorizontalGlue());

    microArrayQuestionCont.setBorder(new TitledBorder(new RoundedBorder(UIHelper.DARK_GREEN_COLOR, 9),
            assay.getAssayReference(), TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION,
            UIHelper.VER_12_BOLD, UIHelper.DARK_GREEN_COLOR));

    return microArrayQuestionCont;
}

From source file:org.isatools.isacreatorconfigurator.configui.DataEntryPanel.java

private JPanel createMenu() {
    JPanel topPanel = new JPanel(new GridLayout(1, 1));
    topPanel.setBackground(UIHelper.BG_COLOR);
    topPanel.setBorder(null);/*from   w  w w  . j  av  a  2 s.  c  o  m*/

    JMenuBar menu_container = new JMenuBar();
    menu_container.setBorder(null);

    JMenu file = new JMenu("File");

    JMenuItem save = new JMenuItem("Save");
    save.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                updateFieldOrder();
                saveCurrentField(true, true);
                if (sourceFile == null) {
                    createOutput();
                } else {
                    save();
                }
            } catch (DataNotCompleteException dce) {
                showMessagePane(dce.getMessage(), JOptionPane.ERROR_MESSAGE);
            } catch (Exception e1) {
                showMessagePane(e1.getMessage(), JOptionPane.ERROR_MESSAGE);
            }
        }
    });

    JMenuItem createFile = new JMenuItem("Save As");
    createFile.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                saveCurrentField(true, true);
                createOutput();
            } catch (DataNotCompleteException dce) {
                showMessagePane(dce.getMessage(), JOptionPane.ERROR_MESSAGE);
            } catch (IOException e1) {
                showMessagePane("IO error occurred when saving file!", JOptionPane.ERROR_MESSAGE);
            } catch (Exception e1) {
                showMessagePane(e1.getMessage(), JOptionPane.ERROR_MESSAGE);
            }
        }
    });

    JMenuItem closeSession = new JMenuItem("Close session without saving");
    closeSession.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            tableFields.clear();
            applicationContainer.setCurrentPage(applicationContainer.getMp());
        }
    });

    file.add(save);
    file.add(createFile);
    file.add(closeSession);

    JMenu mappingMenu = new JMenu("Mappings");

    JMenuItem viewMappings = new JMenuItem("View Mappings", viewMappingsIcon);
    viewMappings.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    getApplicationContainer()
                            .showJDialogAsSheet(new TableMappingViewer(getThis(), getTableTypeMapping()));
                }
            });
        }
    });

    mappingMenu.add(viewMappings);

    JMenu validation = new JMenu("Validation");

    JMenuItem viewErrors = new JMenuItem("Show Validation Errors", viewMappingsIcon);
    viewErrors.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    Validator validator = new Validator();
                    validateAll(validator);

                    ValidationReport report = validator.getReport();

                    ConfigurationValidationUI validationUI = new ConfigurationValidationUI(tableFields.keySet(),
                            report);
                    validationUI.createGUI();
                    validationUI.setLocationRelativeTo(getApplicationContainer());
                    validationUI.setAlwaysOnTop(true);
                    validationUI.setVisible(true);
                }
            });

        }
    });

    validation.add(viewErrors);

    JMenu helpMenu = new JMenu("Help");

    JMenuItem about = new JMenuItem("About", aboutIcon);
    about.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    applicationContainer.setGlassPanelContents(aboutPanel);
                }
            });

        }
    });

    helpMenu.add(about);

    menu_container.add(file);
    menu_container.add(mappingMenu);
    menu_container.add(validation);
    menu_container.add(helpMenu);

    topPanel.add(menu_container);
    return topPanel;
}

From source file:org.isatools.isacreatorconfigurator.configui.DataEntryPanel.java

private void createMainSector() {

    JPanel topContainer = new JPanel();
    topContainer.setLayout(new BoxLayout(topContainer, BoxLayout.PAGE_AXIS));
    topContainer.setBackground(UIHelper.BG_COLOR);

    // add logo to the top
    topContainer.add(createMenu());//  ww w .  java  2  s  .  com

    JPanel headerImagePanel = new JPanel(new GridLayout(1, 2));
    headerImagePanel.setOpaque(false);

    JLabel logo = new JLabel("");
    logo.setOpaque(false);

    headerImagePanel.add(logo);

    tableInformationDisplay = UIHelper.createLabel("", UIHelper.VER_12_PLAIN, UIHelper.DARK_GREEN_COLOR,
            SwingConstants.RIGHT);
    tableInformationDisplay.setVerticalAlignment(SwingConstants.TOP);
    tableInformationDisplay.setHorizontalAlignment(SwingConstants.RIGHT);

    headerImagePanel.add(UIHelper.wrapComponentInPanel(tableInformationDisplay));

    topContainer.add(headerImagePanel);
    topContainer.add(Box.createVerticalStrut(10));

    add(topContainer, BorderLayout.NORTH);

    // create central console with majority of content!
    createNavigationPanel();

    JPanel bottomContainer = new JPanel();
    bottomContainer.setLayout(new BoxLayout(bottomContainer, BoxLayout.PAGE_AXIS));
    bottomContainer.setBackground(UIHelper.BG_COLOR);

    add(bottomContainer, BorderLayout.SOUTH);

}

From source file:org.isatools.isacreatorconfigurator.configui.DataEntryPanel.java

private JPanel createTableListPanel() {

    JPanel container = new JPanel();
    container.setBackground(UIHelper.BG_COLOR);
    container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));

    JLabel lab = new JLabel(tableListTitle);

    container.add(UIHelper.wrapComponentInPanel(lab));
    container.add(Box.createVerticalStrut(5));

    tableModel = new DefaultListModel();
    tableList = new JList(tableModel);
    tableList.setCellRenderer(new TableListRenderer());
    tableList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    tableList.setBackground(UIHelper.BG_COLOR);
    tableList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent event) {
            try {
                saveCurrentField(false, false);
            } catch (DataNotCompleteException dce) {
                showMessagePane(dce.getMessage(), JOptionPane.ERROR_MESSAGE);
            }//from w w w.j  a  v  a2s .c o  m

            MappingObject currentlyEditedTable = getCurrentlySelectedTable();
            ApplicationManager.setCurrentMappingObject(currentlyEditedTable);

            // update the view error button visibility depending on selected tables error state.
            viewErrorsButton.setVisible(areThereErrorsInThisCurrentObject());

            updateTableInfoDisplay(currentlyEditedTable);
            reformFieldList(currentlyEditedTable);
        }
    });

    JScrollPane listScroller = new JScrollPane(tableList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    listScroller.getViewport().setBackground(UIHelper.BG_COLOR);
    listScroller.setBorder(null);
    listScroller.setPreferredSize(new Dimension(((int) (WIDTH * 0.25)), ((int) (HEIGHT * 0.75))));

    IAppWidgetFactory.makeIAppScrollPane(listScroller);

    container.add(listScroller);
    container.add(Box.createVerticalStrut(5));

    tableCountInfo = UIHelper.createLabel("", UIHelper.VER_11_PLAIN, UIHelper.DARK_GREEN_COLOR);
    container.add(UIHelper.wrapComponentInPanel(tableCountInfo));
    container.add(Box.createVerticalStrut(5));

    // create button panel to add and remove tables
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
    buttonPanel.setBackground(UIHelper.BG_COLOR);

    final JLabel addTableButton = new JLabel(addTable, JLabel.LEFT);
    UIHelper.renderComponent(addTableButton, UIHelper.VER_12_BOLD, UIHelper.DARK_GREEN_COLOR, false);
    addTableButton.setOpaque(false);

    addTableButton.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseEntered(MouseEvent mouseEvent) {
            addTableButton.setIcon(addTableOver);
        }

        @Override
        public void mouseExited(MouseEvent mouseEvent) {
            addTableButton.setIcon(addTable);
        }

        public void mousePressed(MouseEvent event) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    addTableButton.setIcon(addTable);
                    applicationContainer.showJDialogAsSheet(addTableUI);
                }
            });

        }

    });

    addTableButton.setToolTipText("<html><b>Add table</b><p>Add a new table definition.</p></html>");

    final JLabel removeTableButton = new JLabel(removeTable, JLabel.LEFT);
    UIHelper.renderComponent(removeTableButton, UIHelper.VER_12_BOLD, UIHelper.DARK_GREEN_COLOR, false);
    removeTableButton.setOpaque(false);

    removeTableButton.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseEntered(MouseEvent mouseEvent) {
            removeTableButton.setIcon(removeTableOver);
        }

        @Override
        public void mouseExited(MouseEvent mouseEvent) {
            removeTableButton.setIcon(removeTable);
        }

        public void mousePressed(MouseEvent event) {
            removeTableButton.setIcon(removeTable);
            if (tableList.getSelectedValue() != null) {
                String selectedTable = tableList.getSelectedValue().toString();
                MappingObject toRemove = null;
                for (MappingObject mo : tableFields.keySet()) {
                    if (mo.getAssayName().equals(selectedTable)) {
                        toRemove = mo;
                        break;
                    }
                }

                if (toRemove != null) {
                    tableFields.remove(toRemove);
                    reformTableList();
                }
            }
        }

    });

    removeTableButton.setToolTipText("<html><b>Remove table</b><p>Remove table from definitions?</p></html>");

    viewErrorsButton = new JLabel(viewErrorsIcon);
    viewErrorsButton.setVisible(false);
    viewErrorsButton.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent mouseEvent) {
            viewErrorsButton.setIcon(viewErrorsIcon);
            // show error pane for current table only.

            Validator validator = new Validator();
            validateFormOrTable(validator, ApplicationManager.getCurrentMappingObject());

            ValidationReport report = validator.getReport();

            ConfigurationValidationUI validationUI = new ConfigurationValidationUI(tableFields.keySet(),
                    report);
            validationUI.createGUI();
            validationUI.setLocationRelativeTo(getApplicationContainer());
            validationUI.setAlwaysOnTop(true);
            validationUI.setVisible(true);
        }

        @Override
        public void mouseEntered(MouseEvent mouseEvent) {
            viewErrorsButton.setIcon(viewErrorsIconOver);
        }

        @Override
        public void mouseExited(MouseEvent mouseEvent) {
            viewErrorsButton.setIcon(viewErrorsIcon);
        }
    });

    buttonPanel.add(addTableButton);
    buttonPanel.add(removeTableButton);
    buttonPanel.add(viewErrorsButton);
    buttonPanel.add(Box.createHorizontalGlue());

    container.add(buttonPanel);

    container.add(Box.createVerticalGlue());

    return container;
}

From source file:org.isatools.isacreatorconfigurator.configui.DataEntryPanel.java

private JPanel createFieldListPanel() {

    JPanel container = new JPanel();
    container.setBackground(UIHelper.BG_COLOR);
    container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));

    JPanel headerLab = new JPanel(new GridLayout(1, 1));
    headerLab.setOpaque(false);//from  w  w  w  .  j a v  a 2  s  . com

    JLabel lab = new JLabel(fieldListTitle);
    headerLab.add(lab);

    container.add(headerLab);
    container.add(Box.createVerticalStrut(5));

    elementModel = new DefaultListModel();
    elementList = new ReOrderableJList(elementModel);
    elementList.setCellRenderer(new CustomReOrderableListCellRenderer(elementList));
    elementList.setDragEnabled(true);
    elementList.setBackground(UIHelper.BG_COLOR);

    elementList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent event) {
            Display selectedNode = (Display) elementList.getSelectedValue();
            if (selectedNode != null) {
                try {
                    saveCurrentField(false, false);
                } catch (DataNotCompleteException dce) {
                    showMessagePane(dce.getMessage(), JOptionPane.ERROR_MESSAGE);
                }
                if (selectedNode instanceof FieldElement) {
                    fieldInterface.setCurrentField((FieldElement) selectedNode);
                    if (currentPage != fieldInterface) {
                        setCurrentPage(fieldInterface);
                    }
                    removeElementButton.setEnabled(!standardISAFields.isFieldRequired(selectedNode.toString()));
                } else {
                    setCurrentPage(structureElement);
                }
            }
        }
    });

    elementList.addPropertyChangeListener("orderChanged", new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
            updateFieldOrder();

            if (tableList.getSelectedValue() instanceof MappingObject) {
                validateFormOrTable(ApplicationManager.getCurrentMappingObject());
            }
        }
    });

    JScrollPane listScroller = new JScrollPane(elementList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    listScroller.getViewport().setBackground(UIHelper.BG_COLOR);
    listScroller.setBorder(new EmptyBorder(2, 2, 2, 10));
    listScroller.setPreferredSize(new Dimension(((int) (WIDTH * 0.25)), ((int) (HEIGHT * 0.75))));
    IAppWidgetFactory.makeIAppScrollPane(listScroller);

    container.add(listScroller);
    container.add(Box.createVerticalStrut(5));

    elementCountInfo = UIHelper.createLabel("", UIHelper.VER_11_PLAIN, UIHelper.DARK_GREEN_COLOR);

    container.add(UIHelper.wrapComponentInPanel(elementCountInfo));
    container.add(Box.createVerticalStrut(5));

    // create button panel to add and remove tables
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
    buttonPanel.setBackground(UIHelper.BG_COLOR);

    final JLabel addFieldButton = new JLabel(addElement, JLabel.LEFT);
    addFieldButton.setOpaque(false);

    addFieldButton.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseEntered(MouseEvent mouseEvent) {
            addFieldButton.setIcon(addElementOver);
        }

        @Override
        public void mouseExited(MouseEvent mouseEvent) {
            addFieldButton.setIcon(addElement);
        }

        public void mousePressed(MouseEvent event) {
            addFieldButton.setIcon(addElement);
            showAddFieldUI();
        }

    });

    addFieldButton.setToolTipText(
            "<html><b>Add Field to table</b><p>Add a new field to currently selected table</b></p></html>");

    removeElementButton = new JLabel(removeElement, JLabel.LEFT);
    removeElementButton.setOpaque(false);

    removeElementButton.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseEntered(MouseEvent mouseEvent) {
            removeElementButton.setIcon(removeElementOver);
        }

        @Override
        public void mouseExited(MouseEvent mouseEvent) {
            removeElementButton.setIcon(removeElement);
        }

        public void mousePressed(MouseEvent event) {
            removeElementButton.setIcon(removeElement);
            if (removeElementButton.isEnabled()) {
                removeSelectedElement();
            }
        }

    });

    removeElementButton.setToolTipText(
            "<html><b>Remove Field from table</b><p>Remove this field from this list and the currently selected table.</b></p></html>");

    final JLabel moveDownButton = new JLabel(moveDown);
    moveDownButton.setOpaque(false);
    moveDownButton.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseEntered(MouseEvent mouseEvent) {
            moveDownButton.setIcon(moveDownOver);
        }

        @Override
        public void mouseExited(MouseEvent mouseEvent) {
            moveDownButton.setIcon(moveDown);
        }

        public void mousePressed(MouseEvent event) {
            moveDownButton.setIcon(moveDown);
            if (elementList.getSelectedIndex() != -1) {
                int toMoveDown = elementList.getSelectedIndex();

                if (toMoveDown != (elementModel.getSize() - 1)) {
                    swapElements(elementList, elementModel, toMoveDown, toMoveDown + 1);
                }

                updateFieldOrder();
                validateFormOrTable(ApplicationManager.getCurrentMappingObject());
            }
        }
    });

    moveDownButton.setToolTipText(
            "<html><b>Move Field Down</b><p>Move the selected field down <b>one</b> position in the list.</p></html>");

    final JLabel moveUpButton = new JLabel(moveUp);
    moveUpButton.setOpaque(false);
    moveUpButton.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseEntered(MouseEvent mouseEvent) {
            moveUpButton.setIcon(moveUpOver);
        }

        @Override
        public void mouseExited(MouseEvent mouseEvent) {
            moveUpButton.setIcon(moveUp);
        }

        public void mousePressed(MouseEvent event) {
            moveUpButton.setIcon(moveUp);
            if (elementList.getSelectedIndex() != -1) {
                int toMoveUp = elementList.getSelectedIndex();

                if (toMoveUp != 0) {
                    swapElements(elementList, elementModel, toMoveUp, toMoveUp - 1);
                }

                updateFieldOrder();
                validateFormOrTable(ApplicationManager.getCurrentMappingObject());

            }
        }

    });

    moveUpButton.setToolTipText(
            "<html><b>Move Field Up</b><p>Move the selected field up <b>one</b> position in the list.</p></html>");

    buttonPanel.add(addFieldButton);
    buttonPanel.add(removeElementButton);
    buttonPanel.add(moveDownButton);
    buttonPanel.add(moveUpButton);

    container.add(buttonPanel);

    container.add(Box.createVerticalGlue());

    return container;
}

From source file:org.isatools.isacreatorconfigurator.configui.FieldInterface.java

private void instantiateFields(String initFieldName) {
    // OVERALL CONTAINER
    JPanel container = new JPanel();
    container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
    container.setBackground(UIHelper.BG_COLOR);

    JLabel fieldDefinitionLab = new JLabel(fieldDefinitionHeader, JLabel.CENTER);
    container.add(fieldDefinitionLab);//from w  w  w  .ja  v a 2  s.c om

    container.add(Box.createVerticalStrut(5));

    // FIELD LABEL & INPUT BOX CONTAINER
    JPanel fieldCont = new JPanel(new GridLayout(1, 2));
    fieldCont.setBackground(UIHelper.BG_COLOR);

    fieldName = new RoundedJTextField(15);
    fieldName.setText(initFieldName);
    fieldName.setEditable(false);
    UIHelper.renderComponent(fieldName, UIHelper.VER_11_PLAIN, UIHelper.DARK_GREEN_COLOR, false);

    JLabel fieldNameLab = UIHelper.createLabel("Field Name: ", UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR);
    fieldCont.add(fieldNameLab);
    fieldCont.add(fieldName);
    container.add(fieldCont);

    JPanel descCont = new JPanel(new GridLayout(1, 2));
    descCont.setBackground(UIHelper.BG_COLOR);
    description = new RoundedJTextArea();
    description.setLineWrap(true);
    description.setWrapStyleWord(true);
    UIHelper.renderComponent(description, UIHelper.VER_11_PLAIN, UIHelper.DARK_GREEN_COLOR, false);

    JScrollPane descScroll = new JScrollPane(description, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    descScroll.setBackground(UIHelper.BG_COLOR);
    descScroll.setPreferredSize(new Dimension(150, 65));
    descScroll.getViewport().setBackground(UIHelper.BG_COLOR);

    IAppWidgetFactory.makeIAppScrollPane(descScroll);

    JLabel descLab = UIHelper.createLabel("Description: ", UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR);
    descLab.setVerticalAlignment(JLabel.TOP);
    descCont.add(descLab);
    descCont.add(descScroll);
    container.add(descCont);

    // add datatype information
    JPanel datatypeCont = new JPanel(new GridLayout(1, 2));
    datatypeCont.setBackground(UIHelper.BG_COLOR);

    DataTypes[] allowedDataTypes = initFieldName.equals(UNIT_STR) ? new DataTypes[] { DataTypes.ONTOLOGY_TERM }
            : DataTypes.values();

    datatype = new JComboBox(allowedDataTypes);
    datatype.addActionListener(this);
    UIHelper.renderComponent(datatype, UIHelper.VER_11_PLAIN, UIHelper.DARK_GREEN_COLOR, UIHelper.BG_COLOR);

    JLabel dataTypeLab = UIHelper.createLabel("Datatype:", UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR);
    datatypeCont.add(dataTypeLab);
    datatypeCont.add(datatype);
    container.add(datatypeCont);

    defaultValContStd = new JPanel(new GridLayout(1, 2));
    defaultValContStd.setBackground(UIHelper.BG_COLOR);

    defaultValCont = Box.createHorizontalBox();
    defaultValCont.setPreferredSize(new Dimension(150, 25));

    defaultValStd = new RoundedFormattedTextField(null, UIHelper.TRANSPARENT_LIGHT_GREEN_COLOR,
            UIHelper.DARK_GREEN_COLOR);
    defaultValCont.setPreferredSize(new Dimension(120, 25));
    defaultValStd.setFormatterFactory(new DefaultFormatterFactory(
            new RegExFormatter(".*", defaultValStd, false, UIHelper.DARK_GREEN_COLOR, UIHelper.RED_COLOR,
                    UIHelper.TRANSPARENT_LIGHT_GREEN_COLOR, UIHelper.TRANSPARENT_LIGHT_GREEN_COLOR)));
    defaultValStd.setForeground(UIHelper.DARK_GREEN_COLOR);
    defaultValStd.setFont(UIHelper.VER_11_PLAIN);

    defaultValCont.add(defaultValStd);

    defaultValLabStd = UIHelper.createLabel(DEFAULT_VAL_STR, UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR);

    defaultValContStd.add(defaultValLabStd);
    defaultValContStd.add(defaultValCont);
    container.add(defaultValContStd);

    defaultValContBool = new JPanel(new GridLayout(1, 2));
    defaultValContBool.setBackground(UIHelper.BG_COLOR);
    defaultValContBool.setVisible(false);

    listDataSourceCont = new JPanel(new GridLayout(2, 1));
    listDataSourceCont.setBackground(UIHelper.BG_COLOR);
    listDataSourceCont.setVisible(false);

    JLabel listValLab = UIHelper.createLabel("Please enter comma separated list of values:",
            UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR);
    listDataSourceCont.add(listValLab);

    listValues = new RoundedJTextArea("SampleVal1, SampleVal2, SampleVal3", 3, 5);
    listValues.setLineWrap(true);
    listValues.setWrapStyleWord(true);
    UIHelper.renderComponent(listValues, UIHelper.VER_11_PLAIN, UIHelper.DARK_GREEN_COLOR, false);

    JScrollPane listScroll = new JScrollPane(listValues, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    listScroll.setBackground(UIHelper.BG_COLOR);
    listScroll.getViewport().setBackground(UIHelper.BG_COLOR);

    listDataSourceCont.add(listScroll);
    container.add(listDataSourceCont);

    IAppWidgetFactory.makeIAppScrollPane(listScroll);

    sourceEntryPanel = new JPanel(new BorderLayout());
    sourceEntryPanel.setSize(new Dimension(125, 190));
    sourceEntryPanel.setOpaque(false);
    sourceEntryPanel.setVisible(false);

    preferredOntologySource = new JPanel();
    preferredOntologySource.setLayout(new BoxLayout(preferredOntologySource, BoxLayout.PAGE_AXIS));
    preferredOntologySource.setVisible(false);
    recommendOntologySource = new JCheckBox("Use recommended ontology source?", false);

    UIHelper.renderComponent(recommendOntologySource, UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR, false);
    recommendOntologySource.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (recommendOntologySource.isSelected()) {
                sourceEntryPanel.setVisible(true);
            } else {
                sourceEntryPanel.setVisible(false);
            }
        }
    });

    JPanel useOntologySourceCont = new JPanel(new GridLayout(1, 1));
    useOntologySourceCont.add(recommendOntologySource);

    preferredOntologySource.add(useOntologySourceCont);

    JPanel infoCont = new JPanel(new GridLayout(1, 1));
    JLabel infoLab = UIHelper.createLabel(
            "<html>click on the <strong>configure ontologies</strong> button to open the ontology configurator to edit the list of ontologies and search areas within an ontology</html>",
            UIHelper.VER_11_PLAIN, UIHelper.DARK_GREEN_COLOR);
    infoLab.setPreferredSize(new Dimension(100, 40));
    infoCont.add(infoLab);

    sourceEntryPanel.add(infoCont, BorderLayout.NORTH);

    JLabel preferredOntologiesLab = new JLabel(preferredOntologiesSidePanelIcon);
    preferredOntologiesLab.setVerticalAlignment(SwingConstants.TOP);

    sourceEntryPanel.add(preferredOntologiesLab, BorderLayout.WEST);

    ontologiesToUseModel = new DefaultTableModel(new String[0][2], ontologyColumnHeaders) {
        @Override
        public boolean isCellEditable(int i, int i1) {
            return false;
        }
    };
    ontologiesToUse = new JTable(ontologiesToUseModel);
    ontologiesToUse.getTableHeader().setBackground(UIHelper.BG_COLOR);

    try {
        ontologiesToUse.setDefaultRenderer(Class.forName("java.lang.Object"),
                new CustomSpreadsheetCellRenderer());
    } catch (ClassNotFoundException e) {
        // empty
    }

    renderTableHeader();

    JScrollPane ontologiesToUseScroller = new JScrollPane(ontologiesToUse,
            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    ontologiesToUseScroller.setBorder(new EmptyBorder(0, 0, 0, 0));
    ontologiesToUseScroller.setPreferredSize(new Dimension(100, 80));
    ontologiesToUseScroller.setBackground(UIHelper.BG_COLOR);
    ontologiesToUseScroller.getViewport().setBackground(UIHelper.BG_COLOR);

    IAppWidgetFactory.makeIAppScrollPane(ontologiesToUseScroller);

    sourceEntryPanel.add(ontologiesToUseScroller);

    JPanel buttonCont = new JPanel(new BorderLayout());
    final JLabel openConfigButton = new JLabel(ontologyConfigIcon);
    openConfigButton.setVerticalAlignment(SwingConstants.TOP);
    openConfigButton.setHorizontalAlignment(SwingConstants.RIGHT);

    MouseAdapter showOntologyConfigurator = new MouseAdapter() {

        public void mouseEntered(MouseEvent mouseEvent) {
            openConfigButton.setIcon(ontologyConfigIconOver);
        }

        public void mouseExited(MouseEvent mouseEvent) {
            openConfigButton.setIcon(ontologyConfigIcon);
        }

        public void mousePressed(MouseEvent mouseEvent) {

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    if (openConfigButton.isEnabled()) {
                        openConfigButton.setIcon(ontologyConfigIcon);
                        ontologyConfig = new OntologyConfigUI(ontologiesToQuery, selectedOntologies);
                        ontologyConfig.addPropertyChangeListener("ontologySelected",
                                new PropertyChangeListener() {
                                    public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
                                        selectedOntologies = (ListOrderedMap<String, RecommendedOntology>) propertyChangeEvent
                                                .getNewValue();
                                        updateTable();
                                    }
                                });
                        showPopupInCenter(ontologyConfig);
                    }
                }
            });
        }

    };

    openConfigButton.addMouseListener(showOntologyConfigurator);

    buttonCont.add(openConfigButton, BorderLayout.EAST);

    sourceEntryPanel.add(buttonCont, BorderLayout.SOUTH);
    preferredOntologySource.add(sourceEntryPanel);
    container.add(preferredOntologySource);

    String[] contents = new String[] { "true", "false" };
    defaultValBool = new

    JComboBox(contents);

    UIHelper.renderComponent(defaultValBool, UIHelper.VER_12_PLAIN, UIHelper.DARK_GREEN_COLOR,
            UIHelper.BG_COLOR);

    JLabel defaultValLabBool = UIHelper.createLabel(DEFAULT_VAL_STR, UIHelper.VER_12_BOLD,
            UIHelper.DARK_GREEN_COLOR);

    defaultValContBool.add(defaultValLabBool);
    defaultValContBool.add(defaultValBool);
    container.add(defaultValContBool);

    // RegExp data entry
    isInputFormatted = new JCheckBox("Is the input formatted?", false);
    isInputFormatted.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    isInputFormatted.setHorizontalAlignment(SwingConstants.LEFT);

    UIHelper.renderComponent(isInputFormatted, UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR, false);
    isInputFormatted.addActionListener(this);
    container.add(UIHelper.wrapComponentInPanel(isInputFormatted));

    inputFormatCont = new JPanel();

    inputFormatCont.setLayout(new BoxLayout(inputFormatCont, BoxLayout.LINE_AXIS));
    inputFormatCont.setVisible(false);
    inputFormatCont.setBackground(UIHelper.BG_COLOR);
    inputFormat = new RoundedJTextField(10);
    inputFormat.setText(".*");
    inputFormat.setSize(new Dimension(150, 19));

    inputFormat.setPreferredSize(new Dimension(160, 25));
    inputFormat.setToolTipText("Field expects a regular expression describing the input format.");
    UIHelper.renderComponent(inputFormat, UIHelper.VER_11_PLAIN, UIHelper.DARK_GREEN_COLOR, false);

    JLabel inputFormatLab = UIHelper.createLabel("Input format:", UIHelper.VER_11_BOLD,
            UIHelper.DARK_GREEN_COLOR);
    inputFormatLab.setVerticalAlignment(SwingConstants.TOP);

    inputFormatCont.add(inputFormatLab);
    inputFormatCont.add(inputFormat);
    JLabel checkRegExp = new JLabel(checkRegExIcon, JLabel.RIGHT);
    checkRegExp.setOpaque(false);
    checkRegExp.addMouseListener(new MouseAdapter() {

        public void mousePressed(MouseEvent event) {
            String regexToCheck = inputFormat.getText();

            final CheckRegExGUI regexChecker = new CheckRegExGUI(regexToCheck);
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    regexChecker.createGUI();
                }
            });
            regexChecker.addPropertyChangeListener("close", new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent evt) {
                    main.getApplicationContainer().hideSheet();
                }
            });
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    main.getApplicationContainer().showJDialogAsSheet(regexChecker);
                }
            });
        }

    }

    );
    inputFormatCont.add(checkRegExp);
    container.add(inputFormatCont);

    usesTemplateForWizard = new JCheckBox("Requires template for wizard?", false);
    usesTemplateForWizard.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    usesTemplateForWizard.setHorizontalAlignment(SwingConstants.LEFT);

    UIHelper.renderComponent(usesTemplateForWizard, UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR, false);
    usesTemplateForWizard.addActionListener(this);
    container.add(UIHelper.wrapComponentInPanel(usesTemplateForWizard));

    wizardTemplatePanel = new JPanel(new GridLayout(1, 2));
    wizardTemplatePanel.setVisible(false);
    wizardTemplatePanel.setBackground(UIHelper.BG_COLOR);

    wizardTemplate = new RoundedJTextArea();
    wizardTemplate.setToolTipText("A template for the wizard to auto-create the data...");
    wizardTemplate.setLineWrap(true);
    wizardTemplate.setWrapStyleWord(true);
    UIHelper.renderComponent(wizardTemplate, UIHelper.VER_11_PLAIN, UIHelper.DARK_GREEN_COLOR, false);

    JScrollPane wizScroll = new JScrollPane(wizardTemplate, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    wizScroll.getViewport().setBackground(UIHelper.BG_COLOR);
    wizScroll.setPreferredSize(new Dimension(70, 60));

    IAppWidgetFactory.makeIAppScrollPane(wizScroll);

    JLabel wizardTemplateLab = UIHelper.createLabel("Template definition:", UIHelper.VER_11_BOLD,
            UIHelper.DARK_GREEN_COLOR);
    wizardTemplateLab.setVerticalAlignment(JLabel.TOP);

    wizardTemplatePanel.add(wizardTemplateLab);
    wizardTemplatePanel.add(wizScroll);

    container.add(wizardTemplatePanel);

    JPanel checkCont = new JPanel(new GridLayout(3, 2));
    checkCont.setBackground(UIHelper.BG_COLOR);
    checkCont.setBorder(new TitledBorder(new RoundedBorder(UIHelper.DARK_GREEN_COLOR, 4),
            "Behavioural Attributes", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION,
            UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR));

    required = new JCheckBox("Required ", true);

    UIHelper.renderComponent(required, UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR, false);
    checkCont.add(required);

    acceptsMultipleValues = new JCheckBox("Allow multiple instances", false);

    UIHelper.renderComponent(acceptsMultipleValues, UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR, false);
    checkCont.add(acceptsMultipleValues);
    acceptsFileLocations = new JCheckBox("Accepts file locations", false);

    acceptsFileLocations.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            acceptsMultipleValues.setSelected(false);
            acceptsMultipleValues.setEnabled(!acceptsFileLocations.isSelected());
        }
    });

    UIHelper.renderComponent(acceptsFileLocations, UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR, false);
    checkCont.add(acceptsFileLocations);

    hidden = new JCheckBox("hidden?", false);

    UIHelper.renderComponent(hidden, UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR, false);
    checkCont.add(hidden);

    forceOntologySelection = new JCheckBox("Force ontology selection", false);
    UIHelper.renderComponent(forceOntologySelection, UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR, false);

    checkCont.add(forceOntologySelection);

    container.add(checkCont);

    JScrollPane contScroll = new JScrollPane(container, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    contScroll.setBorder(null);
    contScroll.setAutoscrolls(true);

    IAppWidgetFactory.makeIAppScrollPane(contScroll);

    add(contScroll, BorderLayout.NORTH);
}

From source file:org.kchine.r.server.manager.ServerManager.java

synchronized public static RServices createRInternal(String RBinPath, boolean forceEmbedded, boolean keepAlive,
        String codeServerHostIp, int codeServerPort, Properties namingInfo, int memoryMinMegabytes,
        int memoryMaxMegabytes, String name, final boolean showProgress, URL[] codeUrls, String logFile,
        String applicationType, final Runnable rShutdownHook, String forcedIP, String mainClassName,
        boolean useCreationCallback) throws Exception {

    final JTextArea[] createRProgressArea = new JTextArea[1];
    final JProgressBar[] createRProgressBar = new JProgressBar[1];
    final JFrame[] createRProgressFrame = new JFrame[1];
    ProgessLoggerInterface progressLogger = new ProgessLoggerInterface() {
        public void logProgress(String message) {

            System.out.println(">>" + message);
            try {
                if (showProgress) {
                    createRProgressArea[0].setText(message);
                }/*from   ww  w.j av  a2  s  .  c o m*/
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    if (showProgress) {
        createRProgressArea[0] = new JTextArea();
        createRProgressBar[0] = new JProgressBar(0, 100);
        createRProgressFrame[0] = new JFrame("Creating R Server on Local Host");

        Runnable runnable = new Runnable() {
            public void run() {

                createRProgressFrame[0].setUndecorated(true);

                JPanel p = new JPanel(new BorderLayout());
                createRProgressArea[0].setForeground(Color.white);
                createRProgressArea[0].setBackground(new Color(0x00, 0x80, 0x80));
                createRProgressArea[0]
                        .setBorder(BorderFactory.createLineBorder(new Color(0x00, 0x80, 0x80), 3));
                createRProgressArea[0].setEditable(false);
                p.setBorder(BorderFactory.createLineBorder(Color.black, 3));

                createRProgressBar[0].setForeground(Color.white);
                createRProgressBar[0].setBackground(new Color(0x00, 0x80, 0x80));
                createRProgressBar[0].setIndeterminate(true);

                p.setBackground(new Color(0x00, 0x80, 0x80));
                p.add(createRProgressBar[0], BorderLayout.SOUTH);
                p.add(createRProgressArea[0], BorderLayout.CENTER);
                createRProgressFrame[0].add(p);

                createRProgressFrame[0].pack();
                createRProgressFrame[0].setSize(600, 64);
                createRProgressFrame[0].setVisible(true);
                createRProgressFrame[0].setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

                PoolUtils.locateInScreenCenter(createRProgressFrame[0]);
            }
        };
        if (SwingUtilities.isEventDispatchThread())
            runnable.run();
        else {
            SwingUtilities.invokeLater(runnable);
        }
    }

    boolean useClassPath = (codeUrls == null || codeUrls.length == 0)
            && (applicationType == null || applicationType.equals("") || applicationType.equals("standard"));
    System.out.println("application type : " + applicationType);
    System.out.println("!! use class path : " + useClassPath);
    System.out.println("java.class.path : " + System.getProperty("java.class.path"));

    try {

        progressLogger.logProgress("Inspecting R installation..");
        new File(INSTALL_DIR).mkdir();

        String rpath = null;
        String rversion = null;
        String userrjavapath = null;
        String[] rinfo = null;

        if (RBinPath != null && !RBinPath.equals("")) {
            rinfo = getRInfo(RBinPath);
            if (rinfo == null) {
                throw new ServantCreationFailed();
            }
            rpath = rinfo[0];
            rversion = rinfo[1];
            userrjavapath = rinfo[2];
        } else if (new File(INSTALL_DIR + "R/" + EMBEDDED_R).exists()) {

            rinfo = getRInfo(INSTALL_DIR + "R/" + EMBEDDED_R + "/bin/R.exe");
            if (rinfo == null) {
                throw new ServantCreationFailed();
            }
            rpath = rinfo[0];
            rversion = rinfo[1];
            userrjavapath = rinfo[2];

            System.setProperty("use.default.libs", "true");

        } else if (!forceEmbedded) {

            String rhome = System.getenv("R_HOME");
            if (rhome == null) {
                rinfo = getRInfo(null);
            } else {
                if (!rhome.endsWith("/")) {
                    rhome = rhome + "/";
                }
                System.out.println("R_HOME is set to :" + rhome);
                rinfo = getRInfo(rhome + "bin/R");
            }

            System.out.println("+rinfo:" + rinfo + " " + Arrays.toString(rinfo));
            rpath = rinfo != null ? rinfo[0] : null;
            rversion = (rinfo != null ? rinfo[1] : "");
            userrjavapath = (rinfo != null ? rinfo[2] : "");
        }

        System.out.println("rpath:" + rpath);
        System.out.println("rversion:" + rversion);
        System.out.println("user rjava path:" + userrjavapath);
        if (rpath == null) {

            String noRCause = System.getenv("R_HOME") == null ? "R is not accessible from the command line"
                    : "Your R_HOME is invalid";
            if (isWindowsOs()) {

                int n;
                if (forceEmbedded) {
                    n = JOptionPane.OK_OPTION;
                } else {
                    n = JOptionPane.showConfirmDialog(null,
                            noRCause + "\nWould you like to use the Embedded R?", "",
                            JOptionPane.YES_NO_OPTION);
                }
                if (n == JOptionPane.OK_OPTION) {
                    String rZipFileName = null;
                    rZipFileName = "http://biocep-distrib.r-forge.r-project.org/r/" + EMBEDDED_R + ".zip";
                    URL rUrl = new URL(rZipFileName);
                    InputStream is = rUrl.openConnection().getInputStream();
                    unzip(is, INSTALL_DIR + "R/", null, BUFFER_SIZE, true, "Unzipping R..", ENTRIES_NUMBER);

                    rinfo = getRInfo(INSTALL_DIR + "R/" + EMBEDDED_R + "/bin/R.exe");
                    if (rinfo == null) {
                        throw new ServantCreationFailed();
                    }
                    rpath = rinfo[0];
                    rversion = rinfo[1];
                    userrjavapath = rinfo[2];
                    System.setProperty("use.default.libs", "true");

                } else {
                    JOptionPane.showMessageDialog(null,
                            "please add R to your System path or set R_HOME to the root Directory of your local R installation\n");
                    throw new ServantCreationFailed();
                }

            } else {
                if (showProgress) {
                    JOptionPane.showMessageDialog(null, noRCause
                            + "\nplease add R to your System path \nor set R_HOME to the root Directory of your local R installation\n");
                } else {
                    System.out.println(noRCause
                            + "\n please add R to your System path \nor set R_HOME to the root Directory of your local R installation");
                }
                throw new ServantCreationFailed();
            }

        }

        progressLogger.logProgress("R installation inspection done.");

        boolean useDefaultUserLibs = (System.getenv("BIOCEP_USE_DEFAULT_LIBS") != null
                && System.getenv("BIOCEP_USE_DEFAULT_LIBS").equalsIgnoreCase("false"))
                || (System.getProperty("use.default.libs") != null
                        && System.getProperty("use.default.libs").equalsIgnoreCase("true"));

        if (System.getProperty("use.default.libs") == null
                || System.getProperty("use.default.libs").equals("")) {
            System.setProperty("use.default.libs", new Boolean(useDefaultUserLibs).toString().toLowerCase());
        }

        if (!rpath.endsWith("/") && !rpath.endsWith("\\"))
            rpath += "/";

        String rlibs = (INSTALL_DIR + "library/"
                + rversion.substring(0, rversion.lastIndexOf(' ')).replace(' ', '-')).replace('\\', '/');
        new File(rlibs).mkdirs();

        Vector<String> envVector = new Vector<String>();
        {
            Map<String, String> osenv = System.getenv();
            String OS_PATH = osenv.get("PATH");
            if (OS_PATH == null)
                OS_PATH = osenv.get("Path");
            if (OS_PATH == null)
                OS_PATH = "";

            Map<String, String> env = new HashMap<String, String>(osenv);

            env.put("Path",
                    rpath + (isWindowsOs() ? "bin" : "lib") + System.getProperty("path.separator") + OS_PATH);
            if (sci != null && isWindowsOs()) {
                env.put("Path", sci_dll_path + System.getProperty("path.separator") + env.get("Path"));
            }

            env.put("LD_LIBRARY_PATH", rpath + (isWindowsOs() ? "bin" : "lib"));
            if (sci != null) {
                env.put("SCI", sci);
                env.put("SCIHOME", sci);
                env.put("SCI_DISABLE_TK", "1");
                env.put("SCI_JAVA_ENABLE_HEADLESS", "1");

                if (!isWindowsOs()) {
                    env.put("LD_LIBRARY_PATH",
                            sci_dll_path + System.getProperty("path.separator") + env.get("LD_LIBRARY_PATH"));
                }
            }

            env.put("R_HOME", rpath);

            String R_LIBS = null;
            if (useDefaultUserLibs) {
                R_LIBS = (System.getenv("R_LIBS") != null ? System.getenv("R_LIBS") : "");
            } else {
                R_LIBS = rlibs + System.getProperty("path.separator")
                        + (System.getenv("R_LIBS") != null ? System.getenv("R_LIBS") : "");
            }

            System.out.println("R_LIBS:" + R_LIBS);
            env.put("R_LIBS", R_LIBS);

            if (System.getenv("JDK_HOME") != null)
                env.put("JAVA_HOME", System.getenv("JDK_HOME"));

            for (String k : env.keySet()) {
                envVector.add(k + "=" + env.get(k));
            }
            System.out.println("envVector:" + envVector);
        }

        String[] requiredPackages = null;
        if (useDefaultUserLibs) {
            requiredPackages = new String[0];
        } else {
            if (isWindowsOs()) {
                requiredPackages = new String[] { "rJava", "JavaGD", "iplots", "TypeInfo", "Cairo" };
            } else {
                requiredPackages = new String[] { "rJava", "JavaGD", "iplots", "TypeInfo" };
            }
        }

        Vector<String> installLibBatch = new Vector<String>();
        installLibBatch.add("source('http://bioconductor.org/biocLite.R')");

        Vector<String> missingPackages = new Vector<String>();
        for (int i = 0; i < requiredPackages.length; ++i) {
            if (!new File(rlibs + "/" + requiredPackages[i]).exists()) {
                installLibBatch.add("biocLite('" + requiredPackages[i] + "',lib='" + rlibs + "')");
                missingPackages.add(requiredPackages[i]);
            }
        }

        progressLogger.logProgress("Installing missing packages " + missingPackages + "..\n"
                + "This doesn't alter your R installation and may take several minutes. It will be done only once");

        if (installLibBatch.size() > 1) {

            File installPackagesFile = new File(INSTALL_DIR + "installRequiredPackages.R");
            File installPackagesOutputFile = new File(INSTALL_DIR + "installRequiredPackages.Rout");

            FileWriter fw = new FileWriter(installPackagesFile);
            PrintWriter pw = new PrintWriter(fw);
            for (int i = 0; i < installLibBatch.size(); ++i) {
                pw.println(installLibBatch.elementAt(i));
            }
            fw.close();

            Vector<String> installCommand = new Vector<String>();
            installCommand.add(rpath + "bin/R");
            installCommand.add("CMD");
            installCommand.add("BATCH");
            installCommand.add("--no-save");
            installCommand.add(installPackagesFile.getAbsolutePath());
            installCommand.add(installPackagesOutputFile.getAbsolutePath());

            System.out.println(installCommand);

            final Process installProc = Runtime.getRuntime().exec(installCommand.toArray(new String[0]),
                    envVector.toArray(new String[0]));
            final Vector<String> installPrint = new Vector<String>();
            final Vector<String> installErrorPrint = new Vector<String>();

            new Thread(new Runnable() {
                public void run() {
                    try {
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(installProc.getErrorStream()));
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            System.out.println(line);
                            installErrorPrint.add(line);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

            new Thread(new Runnable() {
                public void run() {
                    try {
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(installProc.getInputStream()));
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            System.out.println(line);
                            installPrint.add(line);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            installProc.waitFor();

            if (installPackagesOutputFile.exists()
                    && installPackagesOutputFile.lastModified() > installPackagesFile.lastModified()) {
                BufferedReader br = new BufferedReader(new FileReader(installPackagesOutputFile));
                String line = null;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
            }

            Vector<String> missingLibs = new Vector<String>();

            for (int i = 0; i < requiredPackages.length; ++i) {
                if (!new File(rlibs + "/" + requiredPackages[i]).exists()) {
                    missingLibs.add(requiredPackages[i]);
                }
                /*
                 * if (getLibraryPath(requiredPackages[i], rpath, rlibs) ==
                 * null) { missingLibs.add(requiredPackages[i]); }
                 */
            }

            if (missingLibs.size() > 0) {
                System.out.println(
                        "The following packages probably couldn't be automatically installed\n" + missingLibs);
                throw new ServantCreationFailed();
            }

        }

        progressLogger.logProgress("All Required Packages Are Installed.");

        progressLogger.logProgress("Generating Bootstrap Classes..");

        String bootstrap = (INSTALL_DIR + "classes/org/kchine/r/server/manager/bootstrap").replace('\\', '/');
        System.out.println(bootstrap);
        if (!new File(bootstrap).exists())
            new File(bootstrap).mkdirs();
        InputStream is = ServerManager.class
                .getResourceAsStream("/org/kchine/r/server/manager/bootstrap/Boot.class");
        byte[] buffer = new byte[is.available()];
        try {
            for (int i = 0; i < buffer.length; ++i) {
                int b = is.read();
                buffer[i] = (byte) b;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        RandomAccessFile raf = new RandomAccessFile(bootstrap + "/Boot.class", "rw");
        raf.setLength(0);
        raf.write(buffer);
        raf.close();
        progressLogger.logProgress("Bootstrap Classes Generated.");

        // ---------------------------------------

        if (!isWindowsOs() && !new File(INSTALL_DIR + "VRWorkbench.sh").exists()) {
            try {

                progressLogger.logProgress("Generating Launcher Batch..");

                String launcherFile = INSTALL_DIR + "VRWorkbench.sh";
                FileWriter fw = new FileWriter(launcherFile);
                PrintWriter pw = new PrintWriter(fw);
                pw.println("javaws http://biocep-distrib.r-forge.r-project.org/rworkbench.jnlp");
                fw.close();

                progressLogger.logProgress("Launcher Batch generated..");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // ---------------------------------------

        // String jripath = getLibraryPath("rJava", rpath, rlibs) + "jri/";
        String java_library_path = null;
        if (useDefaultUserLibs) {
            java_library_path = userrjavapath + "/jri/";
            System.out.println("jripath:" + java_library_path + "\n");
        } else {
            java_library_path = rlibs + "/rJava/jri/";
            System.out.println("jripath:" + java_library_path + "\n");
        }

        if (sci != null) {
            java_library_path += System.getProperty("path.separator") + sci_dll_path;
        }

        System.out.println("java.library.path" + java_library_path);

        String cp = null;
        if (useClassPath) {
            cp = PoolUtils.getAbsoluteClassPath();
        } else {
            cp = INSTALL_DIR + "classes";
        }

        if (sci != null) {
            if (isWindowsOs()) {
                cp = cp + System.getProperty("path.separator") + sci + "modules/javasci/jar/javasci.jar";
            } else {
                String scilabLibraryDir = INSTALL_DIR + "scilab/javasci/" + SCILAB_VERSION + "/";
                if (new File(scilabLibraryDir).exists())
                    new File(scilabLibraryDir).mkdirs();
                try {
                    PoolUtils.cacheJar(
                            new URL("http://www.biocep.net/scilab/" + SCILAB_VERSION + "/" + "javasci.jar"),
                            scilabLibraryDir, PoolUtils.LOG_PRGRESS_TO_SYSTEM_OUT, false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                cp = cp + System.getProperty("path.separator") + scilabLibraryDir + "javasci.jar";
            }

        }

        Vector<File> extraJarFiles = new Vector<File>();

        try {

            File[] flist = new File(INSTALL_DIR).listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.endsWith(".jar");
                }
            });
            Arrays.sort(flist);
            for (int i = 0; i < flist.length; ++i) {
                extraJarFiles.add(flist[i]);
            }

            System.out.println("Insiders Extra Jars:" + Arrays.toString(flist));

            if (System.getenv().get("BIOCEP_EXTRA_JARS_LOCATION") != null) {
                flist = new File(System.getenv().get("BIOCEP_EXTRA_JARS_LOCATION"))
                        .listFiles(new FilenameFilter() {
                            public boolean accept(File dir, String name) {
                                return name.endsWith(".jar");
                            }
                        });

                Arrays.sort(flist);
                System.out.println("Outsiders Extra Jars:" + Arrays.toString(flist));
                for (int i = 0; i < flist.length; ++i) {
                    extraJarFiles.add(flist[i]);
                }
            }

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

        ManagedServant[] servantHolder = new ManagedServant[1];
        RemoteException[] exceptionHolder = new RemoteException[1];

        CreationCallBack callBack = null;
        String listenerStub = null;

        progressLogger.logProgress("Creating R Server..");

        try {

            if (useCreationCallback) {
                callBack = new CreationCallBack(servantHolder, exceptionHolder);
                listenerStub = PoolUtils.stubToHex(callBack);
            }

            String uid = null;

            if (name != null && !name.equals("") && name.contains("%{uid}")) {
                if (uid == null)
                    uid = UUID.randomUUID().toString();
                name = PoolUtils.replaceAll(name, "%{uid}", uid);
            }

            if (logFile != null && !logFile.equals("") && logFile.contains("%{uid}")) {
                if (uid == null)
                    uid = UUID.randomUUID().toString();
                logFile = PoolUtils.replaceAll(logFile, "%{uid}", uid);
            }

            Vector<String> command = new Vector<String>();

            command.add((isWindowsOs() ? "\"" : "") + System.getProperty("java.home") + "/bin/java"
                    + (isWindowsOs() ? "\"" : ""));

            command.add((isWindowsOs() ? "\"" : "") + "-DXms" + memoryMinMegabytes + "m"
                    + (isWindowsOs() ? "\"" : ""));
            command.add((isWindowsOs() ? "\"" : "") + "-DXmx" + memoryMaxMegabytes + "m"
                    + (isWindowsOs() ? "\"" : ""));

            command.add("-cp");
            command.add((isWindowsOs() ? "\"" : "") + cp + (isWindowsOs() ? "\"" : ""));

            command.add((isWindowsOs() ? "\"" : "") + "-Djava.library.path=" + java_library_path
                    + (isWindowsOs() ? "\"" : ""));

            String codeBase = "http://" + codeServerHostIp + ":" + codeServerPort + "/classes/";

            if (codeUrls != null && codeUrls.length > 0) {
                for (int i = 0; i < codeUrls.length; ++i)
                    codeBase += " " + codeUrls[i].toString();
            }

            if (extraJarFiles.size() > 0) {
                for (int i = 0; i < extraJarFiles.size(); ++i)
                    codeBase += " " + extraJarFiles.elementAt(i).toURI().toURL().toString();
            }

            command.add((isWindowsOs() ? "\"" : "") + "-Djava.rmi.server.codebase=" + codeBase
                    + (isWindowsOs() ? "\"" : ""));
            if (keepAlive) {
                command.add((isWindowsOs() ? "\"" : "") + "-Dpreloadall=true" + (isWindowsOs() ? "\"" : ""));
            }

            command.add((isWindowsOs() ? "\"" : "") + "-Dservantclass=server.RServantImpl"
                    + (isWindowsOs() ? "\"" : ""));

            if (name == null || name.equals("")) {
                command.add((isWindowsOs() ? "\"" : "") + "-Dprivate=true" + (isWindowsOs() ? "\"" : ""));
            } else {
                command.add((isWindowsOs() ? "\"" : "") + "-Dname=" + name + (isWindowsOs() ? "\"" : ""));
            }

            if (useCreationCallback) {
                command.add((isWindowsOs() ? "\"" : "") + "-Dlistener.stub=" + listenerStub
                        + (isWindowsOs() ? "\"" : ""));
            }

            if (forcedIP != null && !forcedIP.equals("")) {
                command.add((isWindowsOs() ? "\"" : "") + "-Dhost.ip.forced=" + forcedIP
                        + (isWindowsOs() ? "\"" : ""));
            }

            command.add((isWindowsOs() ? "\"" : "") + "-Dapply.sandbox=false" + (isWindowsOs() ? "\"" : ""));
            command.add((isWindowsOs() ? "\"" : "") + "-Dworking.dir.root=" + INSTALL_DIR + "wdir"
                    + (isWindowsOs() ? "\"" : ""));

            command.add((isWindowsOs() ? "\"" : "") + "-Dkeepalive=" + keepAlive + (isWindowsOs() ? "\"" : ""));
            command.add((isWindowsOs() ? "\"" : "") + "-Dcode.server.host=" + codeServerHostIp
                    + (isWindowsOs() ? "\"" : ""));
            command.add((isWindowsOs() ? "\"" : "") + "-Dcode.server.port=" + codeServerPort
                    + (isWindowsOs() ? "\"" : ""));

            for (int i = 0; i < namingVars.length; ++i) {
                String var = namingVars[i];
                if (namingInfo.getProperty(var) != null && !namingInfo.getProperty(var).equals("")) {
                    command.add((isWindowsOs() ? "\"" : "") + "-D" + var + "=" + namingInfo.get(var)
                            + (isWindowsOs() ? "\"" : ""));
                }
            }

            command.add((isWindowsOs() ? "\"" : "") + "-Dapplication_type="
                    + (applicationType == null ? "" : applicationType) + (isWindowsOs() ? "\"" : ""));

            if (logFile != null && !logFile.equals("")) {
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "") + "-Dlog4j.rootCategory=DEBUG,A1,A2,A3"
                        + (isWindowsOs() ? "\"" : ""));

                command.add((isWindowsOs() ? "\"" : "") + "-Dlog4j.appender.A1=org.apache.log4j.ConsoleAppender"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A1.layout=org.apache.log4j.PatternLayout"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A1.layout.ConversionPattern=[%-5p] - %m%n"
                        + (isWindowsOs() ? "\"" : ""));

                command.add((isWindowsOs() ? "\"" : "") + "-Dlog4j.appender.A2=org.kchine.rpf.RemoteAppender"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A2.layout=org.apache.log4j.PatternLayout"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A2.layout.ConversionPattern=[%-5p] - %m%n"
                        + (isWindowsOs() ? "\"" : ""));

                command.add((isWindowsOs() ? "\"" : "") + "-Dlog4j.appender.A3=org.apache.log4j.FileAppender"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "") + "-Dlog4j.appender.A3.file=" + logFile
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A3.layout=org.apache.log4j.PatternLayout"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A3.layout.ConversionPattern=[%-5p] - %m%n"
                        + (isWindowsOs() ? "\"" : ""));
            }

            if (useClassPath) {
                command.add(mainClassName);
            } else {
                command.add("org.kchine.r.server.manager.bootstrap.Boot");
            }

            command.add("http://" + codeServerHostIp + ":" + codeServerPort + "/classes/");

            if (codeUrls != null && codeUrls.length > 0) {
                for (int i = 0; i < codeUrls.length; ++i) {
                    command.add(codeUrls[i].toString());
                }
            }

            if (extraJarFiles.size() > 0) {
                for (int i = 0; i < extraJarFiles.size(); ++i)
                    command.add(extraJarFiles.elementAt(i).toURI().toURL().toString());
            }

            final Process proc = Runtime.getRuntime().exec(command.toArray(new String[0]),
                    envVector.toArray(new String[0]));
            if (rShutdownHook != null) {
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            proc.waitFor();
                            rShutdownHook.run();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }

            final Vector<String> outPrint = new Vector<String>();
            final Vector<String> errorPrint = new Vector<String>();

            System.out.println(" command : " + command);

            new Thread(new Runnable() {
                public void run() {
                    try {
                        BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            System.out.println(line);
                            errorPrint.add(line);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    System.out.println();
                }
            }).start();

            new Thread(new Runnable() {
                public void run() {
                    try {
                        BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            System.out.println(line);
                            outPrint.add(line);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

            if (useCreationCallback) {
                long t1 = System.currentTimeMillis();
                while (servantHolder[0] == null && exceptionHolder[0] == null) {
                    if (System.currentTimeMillis() - t1 >= SERVANT_CREATION_TIMEOUT_MILLISEC)
                        throw new ServantCreationTimeout();
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                    }
                }
                if (exceptionHolder[0] != null) {
                    throw exceptionHolder[0];
                }
                progressLogger.logProgress("R Server Created.");
                return (RServices) servantHolder[0];
            } else {
                return null;
            }

        } finally {
            if (callBack != null) {
                UnicastRemoteObject.unexportObject(callBack, true);
            }
        }
    } finally {
        if (showProgress) {
            createRProgressFrame[0].dispose();
        }
    }
}

From source file:org.kchine.rpf.PoolUtils.java

public static String cacheJar(URL url, String location, int logInfo, boolean forced) throws Exception {
    final String jarName = url.toString().substring(url.toString().lastIndexOf("/") + 1);
    if (!location.endsWith("/") && !location.endsWith("\\"))
        location += "/";
    String fileName = location + jarName;
    new File(location).mkdirs();

    final JTextArea area = ((logInfo & LOG_PRGRESS_TO_DIALOG) != 0) ? new JTextArea() : null;
    final JProgressBar jpb = ((logInfo & LOG_PRGRESS_TO_DIALOG) != 0) ? new JProgressBar(0, 100) : null;
    final JFrame f = ((logInfo & LOG_PRGRESS_TO_DIALOG) != 0) ? new JFrame("copying " + jarName + " ...")
            : null;/*from   ww w .j  a v  a2 s.c  om*/

    try {
        ResponseCache.setDefault(null);
        URLConnection urlC = null;
        Exception connectionException = null;
        for (int i = 0; i < RECONNECTION_RETRIAL_NBR; ++i) {
            try {
                urlC = url.openConnection();
                connectionException = null;
                break;
            } catch (Exception e) {
                connectionException = e;
            }
        }
        if (connectionException != null)
            throw connectionException;

        InputStream is = url.openStream();
        File file = new File(fileName);

        long urlLastModified = urlC.getLastModified();
        if (!forced) {
            boolean somethingToDo = !file.exists() || file.lastModified() < urlLastModified
                    || (file.length() != urlC.getContentLength() && !isValidJar(fileName));
            if (!somethingToDo)
                return fileName;
        }

        if ((logInfo & LOG_PRGRESS_TO_DIALOG) != 0) {

            Runnable runnable = new Runnable() {
                public void run() {
                    try {
                        f.setUndecorated(true);
                        f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                        area.setEditable(false);

                        area.setForeground(Color.white);
                        area.setBackground(new Color(0x00, 0x80, 0x80));

                        jpb.setIndeterminate(true);
                        jpb.setForeground(Color.white);
                        jpb.setBackground(new Color(0x00, 0x80, 0x80));

                        JPanel p = new JPanel(new BorderLayout());
                        p.setBorder(BorderFactory.createLineBorder(Color.black, 3));
                        p.setBackground(new Color(0x00, 0x80, 0x80));
                        p.add(jpb, BorderLayout.SOUTH);
                        p.add(area, BorderLayout.CENTER);
                        f.add(p);
                        f.pack();
                        f.setSize(300, 80);
                        locateInScreenCenter(f);
                        f.setVisible(true);
                        System.out.println("here");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };

            if (SwingUtilities.isEventDispatchThread())
                runnable.run();
            else {
                SwingUtilities.invokeLater(runnable);
            }
        }

        if ((logInfo & LOG_PRGRESS_TO_SYSTEM_OUT) != 0) {
            System.out.println("Downloading " + jarName + ":");
            System.out.print("expected:==================================================\ndone    :");
        }

        if ((logInfo & LOG_PRGRESS_TO_LOGGER) != 0) {
            log.info("Downloading " + jarName + ":");
        }

        int jarSize = urlC.getContentLength();
        int currentPercentage = 0;

        FileOutputStream fos = null;
        fos = new FileOutputStream(fileName);

        int count = 0;
        int printcounter = 0;

        byte data[] = new byte[BUFFER_SIZE];
        int co = 0;
        while ((co = is.read(data, 0, BUFFER_SIZE)) != -1) {
            fos.write(data, 0, co);

            count = count + co;
            int expected = (50 * count / jarSize);
            while (printcounter < expected) {
                if ((logInfo & LOG_PRGRESS_TO_SYSTEM_OUT) != 0) {
                    System.out.print("=");
                }
                if ((logInfo & LOG_PRGRESS_TO_LOGGER) != 0) {
                    log.info((int) (100 * count / jarSize) + "% done.");
                }

                ++printcounter;
            }

            if ((logInfo & LOG_PRGRESS_TO_DIALOG) != 0) {
                final int p = (int) (100 * count / jarSize);
                if (p > currentPercentage) {
                    currentPercentage = p;

                    final JTextArea fa = area;
                    final JProgressBar fjpb = jpb;
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            fjpb.setIndeterminate(false);
                            fjpb.setValue(p);
                            fa.setText("Copying " + jarName + " ..." + "\n" + p + "%" + " Done. ");
                        }
                    });

                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            fa.setCaretPosition(fa.getText().length());
                            fa.repaint();
                            fjpb.repaint();
                        }
                    });

                }
            }

        }

        /*
         * while ((oneChar = is.read()) != -1) { fos.write(oneChar);
         * count++;
         * 
         * final int p = (int) (100 * count / jarSize); if (p >
         * currentPercentage) { System.out.print(p+" % "); currentPercentage =
         * p; if (showProgress) { final JTextArea fa = area; final
         * JProgressBar fjpb = jpb; SwingUtilities.invokeLater(new
         * Runnable() { public void run() { fjpb.setIndeterminate(false);
         * fjpb.setValue(p); fa.setText("\n" + p + "%" + " Done "); } });
         * 
         * SwingUtilities.invokeLater(new Runnable() { public void run() {
         * fa.setCaretPosition(fa.getText().length()); fa.repaint();
         * fjpb.repaint(); } }); } else { if (p%2==0) System.out.print("="); } }
         *  }
         * 
         */
        is.close();
        fos.close();

    } catch (MalformedURLException e) {
        System.err.println(e.toString());
        throw e;
    } catch (IOException e) {
        System.err.println(e.toString());

    } finally {
        if ((logInfo & LOG_PRGRESS_TO_DIALOG) != 0) {
            f.dispose();
        }
        if ((logInfo & LOG_PRGRESS_TO_SYSTEM_OUT) != 0) {
            System.out.println("\n 100% of " + jarName + " has been downloaded \n");
        }
        if ((logInfo & LOG_PRGRESS_TO_LOGGER) != 0) {
            log.info(" 100% of " + jarName + " has been downloaded");
        }
    }

    return fileName;
}

From source file:org.kepler.gui.ComponentLibraryPreferencesTab.java

/**
 * Initialize the top panel that contains controls for the table.
 *//*from w w  w.  j av  a2 s  . co  m*/
private void initTopPanel() {

    _newSource = new JButton(StaticResources.getDisplayString("general.ADD", "Add"));
    _newSource.setPreferredSize(new Dimension(100, 50));
    _newSource.addActionListener(new AddSourceListener());

    _removeSource = new JButton(StaticResources.getDisplayString("general.REMOVE", "Remove"));
    _removeSource.setPreferredSize(new Dimension(100, 50));
    _removeSource.addActionListener(new RemoveSourceListener());

    _defaultSources = new JButton(StaticResources.getDisplayString("preferences.useDefaults", "Use Defaults"));
    _defaultSources.setPreferredSize(new Dimension(100, 50));
    _defaultSources.addActionListener(new DefaultSourcesListener());

    _buildLibrary = new JButton(StaticResources.getDisplayString("preferences.build", "Build"));
    _buildLibrary.setPreferredSize(new Dimension(100, 50));
    _buildLibrary.addActionListener(new BuildLibraryListener());

    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
    buttonPanel.setBackground(TabManager.BGCOLOR);
    buttonPanel.setAlignmentX(RIGHT_ALIGNMENT);
    buttonPanel.add(_newSource);
    buttonPanel.add(_removeSource);
    buttonPanel.add(_defaultSources);
    buttonPanel.add(_buildLibrary);

    LibraryManager lm = LibraryManager.getInstance();

    JPanel topPanel = new JPanel(new BorderLayout());
    topPanel.add(buttonPanel, BorderLayout.CENTER);

    add(topPanel);

}