Example usage for javax.swing JLabel setText

List of usage examples for javax.swing JLabel setText

Introduction

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

Prototype

@BeanProperty(preferred = true, visualUpdate = true, description = "Defines the single line of text this component will display.")
public void setText(String text) 

Source Link

Document

Defines the single line of text this component will display.

Usage

From source file:com.declarativa.interprolog.gui.Ini.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    try {/*ww w .  j  ava2s .c  o  m*/
        Forest<String, Integer> forest = new DelegateForest<>();
        ObservableGraph g = new ObservableGraph(new BalloonLayoutDemo().createTree(forest));

        Layout layout = new BalloonLayout(forest);
        //Layout layout = new TreeLayout(forest, 70, 70);
        final BaseJungScene scene = new SceneImpl(g, layout);

        jLayeredPane1.setLayout(new BorderLayout());
        jLayeredPane1.add(new JScrollPane(scene.createView()), BorderLayout.CENTER);

        final JCheckBox checkbox = new JCheckBox("Animate iterative layouts");

        scene.setLayoutAnimationFramesPerSecond(48);

        //**********************
        DefaultComboBoxModel<Transformer<Context<Graph<String, Number>, Number>, Shape>> shapes = new DefaultComboBoxModel<>();
        shapes.addElement(new EdgeShape.QuadCurve<String, Number>());
        shapes.addElement(new EdgeShape.BentLine<String, Number>());
        shapes.addElement(new EdgeShape.CubicCurve<String, Number>());
        shapes.addElement(new EdgeShape.Line<String, Number>());
        shapes.addElement(new EdgeShape.Box<String, Number>());
        shapes.addElement(new EdgeShape.Orthogonal<String, Number>());
        shapes.addElement(new EdgeShape.Wedge<String, Number>(10));

        /*
        final JComboBox<Transformer<Context<Graph<String, Number>, Number>, Shape>> shapesBox = new JComboBox<>(shapes);
        shapesBox.addActionListener(new ActionListener() {
                
        @Override
        public void actionPerformed(ActionEvent ae) {
        Transformer<Context<Graph<String, Number>, Number>, Shape> xform = (Transformer<Context<Graph<String, Number>, Number>, Shape>) shapesBox.getSelectedItem();
        scene.setConnectionEdgeShape(xform);
        }
        });
                
                
                
        shapesBox.setRenderer(new DefaultListCellRenderer() {
        @Override
        public Component getListCellRendererComponent(JList<?> jlist, Object o, int i, boolean bln, boolean bln1) {
        o = o.getClass().getSimpleName();
        return super.getListCellRendererComponent(jlist, o, i, bln, bln1); //To change body of generated methods, choose Tools | Templates.
        }
        });
        shapesBox.setSelectedItem(new EdgeShape.QuadCurve<>());
                
        */
        final JLabel selectionLabel = new JLabel("<html>&nbsp;</html>");
        System.out.println("LOOKUP IS " + scene.getLookup());
        Lookup.Result<String> selectedNodes = scene.getLookup().lookupResult(String.class);
        LookupListener listener = new LookupListener() {
            @Override
            public void resultChanged(LookupEvent le) {
                System.out.println("RES CHANGED");
                Lookup.Result<String> res = (Lookup.Result<String>) le.getSource();
                StringBuilder sb = new StringBuilder("<html>");
                List<String> l = new ArrayList<>(res.allInstances());
                Collections.sort(l);
                for (String s : l) {
                    if (sb.length() != 0) {
                        sb.append(", ");
                    }
                    sb.append(s);
                }
                sb.append("</html>");
                selectionLabel.setText(sb.toString());
                System.out.println("LOOKUP EVENT " + sb);
            }
        };
        selectedNodes.addLookupListener(listener);
        selectedNodes.allInstances();

        checkbox.setSelected(true);
        checkbox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                scene.setAnimateIterativeLayouts(checkbox.isSelected());
            }
        });

        jLayeredPane1.setSize(456, 458);
        ////        jf.setSize(jf.getGraphicsConfiguration().getBounds().width - 120, 700);
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowOpened(WindowEvent we) {
                scene.relayout(true);
                scene.validate();
            }
        });

        /*
                
        int returnVal = fileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
                
        fileChooser.addChoosableFileFilter(new FileFilter() {
                
        public String getDescription() {
        return "Prolog native program (*.P)";
        }
                
        public boolean accept(File f) {
        if (f.isDirectory()) {
        return true;
        } else {
        return f.getName().toLowerCase().endsWith(".P");
        }
        }
        });
                
        try {
        // What to do with the file, e.g. display it in a TextArea
        prologOutput.read(new FileReader(file.getAbsolutePath()), null);
        } catch (IOException ex) {
        System.out.println("problem accessing file" + file.getAbsolutePath());
        }
        } else {
        System.out.println("File access cancelled by user.");
        }
                
        */

        //One file chooser for each buton click
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
        System.out.println("AUCH");
    }
}

From source file:generadorqr.jifrNuevoQr.java

void CargarImagen(JLabel label, Integer identificador) {
    int resultado;
    // ventana = new CargarFoto();
    JFileChooser jfchCargarfoto = new JFileChooser();
    FileNameExtensionFilter filtro = new FileNameExtensionFilter("JPG", "jpg");
    jfchCargarfoto.setFileFilter(filtro);
    resultado = jfchCargarfoto.showOpenDialog(null);
    if (JFileChooser.APPROVE_OPTION == resultado) {
        fichero = jfchCargarfoto.getSelectedFile();
        try {/*from www  . j  a va2  s . c  o  m*/
            tempImagen[identificador] = fichero.getPath();
            tempNombreArchivo[identificador] = fichero.getName();
            ImageIcon icon = new ImageIcon(fichero.toString());
            Icon icono = new ImageIcon(icon.getImage().getScaledInstance(label.getWidth(), label.getHeight(),
                    Image.SCALE_DEFAULT));
            label.setText(null);
            label.setIcon(icono);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error abriendo la imagen" + ex);
        }
    }
}

From source file:SuitaDetails.java

