Example usage for java.awt.event ItemListener ItemListener

List of usage examples for java.awt.event ItemListener ItemListener

Introduction

In this page you can find the example usage for java.awt.event ItemListener ItemListener.

Prototype

ItemListener

Source Link

Usage

From source file:org.ohdsi.whiteRabbit.WhiteRabbitMain.java

private JPanel createLocationsPanel() {
    JPanel panel = new JPanel();

    panel.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 0.5;/* ww  w. java2 s . co m*/

    JPanel folderPanel = new JPanel();
    folderPanel.setLayout(new BoxLayout(folderPanel, BoxLayout.X_AXIS));
    folderPanel.setBorder(BorderFactory.createTitledBorder("Working folder"));
    folderField = new JTextField();
    folderField.setText((new File("").getAbsolutePath()));
    folderField.setToolTipText("The folder where all output will be written");
    folderPanel.add(folderField);
    JButton pickButton = new JButton("Pick folder");
    pickButton.setToolTipText("Pick a different working folder");
    folderPanel.add(pickButton);
    pickButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            pickFolder();
        }
    });
    componentsToDisableWhenRunning.add(pickButton);
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 1;
    panel.add(folderPanel, c);

    JPanel sourcePanel = new JPanel();
    sourcePanel.setLayout(new GridLayout(0, 2));
    sourcePanel.setBorder(BorderFactory.createTitledBorder("Source data location"));
    sourcePanel.add(new JLabel("Data type"));
    sourceType = new JComboBox<String>(new String[] { "Delimited text files", "MySQL", "Oracle", "SQL Server",
            "PostgreSQL", "MS Access", "PDW", "Redshift", "Teradata" });
    sourceType.setToolTipText("Select the type of source data available");
    sourceType.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent arg0) {
            sourceIsFiles = arg0.getItem().toString().equals("Delimited text files");
            sourceServerField.setEnabled(!sourceIsFiles);
            sourceUserField.setEnabled(!sourceIsFiles);
            sourcePasswordField.setEnabled(!sourceIsFiles);
            sourceDatabaseField.setEnabled(!sourceIsFiles);
            sourceDelimiterField.setEnabled(sourceIsFiles);
            addAllButton.setEnabled(!sourceIsFiles);

            if (!sourceIsFiles && arg0.getItem().toString().equals("Oracle")) {
                sourceServerField.setToolTipText(
                        "For Oracle servers this field contains the SID, servicename, and optionally the port: '<host>/<sid>', '<host>:<port>/<sid>', '<host>/<service name>', or '<host>:<port>/<service name>'");
                sourceUserField.setToolTipText(
                        "For Oracle servers this field contains the name of the user used to log in");
                sourcePasswordField.setToolTipText(
                        "For Oracle servers this field contains the password corresponding to the user");
                sourceDatabaseField.setToolTipText(
                        "For Oracle servers this field contains the schema (i.e. 'user' in Oracle terms) containing the source tables");
            } else if (!sourceIsFiles && arg0.getItem().toString().equals("PostgreSQL")) {
                sourceServerField.setToolTipText(
                        "For PostgreSQL servers this field contains the host name and database name (<host>/<database>)");
                sourceUserField.setToolTipText("The user used to log in to the server");
                sourcePasswordField.setToolTipText("The password used to log in to the server");
                sourceDatabaseField.setToolTipText(
                        "For PostgreSQL servers this field contains the schema containing the source tables");
            } else if (!sourceIsFiles) {
                sourceServerField
                        .setToolTipText("This field contains the name or IP address of the database server");
                if (arg0.getItem().toString().equals("SQL Server"))
                    sourceUserField.setToolTipText(
                            "The user used to log in to the server. Optionally, the domain can be specified as <domain>/<user> (e.g. 'MyDomain/Joe')");
                else
                    sourceUserField.setToolTipText("The user used to log in to the server");
                sourcePasswordField.setToolTipText("The password used to log in to the server");
                sourceDatabaseField.setToolTipText("The name of the database containing the source tables");
            }
        }
    });
    sourcePanel.add(sourceType);

    sourcePanel.add(new JLabel("Server location"));
    sourceServerField = new JTextField("127.0.0.1");
    sourceServerField.setEnabled(false);
    sourcePanel.add(sourceServerField);
    sourcePanel.add(new JLabel("User name"));
    sourceUserField = new JTextField("");
    sourceUserField.setEnabled(false);
    sourcePanel.add(sourceUserField);
    sourcePanel.add(new JLabel("Password"));
    sourcePasswordField = new JPasswordField("");
    sourcePasswordField.setEnabled(false);
    sourcePanel.add(sourcePasswordField);
    sourcePanel.add(new JLabel("Database name"));
    sourceDatabaseField = new JTextField("");
    sourceDatabaseField.setEnabled(false);
    sourcePanel.add(sourceDatabaseField);

    sourcePanel.add(new JLabel("Delimiter"));
    sourceDelimiterField = new JTextField(",");
    sourceDelimiterField.setToolTipText("The delimiter that separates values. Enter 'tab' for tab.");
    sourcePanel.add(sourceDelimiterField);

    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 1;
    panel.add(sourcePanel, c);

    JPanel testConnectionButtonPanel = new JPanel();
    testConnectionButtonPanel.setLayout(new BoxLayout(testConnectionButtonPanel, BoxLayout.X_AXIS));
    testConnectionButtonPanel.add(Box.createHorizontalGlue());

    JButton testConnectionButton = new JButton("Test connection");
    testConnectionButton.setBackground(new Color(151, 220, 141));
    testConnectionButton.setToolTipText("Test the connection");
    testConnectionButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            testConnection(getSourceDbSettings());
        }
    });
    componentsToDisableWhenRunning.add(testConnectionButton);
    testConnectionButtonPanel.add(testConnectionButton);

    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = 1;
    panel.add(testConnectionButtonPanel, c);

    return panel;
}

From source file:com.piusvelte.taplock.server.TapLockServer.java