private void initGlobal() {
    suiteoptions = new JPanel();
    suiteoptions.setBackground(Color.WHITE);
    JLabel suite = new JLabel("Suite name: ");
    tsuite = new JTextField();
    ep = new JLabel("Run on SUT:");
    combo = new JList();
    suitelib = new JButton("Libraries");
    panicdetect = new JCheckBox("Panic Detect");
    panicdetect.setBackground(Color.WHITE);

    JScrollPane scroll = new JScrollPane();
    scroll.setViewportView(combo);/* ww w . j  av  a2s .co  m*/
    GroupLayout layout = new GroupLayout(suiteoptions);
    suiteoptions.setLayout(layout);
    layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                    .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(panicdetect)
                    .addComponent(suitelib, GroupLayout.PREFERRED_SIZE, 85,
                            javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ep).addComponent(suite))
                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(tsuite)
                            .addComponent(scroll, GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE))
                    .addContainerGap()));
    layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout
                    .createSequentialGroup().addContainerGap()
                    .addGroup(layout
                            .createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(suite)
                            .addComponent(tsuite, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                                    GroupLayout.PREFERRED_SIZE))
                    .addGap(10, 10, 10)
                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                    .addComponent(scroll, GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE)
                                    .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(panicdetect)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(suitelib))
                            .addComponent(ep))
                    .addContainerGap()));
    tcdelay = new JLabel("TC delay");
    savedb = new JCheckBox("DB autosave");
    ttcdelay = new JTextField();
    JButton globallib = new JButton("Libraries");
    savedb.setBackground(Color.WHITE);
    stoponfail = new JCheckBox("Stop on fail");
    stoponfail.setBackground(Color.WHITE);
    JLabel prescript = new JLabel();
    JLabel postscript = new JLabel();
    prestoponfail = new JCheckBox("Stop on fail");
    prestoponfail.setBackground(Color.WHITE);
    tprescript = new JTextField();
    tpostscript = new JTextField();
    browse1 = new JButton("...");
    browse2 = new JButton("...");
    prescript.setText("Pre execution script:");
    postscript.setText("Post execution script:");

    globallib.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ev) {
            showLib();
        }
    });

    suitelib.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ev) {
            showSuiteLib();
        }
    });

    browse1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            Container c;
            if (RunnerRepository.container != null)
                c = RunnerRepository.container.getParent();
            else
                c = RunnerRepository.window;
            try {
                new MySftpBrowser(RunnerRepository.host, RunnerRepository.user, RunnerRepository.password,
                        tprescript, c, false);
            } catch (Exception e) {
                System.out.println("There was a problem in opening sftp browser!");
                e.printStackTrace();
            }
        }
    });

    browse2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            Container c;
            if (RunnerRepository.container != null)
                c = RunnerRepository.container.getParent();
            else
                c = RunnerRepository.window;
            try {
                new MySftpBrowser(RunnerRepository.host, RunnerRepository.user, RunnerRepository.password,
                        tpostscript, c, false);
            } catch (Exception e) {
                System.out.println("There was a problem in opening sftp browser!");
                e.printStackTrace();
            }
        }
    });

    panicdetect.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            parent.setPanicdetect(panicdetect.isSelected());
        }
    });

    layout = new GroupLayout(global);
    global.setLayout(layout);
    layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout
            .createSequentialGroup()
            .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout
                    .createSequentialGroup().addContainerGap()
                    .addComponent(stoponfail, GroupLayout.PREFERRED_SIZE, 105, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(savedb, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                            GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(tcdelay)
                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(ttcdelay, GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE).addGap(12, 12, 12)
                    .addComponent(globallib))
                    .addGroup(layout.createSequentialGroup().addGap(10, 10, 10)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup().addComponent(prescript).addGap(20,
                                            20, 20))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                            layout.createSequentialGroup().addComponent(postscript).addGap(18,
                                                    18, 18)))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(tpostscript).addComponent(tprescript))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup().addComponent(browse1)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                            .addComponent(prestoponfail))
                                    .addComponent(browse2))))
            .addContainerGap()));
    layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout
            .createSequentialGroup().addGap(12, 12, 12)
            .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
                    .addComponent(stoponfail, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)
                    .addComponent(savedb, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                            GroupLayout.PREFERRED_SIZE)
                    .addComponent(tcdelay)
                    .addComponent(ttcdelay, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                            GroupLayout.PREFERRED_SIZE)
                    .addComponent(globallib))
            .addGap(11, 11, 11)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(prescript)
                    .addComponent(tprescript, javax.swing.GroupLayout.PREFERRED_SIZE,
                            javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(browse1).addComponent(prestoponfail))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tpostscript, javax.swing.GroupLayout.PREFERRED_SIZE,
                            javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(browse2).addComponent(postscript))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

    layout.linkSize(SwingConstants.VERTICAL, new Component[] { browse1, tprescript });

    layout.linkSize(SwingConstants.VERTICAL, new Component[] { browse2, tpostscript });
}

From source file:com.funambol.exchange.admin.DefaultExchangeConnectorConfigPanel.java

/**
 * Create the panel/*www  .  j ava 2 s. co m*/
 */
private void init() {

    JLabel title, contactFolderLabel, eventFolderLabel, taskFolderLabel, noteFolderLabel, seccServerLabel,
            seccPortLabel, exchangeServerLabel;
    JPanel seccPanel, exchangePanel, sslPanel;

    title = new JLabel();
    exchangePanel = new JPanel();
    seccPanel = new JPanel();
    sslPanel = new JPanel();

    contactFolderValue = new JTextField();
    eventFolderValue = new JTextField();
    taskFolderValue = new JTextField();
    noteFolderValue = new JTextField();
    seccServerLabel = new JLabel();
    seccServerValue = new JTextField();
    seccPortLabel = new JLabel();
    seccPortValue = new JTextField();
    useSSLValue = new JCheckBox();
    useFBAValue = new JCheckBox();
    useKeyStoreValue = new JCheckBox();
    keyStoreFileNameLabel = new JLabel();
    keyStoreFileNameValue = new JTextField();
    keyStorePasswordLabel = new JLabel();
    keyStorePasswordValue = new JTextField();

    exchangeServerLabel = new JLabel();
    exchangeServerValue = new JTextField();
    exchangeServerNameLabel = new JLabel();
    exchangeServerNameValue = new JTextField();
    setLayout(null);

    title.setFont(GuiFactory.titlePanelFont);
    title.setText("Funambol Exchange Connector");
    title.setBounds(new Rectangle(14, 5, 316, 28));
    title.setAlignmentX(SwingConstants.CENTER);
    title.setBorder(new TitledBorder(""));

    contactFolderLabel = new JLabel();
    contactFolderLabel.setText("Contact Folder: ");
    contactFolderLabel.setBounds(14, 35, 116, 15);
    add(contactFolderLabel);
    contactFolderValue.setBounds(150, 35, 220, 19);
    add(contactFolderValue);

    eventFolderLabel = new JLabel();
    eventFolderLabel.setText("Event Folder: ");
    eventFolderLabel.setBounds(14, 65, 116, 15);
    add(eventFolderLabel);
    eventFolderValue.setBounds(150, 65, 220, 19);
    add(eventFolderValue);

    taskFolderLabel = new JLabel();
    taskFolderLabel.setText("Task Folder: ");
    taskFolderLabel.setBounds(14, 95, 116, 15);
    add(taskFolderLabel);
    taskFolderValue.setBounds(150, 95, 220, 19);
    add(taskFolderValue);

    noteFolderLabel = new JLabel();
    noteFolderLabel.setText("Note Folder: ");
    noteFolderLabel.setBounds(14, 125, 116, 15);
    add(noteFolderLabel);
    noteFolderValue.setBounds(150, 125, 220, 19);
    add(noteFolderValue);

    seccPanel.setLayout(null);
    seccPanel.setBorder(new TitledBorder("HTTP Server Configuration"));

    seccServerLabel.setText("Server:");
    seccPanel.add(seccServerLabel);
    seccServerLabel.setBounds(10, 20, 116, 15);
    seccPanel.add(seccServerValue);
    seccServerValue.setBounds(150, 20, 220, 19);
    seccServerValue.setFont(GuiFactory.defaultFont);

    seccPortLabel.setText("Port:");
    seccPanel.add(seccPortLabel);
    seccPortLabel.setBounds(10, 50, 131, 15);
    seccPanel.add(seccPortValue);
    seccPortValue.setBounds(150, 50, 220, 19);
    seccPortValue.setFont(GuiFactory.defaultFont);

    add(seccPanel);
    seccPanel.setBounds(10, 155, 380, 80);

    exchangePanel.setLayout(null);
    exchangePanel.setBorder(new TitledBorder("WebDav Message Configuration"));

    exchangeServerLabel.setText("Server: ");
    exchangePanel.add(exchangeServerLabel);
    exchangeServerLabel.setBounds(10, 20, 150, 19);
    exchangePanel.add(exchangeServerValue);
    exchangeServerValue.setBounds(150, 20, 220, 19);
    exchangeServerValue.setFont(GuiFactory.defaultFont);

    exchangeServerNameLabel.setText("Name:");
    exchangeServerNameLabel.setBounds(10, 50, 150, 19);
    exchangePanel.add(exchangeServerNameLabel);
    exchangeServerNameValue.setBounds(150, 50, 220, 19);
    exchangeServerNameValue.setFont(GuiFactory.defaultFont);
    exchangePanel.add(exchangeServerNameValue);

    add(exchangePanel);
    exchangePanel.setBounds(10, 255, 380, 80);

    //the ssl option panel

    sslPanel.setLayout(null);
    sslPanel.setBorder(new TitledBorder("SSL"));

    useSSLValue.setText("Use SSL");
    useSSLValue.setSelected(false);
    useSSLValue.setBounds(5, 20, 150, 19);
    sslPanel.add(useSSLValue);

    useFBAValue.setText("Use Form-Based Authentication");
    useFBAValue.setSelected(true);
    useFBAValue.setBounds(5, 40, 250, 19);
    sslPanel.add(useFBAValue);

    useKeyStoreValue.setText("Use Keystore");
    useKeyStoreValue.setSelected(false);
    useKeyStoreValue.setBounds(5, 60, 200, 19);
    sslPanel.add(useKeyStoreValue);

    useKeyStoreValue.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent acEvent) {
            boolean enabled = useKeyStoreValue.isSelected();
            keyStoreFileNameLabel.setEnabled(enabled);
            keyStoreFileNameValue.setEnabled(enabled);
            keyStorePasswordLabel.setEnabled(enabled);
            keyStorePasswordValue.setEnabled(enabled);
        }
    });

    keyStoreFileNameLabel.setText("Key Store File: ");
    sslPanel.add(keyStoreFileNameLabel);
    keyStoreFileNameLabel.setEnabled(false);
    keyStoreFileNameLabel.setBounds(10, 80, 131, 15);
    sslPanel.add(keyStoreFileNameValue);
    keyStoreFileNameValue.setEnabled(false);
    keyStoreFileNameValue.setBounds(150, 80, 220, 19);
    keyStoreFileNameValue.setFont(GuiFactory.defaultFont);

    keyStorePasswordLabel.setText("Key Store Password: ");
    sslPanel.add(keyStorePasswordLabel);
    keyStorePasswordLabel.setEnabled(false);
    keyStorePasswordLabel.setBounds(10, 110, 131, 15);
    sslPanel.add(keyStorePasswordValue);
    keyStorePasswordValue.setEnabled(false);
    keyStorePasswordValue.setBounds(150, 110, 220, 19);
    keyStorePasswordValue.setFont(GuiFactory.defaultFont);

    add(sslPanel);
    sslPanel.setBounds(10, 355, 450, 140);

    confirmButton.setFont(GuiFactory.defaultFont);
    confirmButton.setText("Save");
    add(confirmButton);
    confirmButton.setBounds(120, 500, 70, 25);
    confirmButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent event) {
            getValues();
            configPanel.saveDefaultConfig(event.getActionCommand());
            configPanel.finishedDefaultConfig();
        }
    });

    cancelButton.setFont(GuiFactory.defaultFont);
    cancelButton.setText("Cancel");
    add(cancelButton);
    cancelButton.setBounds(200, 500, 70, 25);
    cancelButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            configPanel.finishedDefaultConfig();
        }

    });

    //
    // Setting font...
    //
    Component[] components = getComponents();
    for (int i = 0; (components != null) && (i < components.length); ++i) {
        components[i].setFont(GuiFactory.defaultFont);
    }

    //
    // We add it as the last one so that the font won't be changed
    //
    add(title);
}