private static void initialize() {
    (new File(APP_PATH)).mkdir();
    if (OS == OS_WIN)
        Security.addProvider(new BouncyCastleProvider());
    System.out.println("APP_PATH: " + APP_PATH);
    try {//from   w  ww  .  ja va  2  s  .  c  o m
        sLogFileHandler = new FileHandler(sLog);
    } catch (SecurityException e) {
        writeLog("sLogFileHandler init: " + e.getMessage());
    } catch (IOException e) {
        writeLog("sLogFileHandler init: " + e.getMessage());
    }

    File propertiesFile = new File(sProperties);
    if (!propertiesFile.exists()) {
        try {
            propertiesFile.createNewFile();
        } catch (IOException e) {
            writeLog("propertiesFile.createNewFile: " + e.getMessage());
        }
    }

    Properties prop = new Properties();

    try {
        prop.load(new FileInputStream(sProperties));
        if (prop.isEmpty()) {
            prop.setProperty(sPassphraseKey, sPassphrase);
            prop.setProperty(sDisplaySystemTrayKey, Boolean.toString(sDisplaySystemTray));
            prop.setProperty(sDebuggingKey, Boolean.toString(sDebugging));
            prop.store(new FileOutputStream(sProperties), null);
        } else {
            if (prop.containsKey(sPassphraseKey))
                sPassphrase = prop.getProperty(sPassphraseKey);
            else
                prop.setProperty(sPassphraseKey, sPassphrase);
            if (prop.containsKey(sDisplaySystemTrayKey))
                sDisplaySystemTray = Boolean.parseBoolean(prop.getProperty(sDisplaySystemTrayKey));
            else
                prop.setProperty(sDisplaySystemTrayKey, Boolean.toString(sDisplaySystemTray));
            if (prop.containsKey(sDebuggingKey))
                sDebugging = Boolean.parseBoolean(prop.getProperty(sDebuggingKey));
            else
                prop.setProperty(sDebuggingKey, Boolean.toString(sDebugging));
        }
    } catch (FileNotFoundException e) {
        writeLog("prop load: " + e.getMessage());
    } catch (IOException e) {
        writeLog("prop load: " + e.getMessage());
    }

    if (sLogFileHandler != null) {
        sLogger = Logger.getLogger("TapLock");
        sLogger.setUseParentHandlers(false);
        sLogger.addHandler(sLogFileHandler);
        SimpleFormatter sf = new SimpleFormatter();
        sLogFileHandler.setFormatter(sf);
        writeLog("service starting");
    }

    if (sDisplaySystemTray && SystemTray.isSupported()) {
        final SystemTray systemTray = SystemTray.getSystemTray();
        Image trayIconImg = Toolkit.getDefaultToolkit()
                .getImage(TapLockServer.class.getResource("/systemtrayicon.png"));
        final TrayIcon trayIcon = new TrayIcon(trayIconImg, "Tap Lock");
        trayIcon.setImageAutoSize(true);
        PopupMenu popupMenu = new PopupMenu();
        MenuItem aboutItem = new MenuItem("About");
        CheckboxMenuItem toggleSystemTrayIcon = new CheckboxMenuItem("Display Icon in System Tray");
        toggleSystemTrayIcon.setState(sDisplaySystemTray);
        CheckboxMenuItem toggleDebugging = new CheckboxMenuItem("Debugging");
        toggleDebugging.setState(sDebugging);
        MenuItem shutdownItem = new MenuItem("Shutdown Tap Lock Server");
        popupMenu.add(aboutItem);
        popupMenu.add(toggleSystemTrayIcon);
        if (OS == OS_WIN) {
            MenuItem setPasswordItem = new MenuItem("Set password");
            popupMenu.add(setPasswordItem);
            setPasswordItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JPanel panel = new JPanel();
                    JLabel label = new JLabel("Enter your Windows account password:");
                    JPasswordField passField = new JPasswordField(32);
                    panel.add(label);
                    panel.add(passField);
                    String[] options = new String[] { "OK", "Cancel" };
                    int option = JOptionPane.showOptionDialog(null, panel, "Tap Lock", JOptionPane.NO_OPTION,
                            JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
                    if (option == 0) {
                        String password = encryptString(new String(passField.getPassword()));
                        if (password != null) {
                            Properties prop = new Properties();
                            try {
                                prop.load(new FileInputStream(sProperties));
                                prop.setProperty(sPasswordKey, password);
                                prop.store(new FileOutputStream(sProperties), null);
                            } catch (FileNotFoundException e1) {
                                writeLog("prop load: " + e1.getMessage());
                            } catch (IOException e1) {
                                writeLog("prop load: " + e1.getMessage());
                            }
                        }
                    }
                }
            });
        }
        popupMenu.add(toggleDebugging);
        popupMenu.add(shutdownItem);
        trayIcon.setPopupMenu(popupMenu);
        try {
            systemTray.add(trayIcon);
        } catch (AWTException e) {
            writeLog("systemTray.add: " + e.getMessage());
        }
        aboutItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String newline = System.getProperty("line.separator");
                newline += newline;
                JOptionPane.showMessageDialog(null, "Tap Lock" + newline + "Copyright (c) 2012 Bryan Emmanuel"
                        + newline
                        + "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version."
                        + newline
                        + "This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details."
                        + newline
                        + "You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>."
                        + newline + "Bryan Emmanuel piusvelte@gmail.com");
            }
        });
        toggleSystemTrayIcon.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                setTrayIconDisplay(e.getStateChange() == ItemEvent.SELECTED);
                if (!sDisplaySystemTray)
                    systemTray.remove(trayIcon);
            }
        });
        toggleDebugging.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                setDebugging(e.getStateChange() == ItemEvent.SELECTED);
            }
        });
        shutdownItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                shutdown();
            }
        });
    }
    synchronized (sConnectionThreadLock) {
        (sConnectionThread = new ConnectionThread()).start();
    }
}

From source file:com.eviware.soapui.impl.wsdl.monitor.SoapMonitor.java

private JPanel buildFilterBar() {
    requestFilterModel = new DefaultComboBoxModel(new String[] { ALL_FILTER_OPTION });
    targetHostFilterModel = new DefaultComboBoxModel(new String[] { ALL_FILTER_OPTION });
    Dimension comboBoxSize = new Dimension(90, 18);
    requestHostFilterCombo = UISupport.setFixedSize(new JComboBox(requestFilterModel), comboBoxSize);

    // toolbar.addFixed( new JLabel( "<html><b>Filter:</b></html>"));
    // toolbar.addUnrelatedGap();

    ButtonBarBuilder toolbar = new ButtonBarBuilder();

    toolbar.addFixed(new JLabel("Request Host"));
    toolbar.addRelatedGap();/*from  www  .j a  v  a 2 s .c  o m*/
    toolbar.addFixed(requestHostFilterCombo);
    toolbar.addUnrelatedGap();

    requestHostFilterCombo.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            int ix = requestHostFilterCombo.getSelectedIndex();
            if (ix == -1)
                return;

            requestHostFilter.setAcceptNull(ix == 0);

            if (ix == 0)
                requestHostFilter.setPattern(".*", 0);
            else
                requestHostFilter.setPattern(requestHostFilterCombo.getSelectedItem().toString(), 0);

            updateRowCountLabel();
        }
    });

    toolbar.addFixed(new JLabel("Target Host"));
    toolbar.addRelatedGap();
    targetHostFilterCombo = UISupport.setFixedSize(new JComboBox(targetHostFilterModel), comboBoxSize);
    toolbar.addFixed(targetHostFilterCombo);
    toolbar.addUnrelatedGap();

    targetHostFilterCombo.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            int ix = targetHostFilterCombo.getSelectedIndex();
            if (ix == -1)
                return;

            targetHostFilter.setAcceptNull(ix == 0);

            if (ix == 0)
                targetHostFilter.setPattern(".*", 0);
            else
                targetHostFilter.setPattern(targetHostFilterCombo.getSelectedItem().toString(), 0);

            updateRowCountLabel();
        }
    });

    String[] interfaceNames = ModelSupport.getNames(new String[] { ALL_FILTER_OPTION },
            ModelSupport.getChildren(getProject(), WsdlInterface.class));

    toolbar.addFixed(new JLabel("Interface"));
    toolbar.addRelatedGap();
    interfaceFilterCombo = UISupport.setFixedSize(new JComboBox(interfaceNames), comboBoxSize);
    toolbar.addFixed(interfaceFilterCombo);
    toolbar.addUnrelatedGap();

    operationFilterModel = new DefaultComboBoxModel(new String[] { ALL_FILTER_OPTION });
    interfaceFilterCombo.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            String item = (String) interfaceFilterCombo.getSelectedItem();
            operationFilterModel.removeAllElements();

            if (item == null || getProject().getInterfaceByName(item) == null) {
                operationFilterModel.addElement(ALL_FILTER_OPTION);
                interfaceFilter.setPattern(".*", 0);
            } else if (getProject().getInterfaceByName(item) != null) {
                WsdlInterface iface = (WsdlInterface) getProject().getInterfaceByName(item);
                String[] operationNames = ModelSupport.getNames(new String[] { ALL_FILTER_OPTION },
                        iface.getOperationList());
                for (String s : operationNames)
                    operationFilterModel.addElement(s);

                interfaceFilter.setPattern(iface.getName(), 0);
            }
        }
    });

    toolbar.addFixed(new JLabel("Operation"));
    toolbar.addRelatedGap();
    operationFilterCombo = UISupport.setFixedSize(new JComboBox(operationFilterModel), comboBoxSize);
    toolbar.addFixed(operationFilterCombo);

    operationFilterCombo.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            int ix = operationFilterCombo.getSelectedIndex();
            if (ix == -1) {
                operationFilter.setPattern(".*", 0);
                updateRowCountLabel();
                return;
            }

            operationFilter.setAcceptNull(ix == 0);

            if (ix == 0)
                operationFilter.setPattern(".*", 0);
            else
                operationFilter.setPattern(operationFilterCombo.getSelectedItem().toString(), 0);

            updateRowCountLabel();
        }
    });

    toolbar.setBorder(BorderFactory.createEmptyBorder(3, 2, 3, 0));
    return toolbar.getPanel();
}

From source file:com.funambol.foundation.admin.PIMSyncSourceConfigPanel.java

/**
 * Creates the panel's components and layout.
 * @todo adjust layout/* w  w w .  j  a va2s  . c o m*/
 */
private void init() {
    // set layout
    this.setLayout(null);
    // set properties of label, position and border
    //  referred to the title of the panel
    titledBorder = new TitledBorder("");
    panelName.setFont(titlePanelFont);
    panelName.setText(getPanelName());
    panelName.setBounds(new Rectangle(14, 5, 316, 28));
    panelName.setAlignmentX(SwingConstants.CENTER);
    panelName.setBorder(titledBorder);

    final int LABEL_X = 14;
    final int VALUE_X = 170;
    int y = 60;
    final int GAP_X = 150;
    final int GAP_Y = 30;

    sourceUriLabel.setText("Source URI: ");
    sourceUriLabel.setFont(defaultFont);
    sourceUriLabel.setBounds(new Rectangle(LABEL_X, y, 150, 18));
    sourceUriValue.setFont(defaultFont);
    sourceUriValue.setBounds(new Rectangle(VALUE_X, y, 350, 18));

    y += GAP_Y; // New line

    nameLabel.setText("Name: ");
    nameLabel.setFont(defaultFont);
    nameLabel.setBounds(new Rectangle(LABEL_X, y, 150, 18));
    nameValue.setFont(defaultFont);
    nameValue.setBounds(new Rectangle(VALUE_X, y, 350, 18));
    y += GAP_Y; // New line

    typeLabel.setText("Type: ");
    typeLabel.setFont(defaultFont);
    typeLabel.setBounds(new Rectangle(LABEL_X, y, 150, 18));
    typeCombo.setFont(defaultFont);
    typeCombo.setBounds(new Rectangle(VALUE_X, y, 350, 18));

    // What happens when the Type value is changed?
    typeCombo.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (isSIFSelected()) {
                encoding.setSelected(true); // SIFs always encoded
                encoding.setEnabled(false);
            } else {
                encryption.setSelected(false);
                encoding.setSelected(false);
                encoding.setEnabled(true);
            }
        }
    });

    y += GAP_Y; // New line
    int x = LABEL_X;

    y = addExtraComponents(x, y, GAP_X, GAP_Y); // Add other components, if needed

    encryption.setText("Encrypt data");
    encryption.setFont(defaultFont);
    encryption.setSelected(false);
    encryption.setBounds(x, y, 150, 25);

    // What happens if the encryption is enabled?
    encryption.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == e.SELECTED) {
                encoding.setSelected(true); // Encryption implies encoding
                encoding.setEnabled(false);
            }
            if (e.getStateChange() == e.DESELECTED) {
                if (!isSIFSelected()) {
                    encoding.setEnabled(true);
                }
            }
        }
    });

    y += GAP_Y; // New line

    encoding.setText("Encode data in Base 64");
    encoding.setFont(defaultFont);
    encoding.setSelected(false);
    encoding.setBounds(x, y, 150, 25);

    y += GAP_Y; // New line
    y += GAP_Y; // New line

    confirmButton.setFont(defaultFont);
    confirmButton.setText("Add");
    confirmButton.setBounds(VALUE_X, y, 70, 25);

    // What happens when the confirmButton is pressed?
    confirmButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            try {
                validateValues();
                getValues();
                if (getState() == STATE_INSERT) {
                    PIMSyncSourceConfigPanel.this.actionPerformed(new ActionEvent(PIMSyncSourceConfigPanel.this,
                            ACTION_EVENT_INSERT, event.getActionCommand()));
                } else {
                    PIMSyncSourceConfigPanel.this.actionPerformed(new ActionEvent(PIMSyncSourceConfigPanel.this,
                            ACTION_EVENT_UPDATE, event.getActionCommand()));
                }
            } catch (Exception e) {
                notifyError(new AdminException(e.getMessage(), e));
            }
        }
    });

    // Adds all components to the panel
    this.add(panelName, null);
    this.add(nameLabel, null);
    this.add(sourceUriLabel, null);
    this.add(sourceUriValue, null);
    this.add(nameValue, null);
    this.add(typeLabel, null);
    this.add(typeCombo, null);
    this.add(encryption, null);
    this.add(encoding, null);
    this.add(confirmButton, null);
}