From source file:de.tor.tribes.ui.renderer.ColoredCoutdownCellRenderer.java

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
        int row, int column) {
    Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    try {//  w w  w  .j a  v a 2 s  . c om
        JLabel renderComponent = ((JLabel) c);
        Long d = (Long) value;

        // renderComponent.setText(DurationFormatUtils.formatDuration(d, "HHH:mm:ss.SSS", true));

        long diff = d;
        long five_minutes = 5 * MINUTE;
        long ten_minutes = 10 * MINUTE;
        Color color = null;
        if (row % 2 == 0) {
            color = Constants.DS_ROW_A;
        } else {
            color = Constants.DS_ROW_B;
        }

        if (diff <= 0) {
            //value is expired, stroke result
            //renderComponent.setText(specialFormat.format(d));
            //renderComponent.setForeground(Color.RED);
        } else if (diff <= ten_minutes && diff > five_minutes) {
            float ratio = (float) (diff - five_minutes) / (float) five_minutes;
            Color c1 = Color.YELLOW;
            Color c2 = Color.GREEN;
            int red = (int) (c2.getRed() * ratio + c1.getRed() * (1 - ratio));
            int green = (int) (c2.getGreen() * ratio + c1.getGreen() * (1 - ratio));
            int blue = (int) (c2.getBlue() * ratio + c1.getBlue() * (1 - ratio));
            color = new Color(red, green, blue);
        } else if (diff <= five_minutes) {
            float ratio = (float) diff / (float) five_minutes;
            Color c1 = Color.RED;
            Color c2 = Color.YELLOW;
            int red = (int) (c2.getRed() * ratio + c1.getRed() * (1 - ratio));
            int green = (int) (c2.getGreen() * ratio + c1.getGreen() * (1 - ratio));
            int blue = (int) (c2.getBlue() * ratio + c1.getBlue() * (1 - ratio));
            color = new Color(red, green, blue);
        }
        renderComponent.setText(DurationFormatUtils.formatDuration(d, "HHH:mm:ss.SSS", true));
        if (isSelected) {
            color = c.getBackground();
        }
        renderComponent.setOpaque(true);
        renderComponent.setBackground(color);
        return renderComponent;
    } catch (Exception e) {
        return c;
    }
}

From source file:org.nebulaframework.ui.swing.cluster.ClusterMainUI.java

/**
 * Creates a tab pane for the given GridJob.
 * /*from  w  w w .jav a  2s. co m*/
 * @param jobId JobId
 */