From source file:net.sf.vfsjfilechooser.accessories.connection.ConnectionDialog.java

private void initListeners() {
    this.portTextField.addKeyListener(new KeyAdapter() {
        @Override/*from   w w  w . j av a2 s.c o m*/
        public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();

            if (!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
                getToolkit().beep();
                e.consume();
            } else {
                setPortTextFieldDirty(true);
            }
        }
    });

    this.portTextField.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent e) {
            JFormattedTextField f = (JFormattedTextField) e.getSource();
            String text = f.getText();

            if (text.length() == 0) {
                f.setValue(null);
            }

            try {
                f.commitEdit();
            } catch (ParseException exc) {
            }
        }
    });

    this.cancelButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (currentWorker != null) {
                if (currentWorker.isAlive()) {
                    currentWorker.interrupt();
                    setCursor(Cursor.getDefaultCursor());
                }
            }

            setVisible(false);
        }
    });

    this.connectButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            currentWorker = new Thread() {
                @Override
                public void run() {
                    StringBuilder error = new StringBuilder();
                    FileObject fo = null;

                    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                    try {
                        String m_username = usernameTextField.getText();
                        String m_defaultRemotePath = defaultRemotePathTextField.getText();
                        char[] m_password = passwordTextField.getPassword();
                        String m_hostname = hostnameTextField.getText();
                        String m_protocol = protocolList.getSelectedItem().toString();

                        int m_port = -1;

                        if (portTextField.isEditValid() && (portTextField.getValue() != null)) {
                            String s = portTextField.getValue().toString();
                            m_port = Integer.valueOf(s);
                        }

                        Builder credentialsBuilder = Credentials.newBuilder(m_hostname)
                                .defaultRemotePath(m_defaultRemotePath).username(m_username)
                                .password(m_password).protocol(m_protocol).port(m_port);

                        Credentials credentials = credentialsBuilder.build();

                        String uri = credentials.toFileObjectURL();

                        if (isInterrupted()) {
                            setPortTextFieldDirty(false);

                            return;
                        }

                        fo = VFSUtils.resolveFileObject(uri);

                        if ((fo != null) && !fo.exists()) {
                            fo = null;
                        }
                    } catch (Exception err) {
                        error.append(err.getMessage());
                        setCursor(Cursor.getDefaultCursor());
                    }

                    if ((error.length() > 0) || (fo == null)) {
                        error.delete(0, error.length());
                        error.append("Failed to connect!");
                        error.append("\n");
                        error.append("Please check parameters and try again.");

                        JOptionPane.showMessageDialog(ConnectionDialog.this, error, "Error",
                                JOptionPane.ERROR_MESSAGE);
                        setCursor(Cursor.getDefaultCursor());

                        return;
                    }

                    if (isInterrupted()) {
                        return;
                    }

                    fileChooser.setCurrentDirectory(fo);

                    setCursor(Cursor.getDefaultCursor());

                    resetFields();

                    if (bookmarksDialog != null) {
                        String bTitle = fo.getName().getBaseName();

                        if (bTitle.trim().equals("")) {
                            bTitle = fo.getName().toString();
                        }

                        String bURL = fo.getName().getURI();
                        bookmarksDialog.getBookmarks().add(new TitledURLEntry(bTitle, bURL));
                        bookmarksDialog.getBookmarks().save();
                    }

                    setVisible(false);
                }
            };

            currentWorker.setPriority(Thread.MIN_PRIORITY);
            currentWorker.start();
        }
    });

    // add the usual right click popup menu(copy, paste, etc.)
    PopupHandler.installDefaultMouseListener(hostnameTextField);
    PopupHandler.installDefaultMouseListener(portTextField);
    PopupHandler.installDefaultMouseListener(usernameTextField);
    PopupHandler.installDefaultMouseListener(passwordTextField);
    PopupHandler.installDefaultMouseListener(defaultRemotePathTextField);

    this.protocolList.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                selectPortNumber();
            }
        }
    });

    this.protocolList.setSelectedItem(Protocol.FTP);
}

From source file:com.google.code.facebook.graph.sna.applet.FacebookGraphApplet.java

/**
 * create an instance of a simple graph with controls to
 * demo the zoom features./*from w ww .  j a  va  2 s . c  o  m*/
 * 
 */
@Override
public void init() {
    super.init();
    // create a simple graph for the demo
    fetchUserGraph();
    final Collection<? extends Entity<FieldEnum, ConnectionEnum>> vertices = graph.getVertices();

    // a Map for the labels
    Map<Entity<FieldEnum, ConnectionEnum>, String> map = new HashMap<Entity<FieldEnum, ConnectionEnum>, String>();
    Iterator<? extends Entity<FieldEnum, ConnectionEnum>> iterator = vertices.iterator();
    while (iterator.hasNext()) {
        Entity<FieldEnum, ConnectionEnum> entity = iterator.next();
        map.put(entity, entity.getLabel());
    }

    FRLayout<Entity<FieldEnum, ConnectionEnum>, EdgeAdapter<ConnectionEnum>> layout = new FRLayout<Entity<FieldEnum, ConnectionEnum>, EdgeAdapter<ConnectionEnum>>(
            (Graph<Entity<FieldEnum, ConnectionEnum>, EdgeAdapter<ConnectionEnum>>) graph);
    layout.setMaxIterations(100);
    vv = new VisualizationViewer<Entity<FieldEnum, ConnectionEnum>, EdgeAdapter<ConnectionEnum>>(layout,
            new Dimension(2000, 2000));

    Transformer<Entity<FieldEnum, ConnectionEnum>, Paint> vpf = new PickableVertexPaintTransformer<Entity<FieldEnum, ConnectionEnum>>(
            vv.getPickedVertexState(), Color.white, Color.yellow);
    vv.getRenderContext().setVertexFillPaintTransformer(vpf);
    vv.getRenderContext().setEdgeDrawPaintTransformer(
            new PickableEdgePaintTransformer<EdgeAdapter<ConnectionEnum>>(vv.getPickedEdgeState(), Color.black,
                    Color.cyan));

    vv.setBackground(Color.white);

    // a Map for the Icons
    final Map<Entity<FieldEnum, ConnectionEnum>, Icon> iconMap = new HashMap<Entity<FieldEnum, ConnectionEnum>, Icon>();
    new Thread(new Runnable() {
        public void run() {
            Iterator<? extends Entity<FieldEnum, ConnectionEnum>> iterator = vertices.iterator();
            while (iterator.hasNext()) {
                try {
                    Entity<FieldEnum, ConnectionEnum> entity = iterator.next();
                    //                     Icon icon = 
                    //                        new LayeredIcon(new ImageIcon("http://facebookgraph.appspot.com/proxy?url=" + entity.getPicture(PictureType.SQUARE), "Profile Picture").getImage());
                    //                       iconMap.put(entity, icon);

                    Image image = getImageFromEntity(entity);
                    if (image != null && image.getWidth(null) > 0 && image.getHeight(null) > 0) {
                        Icon icon = new LayeredIcon(image);
                        iconMap.put(entity, icon);
                        if ((iconMap.size() % 5) == 0) {
                            vv.repaint();
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            vv.repaint();
        }

    }).start();

    final Transformer<Entity<FieldEnum, ConnectionEnum>, String> vertexStringerImpl = new VertexStringerImpl<Entity<FieldEnum, ConnectionEnum>>(
            map);
    Transformer<EdgeAdapter<ConnectionEnum>, String> edgeStringerImpl = new Transformer<EdgeAdapter<ConnectionEnum>, String>() {
        public String transform(EdgeAdapter<ConnectionEnum> edge) {
            return edge.toString();
        }
    };
    vv.getRenderContext().setEdgeLabelTransformer(edgeStringerImpl);
    vv.getRenderContext().setVertexLabelTransformer(vertexStringerImpl);
    vv.getRenderContext().setVertexLabelRenderer(new DefaultVertexLabelRenderer(Color.cyan));
    vv.getRenderContext().setEdgeLabelRenderer(new DefaultEdgeLabelRenderer(Color.cyan));

    // features on and off. For a real application, use VertexIconAndShapeFunction instead.
    final VertexIconShapeTransformer<Entity<FieldEnum, ConnectionEnum>> vertexImageShapeFunction = new VertexIconShapeTransformer<Entity<FieldEnum, ConnectionEnum>>(
            new EllipseVertexShapeTransformer<Entity<FieldEnum, ConnectionEnum>>());

    final DefaultVertexIconTransformer<Entity<FieldEnum, ConnectionEnum>> vertexIconFunction = new DefaultVertexIconTransformer<Entity<FieldEnum, ConnectionEnum>>();

    vertexImageShapeFunction.setIconMap(iconMap);
    vertexIconFunction.setIconMap(iconMap);

    vv.getRenderContext().setVertexShapeTransformer(vertexImageShapeFunction);
    vv.getRenderContext().setVertexIconTransformer(vertexIconFunction);

    // Get the pickedState and add a listener that will decorate the
    // Vertex images with a checkmark icon when they are picked
    PickedState<Entity<FieldEnum, ConnectionEnum>> ps = vv.getPickedVertexState();
    ps.addItemListener(new PickWithIconListener(vertexIconFunction));

    // add a listener for ToolTips
    vv.setVertexToolTipTransformer(new Transformer<Entity<FieldEnum, ConnectionEnum>, String>() {
        @Override
        public String transform(Entity<FieldEnum, ConnectionEnum> entity) {
            return entity.getDescription();
        }
    });

    Container content = getContentPane();
    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
    content.add(panel);

    final DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse();
    vv.setGraphMouse(graphMouse);

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JComboBox modeBox = graphMouse.getModeComboBox();
    JPanel modePanel = new JPanel();
    modePanel.setBorder(BorderFactory.createTitledBorder("Mouse Mode"));
    modePanel.add(modeBox);

    JPanel scaleGrid = new JPanel(new GridLayout(1, 0));
    scaleGrid.setBorder(BorderFactory.createTitledBorder("Zoom"));
    JPanel controls = new JPanel();
    scaleGrid.add(plus);
    scaleGrid.add(minus);
    controls.add(scaleGrid);

    controls.add(modePanel);
    content.add(controls, BorderLayout.SOUTH);

    this.viewSupport = new MagnifyImageLensSupport<Entity<FieldEnum, ConnectionEnum>, EdgeAdapter<ConnectionEnum>>(
            vv);
    //           new ViewLensSupport<Number,Number>(vv, new HyperbolicShapeTransformer(vv, 
    //              vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW)), 
    //                new ModalLensGraphMouse());

    this.modelSupport = new LayoutLensSupport<Entity<FieldEnum, ConnectionEnum>, EdgeAdapter<ConnectionEnum>>(
            vv);

    graphMouse.addItemListener(modelSupport.getGraphMouse().getModeListener());
    graphMouse.addItemListener(viewSupport.getGraphMouse().getModeListener());

    ButtonGroup radio = new ButtonGroup();
    JRadioButton none = new JRadioButton("None");
    none.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (viewSupport != null) {
                viewSupport.deactivate();
            }
            if (modelSupport != null) {
                modelSupport.deactivate();
            }
        }
    });
    none.setSelected(true);

    JRadioButton hyperView = new JRadioButton("View");
    hyperView.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            viewSupport.activate(e.getStateChange() == ItemEvent.SELECTED);
        }
    });

    JRadioButton hyperModel = new JRadioButton("Layout");
    hyperModel.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            modelSupport.activate(e.getStateChange() == ItemEvent.SELECTED);
        }
    });
    radio.add(none);
    radio.add(hyperView);
    radio.add(hyperModel);

    JMenuBar menubar = new JMenuBar();
    JMenu modeMenu = graphMouse.getModeMenu();
    menubar.add(modeMenu);

    JPanel lensPanel = new JPanel(new GridLayout(2, 0));
    lensPanel.setBorder(BorderFactory.createTitledBorder("Lens"));
    lensPanel.add(none);
    lensPanel.add(hyperView);
    lensPanel.add(hyperModel);
    controls.add(lensPanel);
}