protected void createJobTab(final String jobId) {

    // Request Job Profile
    final InternalClusterJobService jobService = ClusterManager.getInstance().getJobService();
    final GridJobProfile profile = jobService.getProfile(jobId);

    // Job Start Time
    final long startTime = System.currentTimeMillis();

    final JPanel jobPanel = new JPanel();
    jobPanel.setLayout(new BorderLayout(10, 10));

    // Progess Panel
    JPanel progressPanel = new JPanel();
    progressPanel.setLayout(new BorderLayout(10, 10));
    progressPanel.setBorder(BorderFactory.createTitledBorder("Progress"));
    jobPanel.add(progressPanel, BorderLayout.NORTH);

    final JProgressBar progressBar = new JProgressBar();
    progressBar.setStringPainted(true);
    progressPanel.add(progressBar, BorderLayout.CENTER);
    addUIElement("jobs." + jobId + ".progress", progressBar); // Add to components map

    // Buttons Panel
    JPanel buttonsPanel = new JPanel();
    jobPanel.add(buttonsPanel, BorderLayout.SOUTH);
    buttonsPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

    // Terminate Button
    JButton terminateButton = new JButton("Terminate");
    terminateButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            new Thread(new Runnable() {

                public void run() {

                    // Job Name = Class Name
                    String name = profile.getJob().getClass().getSimpleName();

                    // Request user confirmation
                    int option = JOptionPane.showConfirmDialog(ClusterMainUI.this,
                            "Are you sure to terminate GridJob " + name + "?", "Nebula - Terminate GridJob",
                            JOptionPane.YES_NO_OPTION);

                    if (option == JOptionPane.NO_OPTION)
                        return;

                    // Attempt Cancel
                    boolean result = profile.getFuture().cancel();

                    // Notify results
                    if (result) {
                        JOptionPane.showMessageDialog(ClusterMainUI.this,
                                "Grid Job '" + name + "terminated successfully.", "Nebula - Job Terminated",
                                JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(ClusterMainUI.this,
                                "Failed to terminate Grid Job '" + name, "Nebula - Job Termination Failed",
                                JOptionPane.WARNING_MESSAGE);
                    }
                }

            }).start();
        }
    });
    buttonsPanel.add(terminateButton);
    addUIElement("jobs." + jobId + ".terminate", terminateButton); // Add to components map

    // Close Tab Button
    JButton closeButton = new JButton("Close Tab");
    closeButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    removeJobTab(jobId);
                }
            });
        }
    });
    closeButton.setEnabled(false);

    buttonsPanel.add(closeButton);
    addUIElement("jobs." + jobId + ".closetab", closeButton); // Add to components map

    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(new GridBagLayout());
    jobPanel.add(centerPanel, BorderLayout.CENTER);

    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.weightx = 1.0;

    /* -- Job Information -- */

    JPanel jobInfoPanel = new JPanel();
    jobInfoPanel.setBorder(BorderFactory.createTitledBorder("Job Information"));
    jobInfoPanel.setLayout(new GridBagLayout());
    c.gridy = 0;
    c.ipady = 30;
    centerPanel.add(jobInfoPanel, c);

    GridBagConstraints c1 = new GridBagConstraints();
    c1.fill = GridBagConstraints.BOTH;
    c1.weightx = 1;
    c1.weighty = 1;

    // Name
    jobInfoPanel.add(new JLabel("Name :"), c1);
    JLabel jobNameLabel = new JLabel();
    jobInfoPanel.add(jobNameLabel, c1);
    jobNameLabel.setText(profile.getJob().getClass().getSimpleName());
    addUIElement("jobs." + jobId + ".job.name", jobNameLabel); // Add to components map

    // Gap
    jobInfoPanel.add(new JLabel(), c1);

    // Type
    jobInfoPanel.add(new JLabel("Type :"), c1);
    JLabel jobType = new JLabel();
    jobType.setText(getJobType(profile.getJob()));
    jobInfoPanel.add(jobType, c1);
    addUIElement("jobs." + jobId + ".job.type", jobType); // Add to components map

    // Job Class Name
    c1.gridy = 1;
    c1.gridwidth = 1;
    jobInfoPanel.add(new JLabel("GridJob Class :"), c1);
    c1.gridwidth = GridBagConstraints.REMAINDER;
    JLabel jobClassLabel = new JLabel();
    jobClassLabel.setText(profile.getJob().getClass().getName());
    jobInfoPanel.add(jobClassLabel, c1);
    addUIElement("jobs." + jobId + ".job.class", jobClassLabel); // Add to components map

    /* -- Execution Information -- */

    JPanel executionInfoPanel = new JPanel();
    executionInfoPanel.setBorder(BorderFactory.createTitledBorder("Execution Statistics"));
    executionInfoPanel.setLayout(new GridBagLayout());
    c.gridy = 1;
    c.ipady = 30;
    centerPanel.add(executionInfoPanel, c);

    GridBagConstraints c3 = new GridBagConstraints();
    c3.weightx = 1;
    c3.weighty = 1;
    c3.fill = GridBagConstraints.BOTH;

    // Start Time
    executionInfoPanel.add(new JLabel("Job Status :"), c3);
    final JLabel statusLabel = new JLabel("Initializing");
    executionInfoPanel.add(statusLabel, c3);
    addUIElement("jobs." + jobId + ".execution.status", statusLabel); // Add to components map

    // Status Update Listener
    profile.getFuture().addGridJobStateListener(new GridJobStateListener() {
        public void stateChanged(final GridJobState newState) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    statusLabel.setText(StringUtils.capitalize(newState.toString().toLowerCase()));
                }
            });
        }
    });

    executionInfoPanel.add(new JLabel(), c3); // Space Holder

    // Percent Complete
    executionInfoPanel.add(new JLabel("Completed % :"), c3);
    final JLabel percentLabel = new JLabel("-N/A-");
    executionInfoPanel.add(percentLabel, c3);
    addUIElement("jobs." + jobId + ".execution.percentage", percentLabel); // Add to components map

    c3.gridy = 1;

    // Start Time
    executionInfoPanel.add(new JLabel("Start Time :"), c3);
    JLabel startTimeLabel = new JLabel(DateFormat.getInstance().format(new Date(startTime)));
    executionInfoPanel.add(startTimeLabel, c3);
    addUIElement("jobs." + jobId + ".execution.starttime", startTimeLabel); // Add to components map

    executionInfoPanel.add(new JLabel(), c3); // Space Holder

    // Elapsed Time
    executionInfoPanel.add(new JLabel("Elapsed Time :"), c3);
    JLabel elapsedTimeLabel = new JLabel("-N/A-");
    executionInfoPanel.add(elapsedTimeLabel, c3);
    addUIElement("jobs." + jobId + ".execution.elapsedtime", elapsedTimeLabel); // Add to components map

    c3.gridy = 2;

    // Tasks Deployed (Count)
    executionInfoPanel.add(new JLabel("Tasks Deployed :"), c3);
    JLabel tasksDeployedLabel = new JLabel("-N/A-");
    executionInfoPanel.add(tasksDeployedLabel, c3);
    addUIElement("jobs." + jobId + ".execution.tasks", tasksDeployedLabel); // Add to components map

    executionInfoPanel.add(new JLabel(), c3); // Space Holder

    // Results Collected (Count)
    executionInfoPanel.add(new JLabel("Results Collected :"), c3);
    JLabel resultsCollectedLabel = new JLabel("-N/A-");
    executionInfoPanel.add(resultsCollectedLabel, c3);
    addUIElement("jobs." + jobId + ".execution.results", resultsCollectedLabel); // Add to components map

    c3.gridy = 3;

    // Remaining Tasks (Count)
    executionInfoPanel.add(new JLabel("Remaining Tasks :"), c3);
    JLabel remainingTasksLabel = new JLabel("-N/A-");
    executionInfoPanel.add(remainingTasksLabel, c3);
    addUIElement("jobs." + jobId + ".execution.remaining", remainingTasksLabel); // Add to components map

    executionInfoPanel.add(new JLabel(), c3); // Space Holder

    // Failed Tasks (Count)
    executionInfoPanel.add(new JLabel("Failed Tasks :"), c3);
    JLabel failedTasksLabel = new JLabel("-N/A-");
    executionInfoPanel.add(failedTasksLabel, c3);
    addUIElement("jobs." + jobId + ".execution.failed", failedTasksLabel); // Add to components map

    /* -- Submitter Information -- */
    UUID ownerId = profile.getOwner();
    GridNodeDelegate owner = ClusterManager.getInstance().getClusterRegistrationService()
            .getGridNodeDelegate(ownerId);

    JPanel ownerInfoPanel = new JPanel();
    ownerInfoPanel.setBorder(BorderFactory.createTitledBorder("Owner Information"));
    ownerInfoPanel.setLayout(new GridBagLayout());
    c.gridy = 2;
    c.ipady = 10;
    centerPanel.add(ownerInfoPanel, c);

    GridBagConstraints c2 = new GridBagConstraints();

    c2.fill = GridBagConstraints.BOTH;
    c2.weightx = 1;
    c2.weighty = 1;

    // Host Name
    ownerInfoPanel.add(new JLabel("Host Name :"), c2);
    JLabel hostNameLabel = new JLabel(owner.getProfile().getName());
    ownerInfoPanel.add(hostNameLabel, c2);
    addUIElement("jobs." + jobId + ".owner.hostname", hostNameLabel); // Add to components map

    // Gap
    ownerInfoPanel.add(new JLabel(), c2);

    // Host IP Address
    ownerInfoPanel.add(new JLabel("Host IP :"), c2);
    JLabel hostIPLabel = new JLabel(owner.getProfile().getIpAddress());
    ownerInfoPanel.add(hostIPLabel, c2);
    addUIElement("jobs." + jobId + ".owner.hostip", hostIPLabel); // Add to components map

    // Owner UUID
    c2.gridy = 1;
    c2.gridx = 0;
    ownerInfoPanel.add(new JLabel("Owner ID :"), c2);
    JLabel ownerIdLabel = new JLabel(profile.getOwner().toString());
    c2.gridx = 1;
    c2.gridwidth = 4;
    ownerInfoPanel.add(ownerIdLabel, c2);
    addUIElement("jobs." + jobId + ".owner.id", ownerIdLabel); // Add to components map

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            // Create Tab
            addUIElement("jobs." + jobId, jobPanel);
            JTabbedPane tabs = getUIElement("tabs");
            tabs.addTab(profile.getJob().getClass().getSimpleName(), jobPanel);
            tabs.revalidate();
        }
    });

    // Execution Information Updater Thread
    new Thread(new Runnable() {

        boolean initialized = false;
        boolean unbounded = false;

        public void run() {

            // Unbounded, No Progress Supported
            if ((!initialized) && profile.getJob() instanceof UnboundedGridJob<?>) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        progressBar.setIndeterminate(true);
                        progressBar.setStringPainted(false);

                        // Infinity Symbol
                        percentLabel.setText(String.valueOf('\u221e'));

                    }
                });
                initialized = true;
                unbounded = true;
            }

            // Update Job Info
            while (true) {

                try {
                    // 500ms Interval
                    Thread.sleep(500);

                } catch (InterruptedException e) {
                    log.warn("Interrupted Progress Updater Thread", e);
                }

                final int totalCount = profile.getTotalTasks();
                final int tasksRem = profile.getTaskCount();
                final int resCount = profile.getResultCount();
                final int failCount = profile.getFailedCount();

                showBusyIcon();

                // Task Information
                JLabel totalTaskLabel = getUIElement("jobs." + jobId + ".execution.tasks");
                totalTaskLabel.setText(String.valueOf(totalCount));

                // Result Count
                JLabel resCountLabel = getUIElement("jobs." + jobId + ".execution.results");
                resCountLabel.setText(String.valueOf(resCount));

                // Remaining Task Count
                JLabel remLabel = getUIElement("jobs." + jobId + ".execution.remaining");
                remLabel.setText(String.valueOf(tasksRem));

                // Failed Task Count
                JLabel failedLabel = getUIElement("jobs." + jobId + ".execution.failed");
                failedLabel.setText(String.valueOf(failCount));

                // Elapsed Time
                JLabel elapsedLabel = getUIElement("jobs." + jobId + ".execution.elapsedtime");
                elapsedLabel.setText(TimeUtils.timeDifference(startTime));

                // Job State
                final JLabel statusLabel = getUIElement("jobs." + jobId + ".execution.status");

                // If not in Executing Mode
                if ((!profile.getFuture().isJobFinished())
                        && profile.getFuture().getState() != GridJobState.EXECUTING) {
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {

                            // Progress Bar
                            progressBar.setIndeterminate(true);
                            progressBar.setStringPainted(false);

                            // Status Text
                            String state = profile.getFuture().getState().toString();
                            statusLabel.setText(StringUtils.capitalize(state.toLowerCase()));

                            // Percentage Label
                            percentLabel.setText(String.valueOf('\u221e'));
                        }
                    });
                } else { // Executing Mode : Progress Information

                    // Job Finished, Stop
                    if (profile.getFuture().isJobFinished()) {
                        showIdleIcon();
                        return;
                    }

                    // Double check for status label
                    if (!statusLabel.getText().equalsIgnoreCase("executing")) {
                        SwingUtilities.invokeLater(new Runnable() {

                            @Override
                            public void run() {
                                String newstate = profile.getFuture().getState().toString();
                                statusLabel.setText(StringUtils.capitalize(newstate.toLowerCase()));
                            }

                        });
                    }

                    if (!unbounded) {

                        final int percentage = (int) (profile.percentage() * 100);

                        //final int failCount = profile.get
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {

                                // If finished at this point, do not update
                                if (progressBar.getValue() == 100) {
                                    return;
                                }

                                // If ProgressBar is in indeterminate
                                if (progressBar.isIndeterminate()) {
                                    progressBar.setIndeterminate(false);
                                    progressBar.setStringPainted(true);
                                }

                                // Update Progress Bar / Percent Label
                                progressBar.setValue(percentage);
                                percentLabel.setText(percentage + " %");

                            }
                        });
                    }
                }

            }
        }
    }).start();

    // Job End Hook to Execute Job End Actions
    ServiceEventsSupport.addServiceHook(new ServiceHookCallback() {

        public void onServiceEvent(final ServiceMessage event) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {

                    JButton close = getUIElement("jobs." + jobId + ".closetab");
                    JButton terminate = getUIElement("jobs." + jobId + ".terminate");
                    terminate.setEnabled(false);
                    close.setEnabled(true);

                    JProgressBar progress = getUIElement("jobs." + jobId + ".progress");
                    JLabel percentage = getUIElement("jobs." + jobId + ".execution.percentage");

                    progress.setEnabled(false);

                    // If Successfully Finished
                    if (event.getType() == ServiceMessageType.JOB_END) {

                        if (profile.getFuture().getState() != GridJobState.FAILED) {
                            // If Not Job Failed
                            progress.setValue(100);
                            percentage.setText("100 %");
                        } else {
                            // If Failed
                            percentage.setText("N/A");
                        }

                        // Stop (if) Indeterminate Progress Bar
                        if (progress.isIndeterminate()) {
                            progress.setIndeterminate(false);
                            progress.setStringPainted(true);
                        }
                    } else if (event.getType() == ServiceMessageType.JOB_CANCEL) {

                        if (progress.isIndeterminate()) {
                            progress.setIndeterminate(false);
                            progress.setStringPainted(false);
                            percentage.setText("N/A");
                        }
                    }

                    showIdleIcon();
                }
            });
        }

    }, jobId, ServiceMessageType.JOB_CANCEL, ServiceMessageType.JOB_END);
}

From source file:de.hsos.ecs.richwps.wpsmonitor.boundary.gui.controls.datasource.WpsDialog.java

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor./*ww w  .  ja va  2  s  .  c  o m*/
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {

    JPanel jPanel1 = new JPanel();
    closeButton = new JButton();
    addToMonitorButton = new JButton();
    treeScrollPane = new JScrollPane();
    wpsTree = new JTree();
    JLabel jLabel1 = new JLabel();

    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("List of WPS-Servers- and Processes");
    setIconImage(new ImageIcon(getClass().getResource("/icons/database.png")).getImage());
    setMinimumSize(null);
    setName("wpsDialog"); // NOI18N
    setResizable(false);

    jPanel1.setBorder(BorderFactory.createTitledBorder(""));

    closeButton.setIcon(new ImageIcon(getClass().getResource("/icons/apply.png"))); // NOI18N
    closeButton.setText("Close");
    closeButton.setName("closeButton"); // NOI18N
    closeButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            closeButtonActionPerformed(evt);
        }
    });

    addToMonitorButton.setIcon(new ImageIcon(getClass().getResource("/icons/add.png"))); // NOI18N
    addToMonitorButton.setText("Add WPS with Processes");
    addToMonitorButton.setName("addToMonitorButton"); // NOI18N
    addToMonitorButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            addToMonitorButtonActionPerformed(evt);
        }
    });

    DefaultMutableTreeNode treeNode1 = new DefaultMutableTreeNode("root");
    wpsTree.setModel(new DefaultTreeModel(treeNode1));
    wpsTree.setName("wpsTree"); // NOI18N
    treeScrollPane.setViewportView(wpsTree);

    jLabel1.setText(
            "<html><body>Here is a list of all registered data-sources. You can pick up processes and WPS and add your choice to the monitor through the \"Add WPS with Processes\"-Button. If you select only a WPS, all processes of this WPS will also  be added. The processes will  be saved, but they have no Jobs or a testrequest.</body></html>");

    GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup().addContainerGap().addGroup(jPanel1Layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup().addGap(0, 0, Short.MAX_VALUE)
                            .addComponent(addToMonitorButton)
                            .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(closeButton))
                    .addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(treeScrollPane, GroupLayout.PREFERRED_SIZE, 630,
                                    GroupLayout.PREFERRED_SIZE)
                            .addGap(0, 0, Short.MAX_VALUE)))
                    .addContainerGap()));
    jPanel1Layout
            .setVerticalGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup().addContainerGap()
                            .addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                                    GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(treeScrollPane, GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE)
                            .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                    .addComponent(addToMonitorButton).addComponent(closeButton))
                            .addContainerGap()));

    GroupLayout layout = new GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup().addContainerGap()
                    .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap()));
    layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup().addContainerGap()
                    .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap()));

    pack();
}

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