From source file:br.edu.unifei.mestrado.view.GraphPartitioningVisualization.java

private void createView(final int partitions) {

    clusterer = new PartitionClusterer(partitions);

    final Graph<NodeWrapper, EdgeWrapper> graph = getGraph();

    // Create a simple layout frame
    // specify the Fruchterman-Rheingold layout algorithm
    layout = new AggregateLayout<NodeWrapper, EdgeWrapper>(new FRLayout<NodeWrapper, EdgeWrapper>(graph));

    vv = new VisualizationViewer<NodeWrapper, EdgeWrapper>(layout);
    vv.setBackground(Color.white);

    if (vertexLabelTransformer == null) {
        vertexLabelTransformer = new Transformer<NodeWrapper, String>() {
            @Override/* w  ww. ja  v  a 2 s .co m*/
            public String transform(NodeWrapper v) {
                // TODO: voltar o D quando necessrio
                return "V" + v.getId() + ":" + v.getWeight();// + ":" +
                // v.getD();
            }
        };
    }
    vv.getRenderContext().setVertexLabelTransformer(vertexLabelTransformer);

    // MapTransformer.<NodeWrapper, String>
    // getInstance(LazyMap.<NodeWrapper, String> decorate(
    // new HashMap<NodeWrapper, String>(), new
    // ToStringLabeller<NodeWrapper>())));
    vv.getRenderContext().setEdgeLabelTransformer(edgeLabelTransformer);

    // UTIL: Alguma coisa, talvez o LazyMap no estava repintando a aresta
    // com o peso alterado

    // MapTransformer.<EdgeWrapper, String>
    // getInstance(LazyMap.<EdgeWrapper, String> decorate(
    // new HashMap<EdgeWrapper, String>(), new
    // ToStringLabeller<EdgeWrapper>() {
    // @Override
    // public String transform(EdgeWrapper v) {
    // logger.warn("A:" + v.getId() + ":" + v.getWeight());
    // return "A:" + v.getId() + ":" + v.getWeight();
    // }
    // })));
    // Tell the renderer to use our own customized color rendering

    vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.Line<NodeWrapper, EdgeWrapper>());

    vv.getRenderContext().setVertexShapeTransformer(vertexShapeTransformer);
    vv.getRenderContext().setVertexFillPaintTransformer(vertexFillPaintTransformer);
    vv.getRenderContext().setVertexDrawPaintTransformer(vertexDrawPaintTransformer);
    vv.getRenderContext().setVertexStrokeTransformer(vertexStrokeTransformer);

    vv.getRenderContext().setEdgeDrawPaintTransformer(new Transformer<EdgeWrapper, Paint>() {

        // UTIL: Define as cores das arestas
        @Override
        public Paint transform(EdgeWrapper linkToProcess) {
            // if para mostrar arestas com as duas pontas no mesmo vertices
            if (linkToProcess.getStartNode().getId() == linkToProcess.getEndNode().getId()) {
                return Color.red;
            }
            Set<NodeWrapper> nodes = vv.getPickedVertexState().getPicked();
            for (NodeWrapper node : nodes) {
                for (EdgeWrapper link : node.getEdges()) {
                    if (link.getId() == linkToProcess.getId()) {
                        return Color.orange;
                    }
                }
            }
            if (linkToProcess.isEdgeOnCut()) {
                return Color.green;
            }
            return Color.blue;
        }
    });

    // MapTransformer.<EdgeWrapper, Paint> getInstance(edgePaints));

    vv.getRenderContext().setEdgeStrokeTransformer(new Transformer<EdgeWrapper, Stroke>() {
        protected final Stroke THIN = new BasicStroke(1);
        // protected final Stroke THICK = new BasicStroke(2);
        protected final Stroke STRONG_THICK = new BasicStroke(3);

        public Stroke transform(EdgeWrapper e) {
            // if para mostrar arestas com as duas pontas no mesmo vertices
            if (e.getStartNode().getId() == e.getEndNode().getId()) {
                return STRONG_THICK;
            }

            // Paint c = edgePaints.get(e);
            // if (c == Color.red)
            return THIN;
            // else
            // return THIN;
        }
    });

    DefaultModalGraphMouse gm = new DefaultModalGraphMouse();
    vv.setGraphMouse(gm);

    groupVertices = new JToggleButton("Group Clusters");
    groupVertices.setSelected(true);

    groupVertices.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            clusterAndRecolor(layout, e.getStateChange() == ItemEvent.SELECTED,
                    getGroupCircleVertices().isSelected());
            vv.repaint();
        }
    });

    clusterAndRecolor(layout, groupVertices.isSelected(), getGroupCircleVertices().isSelected());

    Container content = getContentPane();
    content.add(new GraphZoomScrollPane(vv));
    JPanel south = new JPanel(new GridLayout(1, 4));
    JPanel grid1 = new JPanel(new GridLayout(2, 1));
    grid1.add(groupVertices);
    grid1.add(getGroupCircleVertices());
    south.add(grid1);

    final ScalingControl scaler = new CrossoverScalingControl();
    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JPanel grid2 = new JPanel(new GridLayout(2, 1));
    grid2.setBorder(BorderFactory.createTitledBorder("Scale"));
    south.add(grid2);
    grid2.add(plus);
    grid2.add(minus);
    JPanel grid3 = new JPanel(new GridLayout(1, 2));
    south.add(grid3);
    grid3.add(getIterationLabel());
    grid3.add(getCutLabel());

    JPanel p = new JPanel();
    p.setBorder(BorderFactory.createTitledBorder("Mouse Mode"));
    p.add(gm.getModeComboBox());
    south.add(p);
    content.add(south, BorderLayout.SOUTH);
    vv.repaint();
}

From source file:com.googlecode.vfsjfilechooser2.accessories.connection.ConnectionDialog.java