/**
 * @return a username/password pair if valid or null if canceled
 * @throws SQLException//  w  ww.j a  v  a2s .  c om
 */
public static Pair<String, String> getITUsernamePwd() {
    JTextField userNameTF = UIHelper.createTextField(15);
    JPasswordField passwordTF = UIHelper.createPasswordField();
    JLabel statusLbl = UIHelper.createLabel("");

    JPanel loginPanel = createLoginPanel("IT_Username", userNameTF, "IT_Password", passwordTF, statusLbl,
            "MySQLFull");

    while (true) {
        CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getMostRecentWindow(),
                UIRegistry.getResourceString("IT_LOGIN"), true, loginPanel);
        dlg.setVisible(true);
        if (!dlg.isCancelled()) {
            String uName = userNameTF.getText();
            String pwd = new String(passwordTF.getPassword());

            DBConnection dbc = DBConnection.getInstance();
            DBConnection dbConn = DBConnection.createInstance(dbc.getDriver(), dbc.getDialect(),
                    dbc.getDatabaseName(), dbc.getConnectionStr(), uName, pwd);
            if (dbConn != null) {
                DBMSUserMgr dbMgr = DBMSUserMgr.getInstance();
                dbMgr.close();

                if (dbMgr.connect(uName, pwd, dbc.getServerName(), dbc.getDatabaseName())) {
                    dbMgr.close();
                    return new Pair<String, String>(uName, pwd);
                }
                dbMgr.close();
                statusLbl.setText("<HTML><font color=\"red\">" + UIRegistry.getResourceString("IT_LOGIN_ERROR")
                        + "</font></HTML>");
            }
        } else {
            return null;
        }
    }
}

From source file:projects.wdlf47tuc.ProcessAllSwathcal.java

/**
 * Main entry point.//from www.j  a v  a2s.  co m
 * 
 * @param args
 * 
 * @throws IOException 
 * 
 */