private void initListeners() {
    this.portTextField.addKeyListener(new KeyAdapter() {
        @Override/*from   ww  w. j a  v a 2s  .  c  om*/
        public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();

            if (!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
                getToolkit().beep();
                e.consume();
            } else {
                setPortTextFieldDirty(true);
            }
        }
    });

    this.portTextField.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent e) {
            JFormattedTextField f = (JFormattedTextField) e.getSource();
            String text = f.getText();

            if (text.length() == 0) {
                f.setValue(null);
            }

            try {
                f.commitEdit();
            } catch (ParseException exc) {
            }
        }
    });

    this.cancelButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (currentWorker != null) {
                if (currentWorker.isAlive()) {
                    currentWorker.interrupt();
                    setCursor(Cursor.getDefaultCursor());
                }
            }

            setVisible(false);
        }
    });

    this.connectButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            currentWorker = new Thread() {
                @Override
                public void run() {
                    StringBuilder error = new StringBuilder();
                    FileObject fo = null;

                    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                    try {
                        String m_username = usernameTextField.getText();
                        String m_defaultRemotePath = defaultRemotePathTextField.getText();
                        char[] m_password = passwordTextField.getPassword();
                        String m_hostname = hostnameTextField.getText();
                        String m_protocol = protocolList.getSelectedItem().toString();

                        int m_port = -1;

                        if (portTextField.isEditValid() && (portTextField.getValue() != null)) {
                            String s = portTextField.getValue().toString();
                            m_port = Integer.valueOf(s);
                        }

                        Builder credentialsBuilder = Credentials.newBuilder(m_hostname)
                                .defaultRemotePath(m_defaultRemotePath).username(m_username)
                                .password(m_password).protocol(m_protocol).port(m_port);

                        Credentials credentials = credentialsBuilder.build();

                        String uri = credentials.toFileObjectURL();

                        if (isInterrupted()) {
                            setPortTextFieldDirty(false);

                            return;
                        }

                        fo = VFSUtils.resolveFileObject(uri);

                        if ((fo != null) && !fo.exists()) {
                            fo = null;
                        }
                    } catch (Exception err) {
                        error.append(err.getMessage());
                        setCursor(Cursor.getDefaultCursor());
                    }

                    if ((error.length() > 0) || (fo == null)) {
                        error.delete(0, error.length());
                        error.append("Failed to connect!");
                        error.append("\n");
                        error.append("Please check parameters and try again.");

                        JOptionPane.showMessageDialog(ConnectionDialog.this, error, "Error",
                                JOptionPane.ERROR_MESSAGE);
                        setCursor(Cursor.getDefaultCursor());

                        return;
                    }

                    if (isInterrupted()) {
                        return;
                    }

                    fileChooser.setCurrentDirectoryObject(fo);

                    setCursor(Cursor.getDefaultCursor());

                    resetFields();

                    if (bookmarksDialog != null) {
                        String bTitle = fo.getName().getBaseName();

                        if (bTitle.trim().equals("")) {
                            bTitle = fo.getName().toString();
                        }

                        String bURL = fo.getName().getURI();
                        bookmarksDialog.getBookmarks().add(new TitledURLEntry(bTitle, bURL));
                        bookmarksDialog.getBookmarks().save();
                    }

                    setVisible(false);
                }
            };

            currentWorker.setPriority(Thread.MIN_PRIORITY);
            currentWorker.start();
        }
    });

    // add the usual right click popup menu(copy, paste, etc.)
    PopupHandler.installDefaultMouseListener(hostnameTextField);
    PopupHandler.installDefaultMouseListener(portTextField);
    PopupHandler.installDefaultMouseListener(usernameTextField);
    PopupHandler.installDefaultMouseListener(passwordTextField);
    PopupHandler.installDefaultMouseListener(defaultRemotePathTextField);

    this.protocolList.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                selectPortNumber();
            }
        }
    });

    this.protocolList.setSelectedItem(Protocol.FTP);
}

From source file:sim.util.media.chart.BoxPlotGenerator.java

protected void buildGlobalAttributes(LabelledList list) {
    // create the chart
    ((CategoryPlot) (chart.getPlot())).setRangeGridlinesVisible(false);
    ((CategoryPlot) (chart.getPlot())).setRangeGridlinePaint(new Color(200, 200, 200));

    xLabel = new PropertyField() {
        public String newValue(String newValue) {
            setXAxisLabel(newValue);//  w  ww .  j a  v a2  s.c  om
            getChartPanel().repaint();
            return newValue;
        }
    };
    xLabel.setValue(getXAxisLabel());

    list.add(new JLabel("X Label"), xLabel);

    yLabel = new PropertyField() {
        public String newValue(String newValue) {
            setYAxisLabel(newValue);
            getChartPanel().repaint();
            return newValue;
        }
    };
    yLabel.setValue(getYAxisLabel());

    list.add(new JLabel("Y Label"), yLabel);

    yLog = new JCheckBox();
    yLog.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            if (yLog.isSelected()) {
                LogarithmicAxis logAxis = new LogarithmicAxis(yLabel.getValue());
                logAxis.setStrictValuesFlag(false);
                ((CategoryPlot) (chart.getPlot())).setRangeAxis(logAxis);
            } else
                ((CategoryPlot) (chart.getPlot())).setRangeAxis(new NumberAxis(yLabel.getValue()));
        }
    });

    list.add(new JLabel("Y Log Axis"), yLog);

    final JCheckBox ygridlines = new JCheckBox();
    ygridlines.setSelected(false);
    ItemListener il = new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                ((CategoryPlot) (chart.getPlot())).setRangeGridlinesVisible(true);
            } else {
                ((CategoryPlot) (chart.getPlot())).setRangeGridlinesVisible(false);
            }
        }
    };
    ygridlines.addItemListener(il);

    // JFreeChart's Box Plots look awful when wide because the mean
    // circle is based on the width of the bar to the exclusion of all
    // else.  So I've restricted the width to be no more than 0.4, and 0.1
    // is the suggested default.

    final double INITIAL_WIDTH = 0.1;
    final double MAXIMUM_RATIONAL_WIDTH = 0.4;

    maximumWidthField = new NumberTextField(INITIAL_WIDTH, 2.0, 0) {
        public double newValue(double newValue) {
            if (newValue <= 0.0 || newValue > MAXIMUM_RATIONAL_WIDTH)
                newValue = currentValue;
            ((BoxAndWhiskerRenderer) (((CategoryPlot) (chart.getPlot())).getRenderer()))
                    .setMaximumBarWidth(newValue);
            //update();
            return newValue;
        }
    };
    list.addLabelled("Max Width", maximumWidthField);

    Box box = Box.createHorizontalBox();
    box.add(new JLabel(" Y"));
    box.add(ygridlines);
    box.add(Box.createGlue());
    list.add(new JLabel("Y Grid Lines"), ygridlines);

    mean = new JCheckBox();
    mean.setSelected(true);
    il = new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            BoxAndWhiskerRenderer renderer = ((BoxAndWhiskerRenderer) ((CategoryPlot) (chart.getPlot()))
                    .getRenderer());
            renderer.setMeanVisible(mean.isSelected());
        }
    };
    mean.addItemListener(il);

    median = new JCheckBox();
    median.setSelected(true);
    il = new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            BoxAndWhiskerRenderer renderer = ((BoxAndWhiskerRenderer) ((CategoryPlot) (chart.getPlot()))
                    .getRenderer());
            renderer.setMedianVisible(median.isSelected());
        }
    };
    median.addItemListener(il);

    list.add(new JLabel("Mean"), mean);
    list.add(new JLabel("Median"), median);

    final JCheckBox horizontal = new JCheckBox();
    horizontal.setSelected(false);
    il = new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            CategoryPlot plot = (CategoryPlot) (chart.getPlot());
            if (e.getStateChange() == ItemEvent.SELECTED) {
                plot.setOrientation(PlotOrientation.HORIZONTAL);
            } else {
                plot.setOrientation(PlotOrientation.VERTICAL);
            }
            //updateGridLines();
        }
    };
    horizontal.addItemListener(il);

    list.add(new JLabel("Horizontal"), horizontal);

    final JCheckBox whiskersUseFillColorButton = new JCheckBox();
    whiskersUseFillColorButton.setSelected(false);
    whiskersUseFillColorButton.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            BoxAndWhiskerRenderer renderer = ((BoxAndWhiskerRenderer) ((CategoryPlot) (chart.getPlot()))
                    .getRenderer());
            renderer.setUseOutlinePaintForWhiskers(!whiskersUseFillColorButton.isSelected());
        }
    });

    box = Box.createHorizontalBox();
    box.add(new JLabel(" Colored"));
    box.add(whiskersUseFillColorButton);
    box.add(Box.createGlue());
    list.add(new JLabel("Whiskers"), box);
}