public ProcessAllSwathcal() {

    // Path to AllSwathcal.dat file
    File allSwathcal = new File(
            "/home/nrowell/Astronomy/Data/47_Tuc/Kalirai_2012/UVIS/www.stsci.edu/~jkalirai/47Tuc/AllSwathcal.dat");

    // Read file contents into the List
    try (BufferedReader in = new BufferedReader(new FileReader(allSwathcal))) {
        String sourceStr;
        while ((sourceStr = in.readLine()) != null) {
            Source source = Source.parseSource(sourceStr);
            if (source != null) {
                allSources.add(source);
            }
        }
    } catch (IOException e) {
    }

    logger.info("Parsed " + allSources.size() + " Sources from AllSwathcal.dat");

    // Initialise chart
    cmdPanel = new ChartPanel(updateDataAndPlotCmd(allSources));
    cmdPanel.addChartMouseListener(new ChartMouseListener() {
        @Override
        public void chartMouseClicked(ChartMouseEvent e) {
            // Capture mouse click location, transform to graph coordinates and add
            // a point to the polygonal selection box.
            Point2D p = cmdPanel.translateScreenToJava2D(e.getTrigger().getPoint());
            Rectangle2D plotArea = cmdPanel.getScreenDataArea();
            XYPlot plot = (XYPlot) cmdPanel.getChart().getPlot();
            double chartX = plot.getDomainAxis().java2DToValue(p.getX(), plotArea, plot.getDomainAxisEdge());
            double chartY = plot.getRangeAxis().java2DToValue(p.getY(), plotArea, plot.getRangeAxisEdge());
            points.add(new double[] { chartX, chartY });
            cmdPanel.setChart(plotCmd());
        }

        @Override
        public void chartMouseMoved(ChartMouseEvent arg0) {
        }
    });

    // Create colour combo boxes
    final JComboBox<Filter> magComboBox = new JComboBox<Filter>(filters);
    final JComboBox<Filter> col1ComboBox = new JComboBox<Filter>(filters);
    final JComboBox<Filter> col2ComboBox = new JComboBox<Filter>(filters);

    // Set initial values
    magComboBox.setSelectedItem(magFilter);
    col1ComboBox.setSelectedItem(col1Filter);
    col2ComboBox.setSelectedItem(col2Filter);

    // Create an action listener for these
    ActionListener al = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            if (evt.getSource() == magComboBox) {
                magFilter = (Filter) magComboBox.getSelectedItem();
            }
            if (evt.getSource() == col1ComboBox) {
                col1Filter = (Filter) col1ComboBox.getSelectedItem();
            }
            if (evt.getSource() == col2ComboBox) {
                col2Filter = (Filter) col2ComboBox.getSelectedItem();
            }
            // Changed colour(s), so reset selection box coordinates
            points.clear();
            cmdPanel.setChart(updateDataAndPlotCmd(allSources));
        }
    };
    magComboBox.addActionListener(al);
    col1ComboBox.addActionListener(al);
    col2ComboBox.addActionListener(al);
    // Add a bit of padding to space things out
    magComboBox.setBorder(new EmptyBorder(5, 5, 5, 5));
    col1ComboBox.setBorder(new EmptyBorder(5, 5, 5, 5));
    col2ComboBox.setBorder(new EmptyBorder(5, 5, 5, 5));

    // Set up statistic sliders
    final JSlider magErrMaxSlider = GuiUtil.buildSlider(magErrorRangeMin, magErrorRangeMax, 3, "%3.3f");
    final JSlider chi2MaxSlider = GuiUtil.buildSlider(chi2RangeMin, chi2RangeMax, 3, "%3.3f");
    final JSlider sharpMinSlider = GuiUtil.buildSlider(sharpRangeMin, sharpRangeMax, 3, "%3.3f");
    final JSlider sharpMaxSlider = GuiUtil.buildSlider(sharpRangeMin, sharpRangeMax, 3, "%3.3f");

    // Set intial values
    magErrMaxSlider.setValue(
            (int) Math.rint(100.0 * (magErrMax - magErrorRangeMin) / (magErrorRangeMax - magErrorRangeMin)));
    chi2MaxSlider.setValue((int) Math.rint(100.0 * (chi2Max - chi2RangeMin) / (chi2RangeMax - chi2RangeMin)));
    sharpMinSlider
            .setValue((int) Math.rint(100.0 * (sharpMin - sharpRangeMin) / (sharpRangeMax - sharpRangeMin)));
    sharpMaxSlider
            .setValue((int) Math.rint(100.0 * (sharpMax - sharpRangeMin) / (sharpRangeMax - sharpRangeMin)));

    // Set labels & initial values
    final JLabel magErrMaxLabel = new JLabel(getMagErrMaxLabel());
    final JLabel chi2MaxLabel = new JLabel(getChi2MaxLabel());
    final JLabel sharpMinLabel = new JLabel(getSharpMinLabel());
    final JLabel sharpMaxLabel = new JLabel(getSharpMaxLabel());

    // Create a change listener fot these
    ChangeListener cl = new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            JSlider source = (JSlider) e.getSource();

            if (source == magErrMaxSlider) {
                // Compute max mag error from slider position
                double newMagErrMax = magErrorRangeMin
                        + (magErrorRangeMax - magErrorRangeMin) * (source.getValue() / 100.0);
                magErrMax = newMagErrMax;
                magErrMaxLabel.setText(getMagErrMaxLabel());
            }
            if (source == chi2MaxSlider) {
                // Compute Chi2 max from slider position
                double newChi2Max = chi2RangeMin + (chi2RangeMax - chi2RangeMin) * (source.getValue() / 100.0);
                chi2Max = newChi2Max;
                chi2MaxLabel.setText(getChi2MaxLabel());
            }
            if (source == sharpMinSlider) {
                // Compute sharp min from slider position
                double newSharpMin = sharpRangeMin
                        + (sharpRangeMax - sharpRangeMin) * (source.getValue() / 100.0);
                sharpMin = newSharpMin;
                sharpMinLabel.setText(getSharpMinLabel());
            }
            if (source == sharpMaxSlider) {
                // Compute sharp max from slider position
                double newSharpMax = sharpRangeMin
                        + (sharpRangeMax - sharpRangeMin) * (source.getValue() / 100.0);
                sharpMax = newSharpMax;
                sharpMaxLabel.setText(getSharpMaxLabel());
            }
            cmdPanel.setChart(updateDataAndPlotCmd(allSources));
        }
    };
    magErrMaxSlider.addChangeListener(cl);
    chi2MaxSlider.addChangeListener(cl);
    sharpMinSlider.addChangeListener(cl);
    sharpMaxSlider.addChangeListener(cl);
    // Add a bit of padding to space things out
    magErrMaxSlider.setBorder(new EmptyBorder(5, 5, 5, 5));
    chi2MaxSlider.setBorder(new EmptyBorder(5, 5, 5, 5));
    sharpMinSlider.setBorder(new EmptyBorder(5, 5, 5, 5));
    sharpMaxSlider.setBorder(new EmptyBorder(5, 5, 5, 5));

    // Text field to store distance modulus
    final JTextField distanceModulusField = new JTextField(Double.toString(mu));
    distanceModulusField.setBorder(new EmptyBorder(5, 5, 5, 5));

    Border compound = BorderFactory.createCompoundBorder(new LineBorder(this.getBackground(), 5),
            BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));

    final JButton lfButton = new JButton("Luminosity function for selection");
    lfButton.setBorder(compound);
    lfButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            // Read distance modulus field
            try {
                double mu_new = Double.parseDouble(distanceModulusField.getText());
                mu = mu_new;
            } catch (NullPointerException | NumberFormatException ex) {
                JOptionPane.showMessageDialog(lfButton,
                        "Error parsing the distance modulus: " + ex.getMessage(), "Distance Modulus Error",
                        JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (boxedSources.isEmpty()) {
                JOptionPane.showMessageDialog(lfButton, "No sources are currently selected!", "Selection Error",
                        JOptionPane.ERROR_MESSAGE);
            } else {
                computeAndPlotLuminosityFunction(boxedSources);
            }
        }
    });
    final JButton clearSelectionButton = new JButton("Clear selection");
    clearSelectionButton.setBorder(compound);
    clearSelectionButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            points.clear();
            cmdPanel.setChart(plotCmd());
        }
    });

    JPanel controls = new JPanel(new GridLayout(9, 2));
    controls.setBorder(new EmptyBorder(10, 10, 10, 10));
    controls.add(new JLabel("Magnitude = "));
    controls.add(magComboBox);
    controls.add(new JLabel("Colour 1 = "));
    controls.add(col1ComboBox);
    controls.add(new JLabel("Colour 2 = "));
    controls.add(col2ComboBox);
    controls.add(magErrMaxLabel);
    controls.add(magErrMaxSlider);
    controls.add(chi2MaxLabel);
    controls.add(chi2MaxSlider);
    controls.add(sharpMinLabel);
    controls.add(sharpMinSlider);
    controls.add(sharpMaxLabel);
    controls.add(sharpMaxSlider);
    controls.add(new JLabel("Adopted distance modulus = "));
    controls.add(distanceModulusField);
    controls.add(lfButton);
    controls.add(clearSelectionButton);

    this.setLayout(new BorderLayout());
    this.add(cmdPanel, BorderLayout.CENTER);
    this.add(controls, BorderLayout.SOUTH);

    this.validate();
}

From source file:edu.ku.brc.specify.extras.ViewToSchemaReview.java

/**
 * /*from   w  w  w  .ja v a2  s  .  c  o  m*/
 */