From source file:MyLink.java

public JPanel printableKSGenerate() {
    // create a simple graph for the demo
    graph = new SparseMultigraph<Integer, MyLink>();

    Integer[] v = createVertices(getTermNum());
    createEdges(v);// w w  w. j a v  a2  s . c o m

    vv = new VisualizationViewer<Integer, MyLink>(new KKLayout<Integer, MyLink>(graph));
    vv.setPreferredSize(new Dimension(520, 520)); // 570, 640 | 565, 640 

    vv.getRenderContext().setVertexLabelTransformer(new UnicodeVertexStringer<Integer>(v));
    vv.getRenderContext().setVertexLabelRenderer(new DefaultVertexLabelRenderer(Color.magenta));
    vv.getRenderContext().setEdgeLabelRenderer(new DefaultEdgeLabelRenderer(Color.magenta));
    VertexIconShapeTransformer<Integer> vertexIconShapeFunction = new VertexIconShapeTransformer<Integer>(
            new EllipseVertexShapeTransformer<Integer>());
    DefaultVertexIconTransformer<Integer> vertexIconFunction = new DefaultVertexIconTransformer<Integer>();
    vv.getRenderContext().setVertexShapeTransformer(vertexIconShapeFunction);
    vv.getRenderContext().setVertexIconTransformer(vertexIconFunction);
    loadImages(v, vertexIconFunction.getIconMap());
    vertexIconShapeFunction.setIconMap(vertexIconFunction.getIconMap());
    vv.getRenderContext().setVertexFillPaintTransformer(new PickableVertexPaintTransformer<Integer>(
            vv.getPickedVertexState(), new Color(0, 102, 255), Color.red));
    vv.getRenderContext().setEdgeDrawPaintTransformer(
            new PickableEdgePaintTransformer<MyLink>(vv.getPickedEdgeState(), Color.orange, Color.cyan));
    vv.setBackground(Color.white);

    final int maxSize = findMaxSizeNumber();

    File file = new File("./output/DESC_TERM_COUNT.txt");
    String s;

    try {
        BufferedReader fis = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

        s = fis.readLine();
        userSelectedTermsCount = Integer.parseInt(s);
        termIndex = new int[userSelectedTermsCount];

        int i = 0;
        while ((s = fis.readLine()) != null) {
            String[] tmp = s.split("=");
            termIndex[i] = Integer.parseInt(tmp[1].trim());
            i++;
        }

    } catch (IOException e) {
        System.out.println(e.getMessage());
    }

    Transformer<Integer, Shape> vertexSize = new Transformer<Integer, Shape>() {
        public Shape transform(Integer i) {
            double sizeInt = termIndex[i];
            sizeInt = (double) sizeInt / (double) maxSize;
            sizeInt = (double) sizeInt * (double) 30 + 10;
            Ellipse2D circle = new Ellipse2D.Double(sizeInt / 2 * (-1), sizeInt / 2 * (-1), sizeInt, sizeInt);
            return circle;
        }
    };
    vv.getRenderContext().setVertexShapeTransformer(vertexSize);
    vv.getRenderer().getVertexLabelRenderer().setPosition(Position.N);

    // add my listener for ToolTips
    vv.setVertexToolTipTransformer(new ToStringLabeller<Integer>());

    // create a frome to hold the graph
    APanel = new JPanel();
    APanel.setLayout(new BoxLayout(APanel, BoxLayout.Y_AXIS));

    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);

    final ModalGraphMouse gm = new DefaultModalGraphMouse<Integer, Number>();
    vv.setGraphMouse(gm);

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JCheckBox lo = new JCheckBox("Show Labels");
    lo.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            showLabels = e.getStateChange() == ItemEvent.SELECTED;

            vv.repaint();
        }
    });
    lo.setSelected(true);

    JPanel controls = new JPanel();
    controls.add(plus);
    controls.add(minus);
    controls.add(lo);
    controls.add(((DefaultModalGraphMouse<Integer, Number>) gm).getModeComboBox());
    APanel.add(vv);
    APanel.add(controls);

    return APanel;
}