public void checkSchemaAndViews() {

    Hashtable<String, HashSet<String>> viewFieldHash = new Hashtable<String, HashSet<String>>();

    SpecifyAppContextMgr sacm = (SpecifyAppContextMgr) AppContextMgr.getInstance();

    for (ViewIFace view : sacm.getEntirelyAllViews()) {
        //System.err.println(view.getName() + " ----------------------");
        for (AltViewIFace av : view.getAltViews()) {
            ViewDefIFace vd = av.getViewDef();
            if (vd.getType() == ViewType.form) {
                DBTableInfo ti = DBTableIdMgr.getInstance().getByClassName(vd.getClassName());
                if (ti != null) {
                    HashSet<String> tiHash = viewFieldHash.get(ti.getName());
                    if (tiHash == null) {
                        tiHash = new HashSet<String>();
                        viewFieldHash.put(ti.getName(), tiHash);
                    }

                    FormViewDef fvd = (FormViewDef) vd;
                    for (FormRowIFace row : fvd.getRows()) {
                        for (FormCellIFace cell : row.getCells()) {
                            if (cell.getType() == FormCellIFace.CellType.panel) {
                                FormCellPanelIFace panelCell = (FormCellPanelIFace) cell;
                                for (String fieldName : panelCell.getFieldNames()) {
                                    tiHash.add(fieldName);
                                }

                            } else if (cell.getType() == FormCellIFace.CellType.field
                                    || cell.getType() == FormCellIFace.CellType.subview) {
                                String fieldName = cell.getName();
                                if (!cell.isIgnoreSetGet() && !fieldName.equals("this")) {
                                    DBFieldInfo fi = ti.getFieldByName(fieldName);
                                    if (fi != null) {
                                        //System.err.println("Form Field["+fieldName+"] is in schema.");
                                        tiHash.add(fieldName);
                                    } else {
                                        DBRelationshipInfo ri = ti.getRelationshipByName(fieldName);
                                        if (ri == null) {
                                            //System.err.println("Form Field["+fieldName+"] not in table.");
                                        } else {
                                            tiHash.add(fieldName);
                                        }
                                    }
                                } else if (cell instanceof FormCellFieldIFace) {
                                    FormCellFieldIFace fcf = (FormCellFieldIFace) cell;
                                    if (fcf.getUiType() == FormCellFieldIFace.FieldType.plugin) {
                                        String pluginName = fcf.getProperty("name");
                                        if (StringUtils.isNotEmpty(pluginName)) {
                                            checkPluginForNames(fcf, pluginName, tiHash);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    for (DBTableInfo ti : DBTableIdMgr.getInstance().getTables()) {
        int cnt = 0;

        HashSet<String> tiHash = viewFieldHash.get(ti.getName());
        if (tiHash != null) {
            tblTitle2Name.put(ti.getTitle(), ti.getName());

            //System.err.println(ti.getName() + " ----------------------");
            for (DBFieldInfo fi : ti.getFields()) {
                Boolean isInForm = tiHash.contains(fi.getName());
                modelList.add(
                        createRow(ti.getTitle(), fi.getName(), fi.getTitle(), isInForm, fi.isHidden(), cnt++));
            }

            for (DBRelationshipInfo ri : ti.getRelationships()) {
                Boolean isInForm = tiHash.contains(ri.getName());
                modelList.add(
                        createRow(ti.getTitle(), ri.getName(), ri.getTitle(), isInForm, ri.isHidden(), cnt++));
            }
        }
    }

    viewModel = new ViewModel();
    JTable table = new JTable(viewModel);

    sorter = new TableRowSorter<TableModel>(viewModel);
    searchTF = new JAutoCompTextField(20);

    table.setRowSorter(sorter);

    CellConstraints cc = new CellConstraints();
    PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "p,4px,f:p:g,2px,p:g"));
    SearchBox searchBox = new SearchBox(searchTF, null);

    filterCBX = UIHelper.createComboBox(new String[] { "None", "Not On Form, Not Hidden", "On Form, Hidden" });

    PanelBuilder searchPB = new PanelBuilder(new FormLayout("p,2px,p, f:p:g, p,2px,p", "p"));
    searchPB.add(UIHelper.createI18NFormLabel("SEARCH"), cc.xy(1, 1));
    searchPB.add(searchBox, cc.xy(3, 1));
    searchPB.add(UIHelper.createI18NFormLabel("Filter"), cc.xy(5, 1));
    searchPB.add(filterCBX, cc.xy(7, 1));

    JLabel legend = UIHelper.createLabel(
            "<HTML><li><font color=\"red\">Red</font> - Not on form and not hidden</li><li><font color=\"magenta\">Magenta</font> - On the form , but is hidden</li><li>Black - Correct</li>");
    legend.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
    PanelBuilder legPB = new PanelBuilder(new FormLayout("p,f:p:g", "p"));
    legPB.add(legend, cc.xy(1, 1));

    pb.add(searchPB.getPanel(), cc.xy(1, 1));
    pb.add(UIHelper.createScrollPane(table), cc.xy(1, 3));
    pb.add(legPB.getPanel(), cc.xy(1, 5));
    pb.setDefaultDialogBorder();

    sorter.setRowFilter(null);

    searchTF.getDocument().addDocumentListener(new DocumentAdaptor() {
        @Override
        protected void changed(DocumentEvent e) {
            SwingUtilities.invokeLater(new Runnable() {

                /* (non-Javadoc)
                 * @see java.lang.Runnable#run()
                 */
                @Override
                public void run() {
                    if (filterCBX.getSelectedIndex() > 0) {
                        blockCBXUpdate = true;
                        filterCBX.setSelectedIndex(-1);
                        blockCBXUpdate = false;
                    }
                    String text = searchTF.getText();
                    sorter.setRowFilter(text.isEmpty() ? null : RowFilter.regexFilter("^(?i)" + text, 0, 1));
                }
            });
        }
    });

    filterCBX.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    if (!blockCBXUpdate) {
                        RowFilter<TableModel, Integer> filter = null;
                        int inx = filterCBX.getSelectedIndex();
                        if (inx > 0) {
                            filter = filterCBX.getSelectedIndex() == 1 ? new NotOnFormNotHiddenRowFilter()
                                    : new OnFormIsHiddenRowFilter();
                        }
                        sorter.setRowFilter(filter);
                    }
                }
            });
        }
    });

    table.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false));
    table.setDefaultRenderer(Boolean.class, new BiColorBooleanTableCellRenderer());
    table.getColumnModel().getColumn(0).setCellRenderer(new TitleCellFadeRenderer());
    table.getColumnModel().getColumn(3).setCellRenderer(new BiColorTableCellRenderer(true));
    table.getColumnModel().getColumn(2).setCellRenderer(new BiColorTableCellRenderer(false) {
        @SuppressWarnings("unchecked")
        @Override
        public Component getTableCellRendererComponent(JTable tableArg, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JLabel lbl = (JLabel) super.getTableCellRendererComponent(tableArg, value, isSelected, hasFocus,
                    row, column);

            /*if (sorter.getRowFilter() != null)
            {
            System.out.println(" getRowCount:"+sorter.getModel().getRowCount());
            Pair<String, Integer> col1Pair = (Pair<String, Integer>)sorter.getModel().getValueAt(row, 0);
            rowData = modelList.get(col1Pair.second);
                    
            } else
            {
            rowData = modelList.get(row);
            }*/

            //System.out.println(" R2:"+row+"  "+rowData[0]+"/"+rowData[1]+" - "+rowData[3]+"|"+rowData[4]);
            if (value instanceof TableInfo) {
                TableInfo pair = (TableInfo) value;
                Object[] rowData = modelList.get(pair.getSecond());
                lbl.setText(rowData[0].toString());

            } else if (value instanceof Pair<?, ?>) {
                Pair<String, Integer> pair = (Pair<String, Integer>) value;
                Object[] rowData = modelList.get(pair.getSecond());

                boolean isOnForm = rowData[3] instanceof Boolean ? (Boolean) rowData[3]
                        : ((String) rowData[3]).equals("Yes");
                boolean isHidden = rowData[4] instanceof Boolean ? (Boolean) rowData[4]
                        : ((String) rowData[4]).equals("true");

                if (!isOnForm && !isHidden) {
                    lbl.setForeground(Color.RED);

                } else if (isOnForm && isHidden) {
                    lbl.setForeground(Color.MAGENTA);
                } else {
                    lbl.setForeground(Color.BLACK);
                }
                lbl.setText(pair.getFirst());
            } else {
                lbl.setText(value.toString());
            }
            return lbl;
        }

    });

    //UIHelper.makeTableHeadersCentered(table, false);
    UIHelper.calcColumnWidths(table, null);

    //Removing fix all button because fix() method is broken (bug #8087)...

    /*CustomDialog dlg = new CustomDialog((Frame)UIRegistry.getTopWindow(), "", true, CustomDialog.OKCANCELAPPLY, pb.getPanel()) 
    {
    @Override
    protected void applyButtonPressed()
    {
        fix(this);
    }
    };
    dlg.setApplyLabel("Fix All");*/

    CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getTopWindow(), "", true, CustomDialog.OKCANCEL,
            pb.getPanel());

    //... end removing fix all button

    dlg.setVisible(true);

    if (!dlg.isCancelled()) {
        updateSchema();
    }
}