Example usage for javax.swing JComboBox addItem

List of usage examples for javax.swing JComboBox addItem

Introduction

In this page you can find the example usage for javax.swing JComboBox addItem.

Prototype

public void addItem(E item) 

Source Link

Document

Adds an item to the item list.

Usage

From source file:com.intuit.tank.tools.debugger.ActionProducer.java

public void setChoiceComboBoxOptions(JComboBox<TankClientChoice> cb) {
    cb.removeAllItems();//  w  w w.  j  av  a2s .co  m
    try {
        TankHttpClientDefinitionContainer clientDefinitions = agentServiceClient.getClientDefinitions();
        for (TankHttpClientDefinition def : clientDefinitions.getDefinitions()) {
            TankClientChoice c = new TankClientChoice(def.getName(), def.getClassName());
            cb.addItem(c);
            if (def.getClassName().equals(clientDefinitions.getDefaultDefinition())) {
                cb.setSelectedItem(c);
            }
        }
    } catch (Exception e) {
        //            set to default
        cb.addItem(
                new TankClientChoice("Apache HttpClient 3.1", "com.intuit.tank.httpclient3.TankHttpClient3"));
        cb.addItem(
                new TankClientChoice("Apache HttpClient 4.5", "com.intuit.tank.httpclient4.TankHttpClient4"));
        cb.setSelectedIndex(1);
    }
}

From source file:de.unikassel.jung.PluggableRendererDemo.java

/**
 * @param jp//from  w ww.j a v a  2  s.co m
 *            panel to which controls will be added
 */
@SuppressWarnings("serial")
protected void addBottomControls(final JPanel jp) {
    final JPanel control_panel = new JPanel();
    jp.add(control_panel, BorderLayout.EAST);
    control_panel.setLayout(new BorderLayout());
    final Box vertex_panel = Box.createVerticalBox();
    vertex_panel.setBorder(BorderFactory.createTitledBorder("Vertices"));
    final Box edge_panel = Box.createVerticalBox();
    edge_panel.setBorder(BorderFactory.createTitledBorder("Edges"));
    final Box both_panel = Box.createVerticalBox();

    control_panel.add(vertex_panel, BorderLayout.NORTH);
    control_panel.add(edge_panel, BorderLayout.SOUTH);
    control_panel.add(both_panel, BorderLayout.CENTER);

    // set up vertex controls
    v_color = new JCheckBox("seed highlight");
    v_color.addActionListener(this);
    v_stroke = new JCheckBox("stroke highlight on selection");
    v_stroke.addActionListener(this);
    v_labels = new JCheckBox("show voltage values");
    v_labels.addActionListener(this);
    v_shape = new JCheckBox("shape by degree");
    v_shape.addActionListener(this);
    v_size = new JCheckBox("size by voltage");
    v_size.addActionListener(this);
    v_size.setSelected(true);
    v_aspect = new JCheckBox("stretch by degree ratio");
    v_aspect.addActionListener(this);
    v_small = new JCheckBox("filter when degree < " + VertexDisplayPredicate.MIN_DEGREE);
    v_small.addActionListener(this);

    vertex_panel.add(v_color);
    vertex_panel.add(v_stroke);
    vertex_panel.add(v_labels);
    vertex_panel.add(v_shape);
    vertex_panel.add(v_size);
    vertex_panel.add(v_aspect);
    vertex_panel.add(v_small);

    // set up edge controls
    JPanel gradient_panel = new JPanel(new GridLayout(1, 0));
    gradient_panel.setBorder(BorderFactory.createTitledBorder("Edge paint"));
    no_gradient = new JRadioButton("Solid color");
    no_gradient.addActionListener(this);
    no_gradient.setSelected(true);
    // gradient_absolute = new JRadioButton("Absolute gradient");
    // gradient_absolute.addActionListener(this);
    gradient_relative = new JRadioButton("Gradient");
    gradient_relative.addActionListener(this);
    ButtonGroup bg_grad = new ButtonGroup();
    bg_grad.add(no_gradient);
    bg_grad.add(gradient_relative);
    // bg_grad.add(gradient_absolute);
    gradient_panel.add(no_gradient);
    // gradientGrid.add(gradient_absolute);
    gradient_panel.add(gradient_relative);

    JPanel shape_panel = new JPanel(new GridLayout(3, 2));
    shape_panel.setBorder(BorderFactory.createTitledBorder("Edge shape"));
    e_line = new JRadioButton("line");
    e_line.addActionListener(this);
    e_line.setSelected(true);
    // e_bent = new JRadioButton("bent line");
    // e_bent.addActionListener(this);
    e_wedge = new JRadioButton("wedge");
    e_wedge.addActionListener(this);
    e_quad = new JRadioButton("quad curve");
    e_quad.addActionListener(this);
    e_cubic = new JRadioButton("cubic curve");
    e_cubic.addActionListener(this);
    e_ortho = new JRadioButton("orthogonal");
    e_ortho.addActionListener(this);
    ButtonGroup bg_shape = new ButtonGroup();
    bg_shape.add(e_line);
    // bg.add(e_bent);
    bg_shape.add(e_wedge);
    bg_shape.add(e_quad);
    bg_shape.add(e_ortho);
    bg_shape.add(e_cubic);
    shape_panel.add(e_line);
    // shape_panel.add(e_bent);
    shape_panel.add(e_wedge);
    shape_panel.add(e_quad);
    shape_panel.add(e_cubic);
    shape_panel.add(e_ortho);
    fill_edges = new JCheckBox("fill edge shapes");
    fill_edges.setSelected(false);
    fill_edges.addActionListener(this);
    shape_panel.add(fill_edges);
    shape_panel.setOpaque(true);
    e_color = new JCheckBox("highlight edge weights");
    e_color.addActionListener(this);
    e_labels = new JCheckBox("show edge weight values");
    e_labels.addActionListener(this);
    e_uarrow_pred = new JCheckBox("undirected");
    e_uarrow_pred.addActionListener(this);
    e_darrow_pred = new JCheckBox("directed");
    e_darrow_pred.addActionListener(this);
    e_darrow_pred.setSelected(true);
    e_arrow_centered = new JCheckBox("centered");
    e_arrow_centered.addActionListener(this);
    JPanel arrow_panel = new JPanel(new GridLayout(1, 0));
    arrow_panel.setBorder(BorderFactory.createTitledBorder("Show arrows"));
    arrow_panel.add(e_uarrow_pred);
    arrow_panel.add(e_darrow_pred);
    arrow_panel.add(e_arrow_centered);

    e_show_d = new JCheckBox("directed");
    e_show_d.addActionListener(this);
    e_show_d.setSelected(true);
    e_show_u = new JCheckBox("undirected");
    e_show_u.addActionListener(this);
    e_show_u.setSelected(true);
    JPanel show_edge_panel = new JPanel(new GridLayout(1, 0));
    show_edge_panel.setBorder(BorderFactory.createTitledBorder("Show edges"));
    show_edge_panel.add(e_show_u);
    show_edge_panel.add(e_show_d);

    shape_panel.setAlignmentX(Component.LEFT_ALIGNMENT);
    edge_panel.add(shape_panel);
    gradient_panel.setAlignmentX(Component.LEFT_ALIGNMENT);
    edge_panel.add(gradient_panel);
    show_edge_panel.setAlignmentX(Component.LEFT_ALIGNMENT);
    edge_panel.add(show_edge_panel);
    arrow_panel.setAlignmentX(Component.LEFT_ALIGNMENT);
    edge_panel.add(arrow_panel);

    e_color.setAlignmentX(Component.LEFT_ALIGNMENT);
    edge_panel.add(e_color);
    e_labels.setAlignmentX(Component.LEFT_ALIGNMENT);
    edge_panel.add(e_labels);

    // set up zoom controls
    zoom_at_mouse = new JCheckBox("<html><center>zoom at mouse<p>(wheel only)</center></html>");
    zoom_at_mouse.addActionListener(this);
    zoom_at_mouse.setSelected(true);

    final ScalingControl scaler = new CrossoverScalingControl();

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

    JPanel zoomPanel = new JPanel();
    zoomPanel.setBorder(BorderFactory.createTitledBorder("Zoom"));
    plus.setAlignmentX(Component.CENTER_ALIGNMENT);
    zoomPanel.add(plus);
    minus.setAlignmentX(Component.CENTER_ALIGNMENT);
    zoomPanel.add(minus);
    zoom_at_mouse.setAlignmentX(Component.CENTER_ALIGNMENT);
    zoomPanel.add(zoom_at_mouse);

    JPanel fontPanel = new JPanel();
    // add font and zoom controls to center panel
    font = new JCheckBox("bold text");
    font.addActionListener(this);
    font.setAlignmentX(Component.CENTER_ALIGNMENT);
    fontPanel.add(font);

    both_panel.add(zoomPanel);
    both_panel.add(fontPanel);

    JComboBox modeBox = gm.getModeComboBox();
    modeBox.setAlignmentX(Component.CENTER_ALIGNMENT);
    JPanel modePanel = new JPanel(new BorderLayout()) {
        @Override
        public Dimension getMaximumSize() {
            return getPreferredSize();
        }
    };
    modePanel.setBorder(BorderFactory.createTitledBorder("Mouse Mode"));
    modePanel.add(modeBox);
    JPanel comboGrid = new JPanel(new GridLayout(0, 1));
    comboGrid.add(modePanel);
    fontPanel.add(comboGrid);

    JComboBox cb = new JComboBox();
    cb.addItem(Renderer.VertexLabel.Position.N);
    cb.addItem(Renderer.VertexLabel.Position.NE);
    cb.addItem(Renderer.VertexLabel.Position.E);
    cb.addItem(Renderer.VertexLabel.Position.SE);
    cb.addItem(Renderer.VertexLabel.Position.S);
    cb.addItem(Renderer.VertexLabel.Position.SW);
    cb.addItem(Renderer.VertexLabel.Position.W);
    cb.addItem(Renderer.VertexLabel.Position.NW);
    cb.addItem(Renderer.VertexLabel.Position.N);
    cb.addItem(Renderer.VertexLabel.Position.CNTR);
    cb.addItem(Renderer.VertexLabel.Position.AUTO);
    cb.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(final ItemEvent e) {
            Renderer.VertexLabel.Position position = (Renderer.VertexLabel.Position) e.getItem();
            vv.getRenderer().getVertexLabelRenderer().setPosition(position);
            vv.repaint();
        }
    });
    cb.setSelectedItem(Renderer.VertexLabel.Position.SE);
    JPanel positionPanel = new JPanel();
    positionPanel.setBorder(BorderFactory.createTitledBorder("Label Position"));
    positionPanel.add(cb);

    comboGrid.add(positionPanel);

}

From source file:com.net2plan.gui.utils.viewEditTopolTables.specificTables.AdvancedJTable_node.java

private List<JComponent> getExtraOptions(final int row, final Object itemId) {
    List<JComponent> options = new LinkedList<JComponent>();
    final int numRows = model.getRowCount();
    final List<Node> tableVisibleNodes = getVisibleElementsInTable();

    if (itemId != null) {
        JMenuItem switchCoordinates_thisNode = new JMenuItem("Switch node coordinates from (x,y) to (y,x)");

        switchCoordinates_thisNode.addActionListener(new ActionListener() {
            @Override/*from w w w .  ja  va 2s .c o  m*/
            public void actionPerformed(ActionEvent e) {
                NetPlan netPlan = callback.getDesign();
                Node node = netPlan.getNodeFromId((long) itemId);
                Point2D currentPosition = node.getXYPositionMap();
                node.setXYPositionMap(new Point2D.Double(currentPosition.getY(), currentPosition.getX()));
                callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.NODE));
                callback.runCanvasOperation(ITopologyCanvas.CanvasOperation.ZOOM_ALL);
                callback.getUndoRedoNavigationManager().addNetPlanChange();
            }
        });

        options.add(switchCoordinates_thisNode);

        JMenuItem xyPositionFromAttributes_thisNode = new JMenuItem("Set node coordinates from attributes");

        xyPositionFromAttributes_thisNode.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                NetPlan netPlan = callback.getDesign();

                Set<String> attributeSet = new LinkedHashSet<String>();
                Node node = netPlan.getNodeFromId((long) itemId);
                attributeSet.addAll(node.getAttributes().keySet());

                try {
                    if (attributeSet.isEmpty())
                        throw new Exception("No attribute to select");

                    final JComboBox latSelector = new WiderJComboBox();
                    final JComboBox lonSelector = new WiderJComboBox();
                    for (String attribute : attributeSet) {
                        latSelector.addItem(attribute);
                        lonSelector.addItem(attribute);
                    }

                    JPanel pane = new JPanel(new MigLayout("", "[][grow]", "[][]"));
                    pane.add(new JLabel("X-coordinate / Longitude: "));
                    pane.add(lonSelector, "growx, wrap");
                    pane.add(new JLabel("Y-coordinate / Latitude: "));
                    pane.add(latSelector, "growx, wrap");

                    while (true) {
                        int result = JOptionPane.showConfirmDialog(null, pane,
                                "Please select the attributes for coordinates", JOptionPane.OK_CANCEL_OPTION,
                                JOptionPane.QUESTION_MESSAGE);
                        if (result != JOptionPane.OK_OPTION)
                            return;

                        try {
                            String latAttribute = latSelector.getSelectedItem().toString();
                            String lonAttribute = lonSelector.getSelectedItem().toString();

                            node.setXYPositionMap(
                                    new Point2D.Double(Double.parseDouble(node.getAttribute(lonAttribute)),
                                            Double.parseDouble(node.getAttribute(latAttribute))));
                            callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.NODE));
                            callback.getUndoRedoNavigationManager().addNetPlanChange();
                            break;
                        } catch (Throwable ex) {
                            ErrorHandling.showErrorDialog(ex.getMessage(),
                                    "Error retrieving coordinates from attributes");
                            break;
                        }
                    }
                    callback.runCanvasOperation(ITopologyCanvas.CanvasOperation.ZOOM_ALL);
                } catch (Throwable ex) {
                    ErrorHandling.showErrorDialog(ex.getMessage(),
                            "Error retrieving coordinates from attributes");
                }
            }
        });

        options.add(xyPositionFromAttributes_thisNode);

        JMenuItem nameFromAttribute_thisNode = new JMenuItem("Set node name from attribute");
        nameFromAttribute_thisNode.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                NetPlan netPlan = callback.getDesign();

                Set<String> attributeSet = new LinkedHashSet<String>();
                long nodeId = (long) itemId;
                attributeSet.addAll(netPlan.getNodeFromId(nodeId).getAttributes().keySet());

                try {
                    if (attributeSet.isEmpty())
                        throw new Exception("No attribute to select");

                    final JComboBox selector = new WiderJComboBox();
                    for (String attribute : attributeSet)
                        selector.addItem(attribute);

                    JPanel pane = new JPanel(new MigLayout("", "[][grow]", "[]"));
                    pane.add(new JLabel("Name: "));
                    pane.add(selector, "growx, wrap");

                    while (true) {
                        int result = JOptionPane.showConfirmDialog(null, pane,
                                "Please select the attribute for name", JOptionPane.OK_CANCEL_OPTION,
                                JOptionPane.QUESTION_MESSAGE);
                        if (result != JOptionPane.OK_OPTION)
                            return;

                        try {
                            String name = selector.getSelectedItem().toString();
                            netPlan.getNodeFromId(nodeId)
                                    .setName(netPlan.getNodeFromId(nodeId).getAttribute(name));
                            callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.NODE));
                            callback.getUndoRedoNavigationManager().addNetPlanChange();

                            break;
                        } catch (Throwable ex) {
                            ErrorHandling.showErrorDialog(ex.getMessage(),
                                    "Error retrieving name from attribute");
                            break;
                        }
                    }
                } catch (Throwable ex) {
                    ErrorHandling.showErrorDialog(ex.getMessage(), "Error retrieving name from attribute");
                }
            }
        });

        options.add(nameFromAttribute_thisNode);
    }

    if (numRows > 1) {
        if (!options.isEmpty())
            options.add(new JPopupMenu.Separator());

        JMenuItem switchCoordinates_allNodes = new JMenuItem(
                "Switch all table node coordinates from (x,y) to (y,x)");

        switchCoordinates_allNodes.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (Node n : tableVisibleNodes) {
                    Point2D currentPosition = n.getXYPositionMap();
                    double newX = currentPosition.getY();
                    double newY = currentPosition.getX();
                    Point2D newPosition = new Point2D.Double(newX, newY);
                    n.setXYPositionMap(newPosition);
                }
                callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.NODE));
                callback.runCanvasOperation(ITopologyCanvas.CanvasOperation.ZOOM_ALL);
                callback.getUndoRedoNavigationManager().addNetPlanChange();
            }
        });

        options.add(switchCoordinates_allNodes);

        JMenuItem xyPositionFromAttributes_allNodes = new JMenuItem(
                "Set all table node coordinates from attributes");

        xyPositionFromAttributes_allNodes.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Set<String> attributeSet = new LinkedHashSet<String>();
                for (Node node : tableVisibleNodes)
                    attributeSet.addAll(node.getAttributes().keySet());

                try {
                    if (attributeSet.isEmpty())
                        throw new Exception("No attribute to select");

                    final JComboBox latSelector = new WiderJComboBox();
                    final JComboBox lonSelector = new WiderJComboBox();
                    for (String attribute : attributeSet) {
                        latSelector.addItem(attribute);
                        lonSelector.addItem(attribute);
                    }

                    JPanel pane = new JPanel(new MigLayout("", "[][grow]", "[][]"));
                    pane.add(new JLabel("X-coordinate / Longitude: "));
                    pane.add(lonSelector, "growx, wrap");
                    pane.add(new JLabel("Y-coordinate / Latitude: "));
                    pane.add(latSelector, "growx, wrap");

                    while (true) {
                        int result = JOptionPane.showConfirmDialog(null, pane,
                                "Please select the attributes for coordinates", JOptionPane.OK_CANCEL_OPTION,
                                JOptionPane.QUESTION_MESSAGE);
                        if (result != JOptionPane.OK_OPTION)
                            return;

                        try {
                            String latAttribute = latSelector.getSelectedItem().toString();
                            String lonAttribute = lonSelector.getSelectedItem().toString();

                            for (Node node : tableVisibleNodes)
                                node.setXYPositionMap(
                                        new Point2D.Double(Double.parseDouble(node.getAttribute(lonAttribute)),
                                                Double.parseDouble(node.getAttribute(latAttribute))));
                            callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.NODE));
                            callback.getUndoRedoNavigationManager().addNetPlanChange();
                            break;
                        } catch (Throwable ex) {
                            ErrorHandling.showErrorDialog(ex.getMessage(),
                                    "Error retrieving coordinates from attributes");
                            break;
                        }
                    }
                    callback.runCanvasOperation(ITopologyCanvas.CanvasOperation.ZOOM_ALL);
                } catch (Throwable ex) {
                    ErrorHandling.showErrorDialog(ex.getMessage(),
                            "Error retrieving coordinates from attributes");
                }
            }
        });

        options.add(xyPositionFromAttributes_allNodes);

        JMenuItem nameFromAttribute_allNodes = new JMenuItem("Set all table node names from attribute");
        nameFromAttribute_allNodes.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                Set<String> attributeSet = new LinkedHashSet<String>();
                for (Node node : tableVisibleNodes)
                    attributeSet.addAll(node.getAttributes().keySet());

                try {
                    if (attributeSet.isEmpty())
                        throw new Exception("No attribute to select");

                    final JComboBox selector = new WiderJComboBox();
                    for (String attribute : attributeSet)
                        selector.addItem(attribute);

                    JPanel pane = new JPanel(new MigLayout("", "[][grow]", "[]"));
                    pane.add(new JLabel("Name: "));
                    pane.add(selector, "growx, wrap");

                    while (true) {
                        int result = JOptionPane.showConfirmDialog(null, pane,
                                "Please select the attribute for name", JOptionPane.OK_CANCEL_OPTION,
                                JOptionPane.QUESTION_MESSAGE);
                        if (result != JOptionPane.OK_OPTION)
                            return;

                        try {
                            String name = selector.getSelectedItem().toString();

                            for (Node node : tableVisibleNodes)
                                node.setName(node.getAttribute(name) != null ? node.getAttribute(name) : "");
                            callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.NODE));
                            callback.getUndoRedoNavigationManager().addNetPlanChange();
                            break;
                        } catch (Throwable ex) {
                            ErrorHandling.showErrorDialog(ex.getMessage(),
                                    "Error retrieving name from attribute");
                            break;
                        }
                    }
                } catch (Throwable ex) {
                    ErrorHandling.showErrorDialog(ex.getMessage(), "Error retrieving name from attribute");
                }
            }
        });

        options.add(nameFromAttribute_allNodes);
    }

    return options;
}

From source file:com.entertailion.java.fling.FlingFrame.java

public FlingFrame(String appId) {
    super();//from   w ww.ja v  a  2s .  c o  m
    this.appId = appId;
    rampClient = new RampClient(this);

    addWindowListener(this);

    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    Locale locale = Locale.getDefault();
    resourceBundle = ResourceBundle.getBundle("com/entertailion/java/fling/resources/resources", locale);
    setTitle(MessageFormat.format(resourceBundle.getString("fling.title"), Fling.VERSION));

    JPanel listPane = new JPanel();
    // show list of ChromeCast devices detected on the local network
    listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS));
    JPanel devicePane = new JPanel();
    devicePane.setLayout(new BoxLayout(devicePane, BoxLayout.LINE_AXIS));
    deviceList = new JComboBox();
    deviceList.addActionListener(this);
    devicePane.add(deviceList);
    URL url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/refresh.png");
    ImageIcon icon = new ImageIcon(url, resourceBundle.getString("button.refresh"));
    refreshButton = new JButton(icon);
    refreshButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            // refresh the list of devices
            if (deviceList.getItemCount() > 0) {
                deviceList.setSelectedIndex(0);
            }
            discoverDevices();
        }
    });
    refreshButton.setToolTipText(resourceBundle.getString("button.refresh"));
    devicePane.add(refreshButton);
    url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/settings.png");
    icon = new ImageIcon(url, resourceBundle.getString("settings.title"));
    settingsButton = new JButton(icon);
    settingsButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            JTextField transcodingExtensions = new JTextField(50);
            transcodingExtensions.setText(transcodingExtensionValues);
            JTextField transcodingParameters = new JTextField(50);
            transcodingParameters.setText(transcodingParameterValues);

            JPanel myPanel = new JPanel(new BorderLayout());
            JPanel labelPanel = new JPanel(new GridLayout(3, 1));
            JPanel fieldPanel = new JPanel(new GridLayout(3, 1));
            myPanel.add(labelPanel, BorderLayout.WEST);
            myPanel.add(fieldPanel, BorderLayout.CENTER);
            labelPanel.add(new JLabel(resourceBundle.getString("transcoding.extensions"), JLabel.RIGHT));
            fieldPanel.add(transcodingExtensions);
            labelPanel.add(new JLabel(resourceBundle.getString("transcoding.parameters"), JLabel.RIGHT));
            fieldPanel.add(transcodingParameters);
            labelPanel.add(new JLabel(resourceBundle.getString("device.manual"), JLabel.RIGHT));
            JPanel devicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            final JComboBox manualDeviceList = new JComboBox();
            if (manualServers.size() == 0) {
                manualDeviceList.setVisible(false);
            } else {
                for (DialServer dialServer : manualServers) {
                    manualDeviceList.addItem(dialServer);
                }
            }
            devicePanel.add(manualDeviceList);
            JButton addButton = new JButton(resourceBundle.getString("device.manual.add"));
            addButton.setToolTipText(resourceBundle.getString("device.manual.add.tooltip"));
            addButton.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    JTextField name = new JTextField();
                    JTextField ipAddress = new JTextField();
                    Object[] message = { resourceBundle.getString("device.manual.name") + ":", name,
                            resourceBundle.getString("device.manual.ipaddress") + ":", ipAddress };

                    int option = JOptionPane.showConfirmDialog(null, message,
                            resourceBundle.getString("device.manual"), JOptionPane.OK_CANCEL_OPTION);
                    if (option == JOptionPane.OK_OPTION) {
                        try {
                            manualServers.add(
                                    new DialServer(name.getText(), InetAddress.getByName(ipAddress.getText())));

                            Object selected = deviceList.getSelectedItem();
                            int selectedIndex = deviceList.getSelectedIndex();
                            deviceList.removeAllItems();
                            deviceList.addItem(resourceBundle.getString("devices.select"));
                            for (DialServer dialServer : servers) {
                                deviceList.addItem(dialServer);
                            }
                            for (DialServer dialServer : manualServers) {
                                deviceList.addItem(dialServer);
                            }
                            deviceList.invalidate();
                            if (selectedIndex > 0) {
                                deviceList.setSelectedItem(selected);
                            } else {
                                if (deviceList.getItemCount() == 2) {
                                    // Automatically select single device
                                    deviceList.setSelectedIndex(1);
                                }
                            }

                            manualDeviceList.removeAllItems();
                            for (DialServer dialServer : manualServers) {
                                manualDeviceList.addItem(dialServer);
                            }
                            manualDeviceList.setVisible(true);
                            storeProperties();
                        } catch (UnknownHostException e1) {
                            Log.e(LOG_TAG, "manual IP address", e1);

                            JOptionPane.showMessageDialog(FlingFrame.this,
                                    resourceBundle.getString("device.manual.invalidip"));
                        }
                    }
                }
            });
            devicePanel.add(addButton);
            JButton removeButton = new JButton(resourceBundle.getString("device.manual.remove"));
            removeButton.setToolTipText(resourceBundle.getString("device.manual.remove.tooltip"));
            removeButton.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    Object selected = manualDeviceList.getSelectedItem();
                    manualDeviceList.removeItem(selected);
                    if (manualDeviceList.getItemCount() == 0) {
                        manualDeviceList.setVisible(false);
                    }
                    deviceList.removeItem(selected);
                    deviceList.invalidate();
                    manualServers.remove(selected);
                    storeProperties();
                }
            });
            devicePanel.add(removeButton);
            fieldPanel.add(devicePanel);
            int result = JOptionPane.showConfirmDialog(FlingFrame.this, myPanel,
                    resourceBundle.getString("settings.title"), JOptionPane.OK_CANCEL_OPTION);
            if (result == JOptionPane.OK_OPTION) {
                transcodingParameterValues = transcodingParameters.getText();
                transcodingExtensionValues = transcodingExtensions.getText();
                storeProperties();
            }
        }
    });
    settingsButton.setToolTipText(resourceBundle.getString("settings.title"));
    devicePane.add(settingsButton);
    listPane.add(devicePane);

    // TODO
    volume = new JSlider(JSlider.VERTICAL, 0, 100, 0);
    volume.setUI(new MySliderUI(volume));
    volume.setMajorTickSpacing(25);
    // volume.setMinorTickSpacing(5);
    volume.setPaintTicks(true);
    volume.setEnabled(true);
    volume.setValue(100);
    volume.setToolTipText(resourceBundle.getString("volume.title"));
    volume.addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            JSlider source = (JSlider) e.getSource();
            if (!source.getValueIsAdjusting()) {
                int position = (int) source.getValue();
                rampClient.volume(position / 100.0f);
            }
        }

    });
    JPanel centerPanel = new JPanel(new BorderLayout());
    // centerPanel.add(volume, BorderLayout.WEST);

    centerPanel.add(DragHereIcon.makeUI(this), BorderLayout.CENTER);
    listPane.add(centerPanel);

    scrubber = new JSlider(JSlider.HORIZONTAL, 0, 100, 0);
    scrubber.addChangeListener(this);
    scrubber.setMajorTickSpacing(25);
    scrubber.setMinorTickSpacing(5);
    scrubber.setPaintTicks(true);
    scrubber.setEnabled(false);
    listPane.add(scrubber);

    // panel of playback buttons
    JPanel buttonPane = new JPanel();
    buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
    label = new JLabel("00:00:00");
    buttonPane.add(label);
    url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/play.png");
    icon = new ImageIcon(url, resourceBundle.getString("button.play"));
    playButton = new JButton(icon);
    playButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            rampClient.play();
        }
    });
    buttonPane.add(playButton);
    url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/pause.png");
    icon = new ImageIcon(url, resourceBundle.getString("button.pause"));
    pauseButton = new JButton(icon);
    pauseButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            rampClient.pause();
        }
    });
    buttonPane.add(pauseButton);
    url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/stop.png");
    icon = new ImageIcon(url, resourceBundle.getString("button.stop"));
    stopButton = new JButton(icon);
    stopButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            rampClient.stop();
            setDuration(0);
            scrubber.setValue(0);
            scrubber.setEnabled(false);
        }
    });
    buttonPane.add(stopButton);
    listPane.add(buttonPane);
    getContentPane().add(listPane);

    createProgressDialog();
    startWebserver();
    discoverDevices();
}

From source file:net.itransformers.topologyviewer.gui.GraphViewerPanel.java

private JComboBox createFilterCombo(JComboBox filtersCombo) {
    FiltersType filtersType = viewerConfig.getFilters();
    // filtersCombo = new JComboBox();
    if (filtersType == null)
        return filtersCombo;
    java.util.List<FilterType> filters = filtersType.getFilter();
    final Map<String, FilterType> filterName2FilterType = new HashMap<String, FilterType>();

    for (FilterType filter : filters) {
        filtersCombo.addItem(filter.getName());
        filterName2FilterType.put(filter.getName(), filter);
    }/*from ww w.  j a v a2s . c om*/
    filtersCombo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String filterName = (String) ((JComboBox) e.getSource()).getSelectedItem();
            currentFilter = filterName2FilterType.get(filterName);
            vv.setCurrentFilter(currentFilter);
            //                Set<String> vertexes = new HashSet<String>(currentGraph.getVertices());
            Set<String> pickedVertexes = getPickedVerteces();
            if (pickedVertexes != null) {
                applyFilter(currentFilter, currentHops, pickedVertexes);
            } else {
                applyFilter(currentFilter, currentHops);
            }
        }
    });
    final String filterName = (String) filtersCombo.getSelectedItem();
    currentFilter = filterName2FilterType.get(filterName);
    vv.setCurrentFilter(currentFilter);
    return filtersCombo;
}

From source file:com.net2plan.gui.utils.viewEditTopolTables.specificTables.AdvancedJTable_multicastDemand.java

private List<JComponent> getExtraOptions(final int row, final Object itemId) {
    List<JComponent> options = new LinkedList<JComponent>();

    final int numRows = model.getRowCount();
    final NetPlan netPlan = callback.getDesign();
    final List<MulticastDemand> visibleRows = getVisibleElementsInTable();

    JMenuItem offeredTrafficToAll = new JMenuItem("Set offered traffic to all");
    offeredTrafficToAll.addActionListener(new ActionListener() {
        @Override/* w  w  w. ja  va 2  s.c  om*/
        public void actionPerformed(ActionEvent e) {
            double h_d;

            while (true) {
                String str = JOptionPane.showInputDialog(null, "Offered traffic volume",
                        "Set traffic value to all table multicast demands", JOptionPane.QUESTION_MESSAGE);
                if (str == null)
                    return;

                try {
                    h_d = Double.parseDouble(str);
                    if (h_d < 0)
                        throw new RuntimeException();

                    break;
                } catch (Throwable ex) {
                    ErrorHandling.showErrorDialog(
                            "Non-valid multicast demand offered traffic value. Please, introduce a non-negative number",
                            "Error setting link length");
                }
            }

            try {
                for (MulticastDemand demand : visibleRows)
                    demand.setOfferedTraffic(h_d);
                callback.updateVisualizationAfterChanges(
                        Collections.singleton(NetworkElementType.MULTICAST_DEMAND));
                callback.getUndoRedoNavigationManager().addNetPlanChange();
            } catch (Throwable ex) {
                ErrorHandling.showErrorDialog(ex.getMessage(),
                        "Unable to set offered traffic to all multicast demands");
            }
        }
    });

    options.add(offeredTrafficToAll);

    if (itemId != null && netPlan.isMultilayer()) {
        final long demandId = (long) itemId;
        final MulticastDemand demand = netPlan.getMulticastDemandFromId(demandId);
        if (demand.isCoupled()) {
            JMenuItem decoupleDemandItem = new JMenuItem("Decouple multicast demand");
            decoupleDemandItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    demand.decouple();
                    model.setValueAt("", row, COLUMN_COUPLEDTOLINKS);
                    callback.getVisualizationState().resetPickedState();
                    callback.updateVisualizationAfterChanges(
                            Sets.newHashSet(NetworkElementType.MULTICAST_DEMAND, NetworkElementType.LINK));
                    callback.getUndoRedoNavigationManager().addNetPlanChange();
                }
            });

            options.add(decoupleDemandItem);
        }
        if (numRows > 1) {
            JMenuItem decoupleAllDemandsItem = null;
            JMenuItem createUpperLayerLinksFromDemandsItem = null;

            final Set<MulticastDemand> coupledDemands = visibleRows.stream().filter(e -> e.isCoupled())
                    .collect(Collectors.toSet());
            if (!coupledDemands.isEmpty()) {
                decoupleAllDemandsItem = new JMenuItem("Decouple all table demands");
                decoupleAllDemandsItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        for (MulticastDemand d : coupledDemands)
                            d.decouple();
                        int numRows = model.getRowCount();
                        for (int i = 0; i < numRows; i++)
                            model.setValueAt("", i, COLUMN_COUPLEDTOLINKS);
                        callback.getVisualizationState().resetPickedState();
                        callback.updateVisualizationAfterChanges(
                                Sets.newHashSet(NetworkElementType.MULTICAST_DEMAND, NetworkElementType.LINK));
                        callback.getUndoRedoNavigationManager().addNetPlanChange();
                    }
                });
            }

            if (coupledDemands.size() < visibleRows.size()) {
                createUpperLayerLinksFromDemandsItem = new JMenuItem(
                        "Create upper layer links from uncoupled demands");
                createUpperLayerLinksFromDemandsItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        List<Long> layerIds = netPlan.getNetworkLayerIds();
                        final JComboBox layerSelector = new WiderJComboBox();
                        for (long layerId : layerIds) {
                            if (layerId == netPlan.getNetworkLayerDefault().getId())
                                continue;

                            final String layerName = netPlan.getNetworkLayerFromId(layerId).getName();
                            String layerLabel = "Layer " + layerId;
                            if (!layerName.isEmpty())
                                layerLabel += " (" + layerName + ")";

                            layerSelector.addItem(StringLabeller.of(layerId, layerLabel));
                        }

                        layerSelector.setSelectedIndex(0);

                        JPanel pane = new JPanel();
                        pane.add(new JLabel("Select layer: "));
                        pane.add(layerSelector);

                        while (true) {
                            int result = JOptionPane.showConfirmDialog(null, pane,
                                    "Please select the upper layer to create links",
                                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                            if (result != JOptionPane.OK_OPTION)
                                return;

                            try {
                                long layerId = (long) ((StringLabeller) layerSelector.getSelectedItem())
                                        .getObject();
                                NetworkLayer layer = netPlan.getNetworkLayerFromId(layerId);
                                for (MulticastDemand demand : visibleRows)
                                    if (!demand.isCoupled())
                                        demand.coupleToNewLinksCreated(layer);
                                callback.getVisualizationState()
                                        .recomputeCanvasTopologyBecauseOfLinkOrNodeAdditionsOrRemovals();
                                callback.updateVisualizationAfterChanges(Sets.newHashSet(
                                        NetworkElementType.MULTICAST_DEMAND, NetworkElementType.LINK));
                                callback.getUndoRedoNavigationManager().addNetPlanChange();
                                break;
                            } catch (Throwable ex) {
                                ErrorHandling.showErrorDialog(ex.getMessage(),
                                        "Error creating upper layer links");
                            }
                        }
                    }
                });
            }

            if (!options.isEmpty()
                    && (decoupleAllDemandsItem != null || createUpperLayerLinksFromDemandsItem != null)) {
                options.add(new JPopupMenu.Separator());
                if (decoupleAllDemandsItem != null)
                    options.add(decoupleAllDemandsItem);
                if (createUpperLayerLinksFromDemandsItem != null)
                    options.add(createUpperLayerLinksFromDemandsItem);
            }

        }
    }

    return options;
}

From source file:com.diversityarrays.kdxplore.curate.SampleEntryPanel.java

private void doRepopulateStatsControls() {
    for (StatType statType : StatType.values()) {
        Object statValue = statType.getStatValue(kdsmartSampleStatistics);

        statButtonByStatType.get(statType).setEnabled(statValue != null);

        Component component = statComponentByStatType.get(statType);
        if (statType != StatType.MODE) {
            component.setEnabled(statValue != null);
            ((JButton) component).setText(statValue == null ? "" : statValue.toString()); //$NON-NLS-1$
        } else {//from   ww w  .  jav a  2  s.co  m
            @SuppressWarnings("unchecked")
            JComboBox<String> comboBox = (JComboBox<String>) component;

            comboBox.removeAllItems();
            String[] modesArray = (String.valueOf(statValue)).split(",", -1); //$NON-NLS-1$
            List<String> modes = Arrays.asList(modesArray);
            if (modes.size() > 1) {
                comboBox.setEnabled(true);
                for (String s : modes) {
                    if (s.trim() != null) {
                        comboBox.addItem(s.trim());
                    }
                }
            } else {
                comboBox.setEnabled(true);
                comboBox.addItem(String.valueOf(statValue));
            }
        }
    }
}

From source file:net.sf.mzmine.modules.visualization.spectra.SpectraVisualizerWindow.java

public void loadRawData(Scan scan) {

    logger.finest("Loading scan #" + scan.getScanNumber() + " from " + dataFile + " for spectra visualizer");

    spectrumDataSet = new ScanDataSet(scan);

    this.currentScan = scan;

    // If the plot mode has not been set yet, set it accordingly
    if (spectrumPlot.getPlotMode() == null) {
        if (currentScan.isCentroided()) {
            spectrumPlot.setPlotMode(PlotMode.CENTROID);
            toolBar.setCentroidButton(false);
        } else {//w w  w .  ja v  a 2  s  .  co m
            spectrumPlot.setPlotMode(PlotMode.CONTINUOUS);
            toolBar.setCentroidButton(true);
        }
    }

    // Clean up the MS/MS selector combo

    final JComboBox msmsSelector = bottomPanel.getMSMSSelector();

    // We disable the MSMS selector first and then enable it again later
    // after updating the items. If we skip this, the size of the
    // selector may not be adjusted properly (timing issues?)
    msmsSelector.setEnabled(false);

    msmsSelector.removeAllItems();
    boolean msmsVisible = false;

    // Add parent scan to MS/MS selector combo

    NumberFormat rtFormat = MZmineCore.getConfiguration().getRTFormat();
    NumberFormat mzFormat = MZmineCore.getConfiguration().getMZFormat();
    NumberFormat intensityFormat = MZmineCore.getConfiguration().getIntensityFormat();

    int parentNumber = currentScan.getParentScanNumber();
    if ((currentScan.getMSLevel() > 1) && (parentNumber > 0)) {

        Scan parentScan = dataFile.getScan(parentNumber);
        if (parentScan != null) {
            String itemText = "Parent scan #" + parentNumber + ", RT: "
                    + rtFormat.format(parentScan.getRetentionTime()) + ", precursor m/z: "
                    + mzFormat.format(currentScan.getPrecursorMZ());

            if (currentScan.getPrecursorCharge() > 0)
                itemText += " (chrg " + currentScan.getPrecursorCharge() + ")";

            msmsSelector.addItem(itemText);
            msmsVisible = true;
        }
    }

    // Add all fragment scans to MS/MS selector combo
    int fragmentScans[] = currentScan.getFragmentScanNumbers();
    if (fragmentScans != null) {
        for (int fragment : fragmentScans) {
            Scan fragmentScan = dataFile.getScan(fragment);
            if (fragmentScan == null)
                continue;
            final String itemText = "Fragment scan #" + fragment + ", RT: "
                    + rtFormat.format(fragmentScan.getRetentionTime()) + ", precursor m/z: "
                    + mzFormat.format(fragmentScan.getPrecursorMZ());
            // Updating the combo in other than Swing thread may cause
            // exception
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    msmsSelector.addItem(itemText);
                }
            });
            msmsVisible = true;
        }
    }

    msmsSelector.setEnabled(true);

    // Update the visibility of MS/MS selection combo
    bottomPanel.setMSMSSelectorVisible(msmsVisible);

    // Set window and plot titles

    String title = "[" + dataFile.getName() + "] scan #" + currentScan.getScanNumber();

    String subTitle = "MS" + currentScan.getMSLevel();

    if (currentScan.getMSLevel() > 1) {
        subTitle += " (" + mzFormat.format(currentScan.getPrecursorMZ()) + " precursor m/z)";
    }

    subTitle += ", RT " + rtFormat.format(currentScan.getRetentionTime());

    DataPoint basePeak = currentScan.getHighestDataPoint();
    if (basePeak != null) {
        subTitle += ", base peak: " + mzFormat.format(basePeak.getMZ()) + " m/z ("
                + intensityFormat.format(basePeak.getIntensity()) + ")";
    }

    setTitle(title);
    spectrumPlot.setTitle(title, subTitle);

    // Set plot data set
    spectrumPlot.removeAllDataSets();
    spectrumPlot.addDataSet(spectrumDataSet, scanColor, false);

    // Reload peak list
    bottomPanel.rebuildPeakListSelector();

}

From source file:edu.ku.brc.specify.prefs.FormattingPrefsPanel.java

/**
 * Create the UI for the panel// w w w.j  a v  a  2 s .c o m
 */
protected void createUI() {
    createForm("Preferences", "Formatting"); //$NON-NLS-1$ //$NON-NLS-2$

    UIValidator.setIgnoreAllValidation(this, true);

    JLabel fontNamesLabel = form.getLabelFor("fontNames"); //$NON-NLS-1$
    ValComboBox fontNamesVCB = form.getCompById("fontNames"); //$NON-NLS-1$

    JLabel fontSizesLabel = form.getLabelFor("fontSizes"); //$NON-NLS-1$
    ValComboBox fontSizesVCB = form.getCompById("fontSizes"); //$NON-NLS-1$

    JLabel controlSizesLabel = form.getLabelFor("controlSizes"); //$NON-NLS-1$
    ValComboBox controlSizesVCB = form.getCompById("controlSizes"); //$NON-NLS-1$

    formTypesCBX = form.getCompById("formtype"); //$NON-NLS-1$

    fontNames = fontNamesVCB.getComboBox();
    fontSizes = fontSizesVCB.getComboBox();
    controlSizes = controlSizesVCB.getComboBox();

    testField = form.getCompById("fontTest"); //$NON-NLS-1$
    if (testField != null) {
        testField.setText(UIRegistry.getResourceString("FormattingPrefsPanel.THIS_TEST")); //$NON-NLS-1$
    }
    if (UIHelper.isMacOS_10_5_X()) {
        fontNamesLabel.setVisible(false);
        fontNamesVCB.setVisible(false);
        fontSizesLabel.setVisible(false);
        fontSizesVCB.setVisible(false);
        testField.setVisible(false);

        int inx = -1;
        int i = 0;
        Vector<String> controlSizeTitles = new Vector<String>();
        for (UIHelper.CONTROLSIZE cs : UIHelper.CONTROLSIZE.values()) {
            String titleStr = getResourceString(cs.toString());
            controlSizeTitles.add(titleStr);
            controlSizesHash.put(titleStr, cs);
            controlSizes.addItem(titleStr);
            if (cs == UIHelper.getControlSize()) {
                inx = i;
            }
            i++;
        }
        controlSizes.setSelectedIndex(inx);

        Font baseFont = UIRegistry.getBaseFont();
        if (baseFont != null) {
            fontNames.addItem(baseFont.getFamily());
            fontSizes.addItem(Integer.toString(baseFont.getSize()));
            fontNames.setSelectedIndex(0);
            fontSizes.setSelectedIndex(0);
        }

    } else {
        controlSizesLabel.setVisible(false);
        controlSizesVCB.setVisible(false);

        Hashtable<String, Boolean> namesUsed = new Hashtable<String, Boolean>();
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        for (Font font : ge.getAllFonts()) {
            if (namesUsed.get(font.getFamily()) == null) {
                fontNames.addItem(font.getFamily());
                namesUsed.put(font.getFamily(), true); //$NON-NLS-1$
            }
        }
        for (int i = BASE_FONT_SIZE; i < 22; i++) {
            fontSizes.addItem(Integer.toString(i));
        }

        Font baseFont = UIRegistry.getBaseFont();
        if (baseFont != null) {
            fontNames.setSelectedItem(baseFont.getFamily());
            fontSizes.setSelectedItem(Integer.toString(baseFont.getSize()));

            if (testField != null) {
                ActionListener al = new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        testField.setFont(new Font((String) fontNames.getSelectedItem(), Font.PLAIN,
                                fontSizes.getSelectedIndex() + BASE_FONT_SIZE));
                        form.getUIComponent().validate();
                        clearFontSettings = false;
                    }
                };
                fontNames.addActionListener(al);
                fontSizes.addActionListener(al);
            }
        }
    }

    //-----------------------------------
    // Do DisciplineType Icons
    //-----------------------------------

    String iconName = AppPreferences.getRemote().get(getDisciplineImageName(), "CollectionObject"); //$NON-NLS-1$ //$NON-NLS-2$

    List<Pair<String, ImageIcon>> list = IconManager.getListByType("disciplines", IconManager.IconSize.Std16); //$NON-NLS-1$
    Collections.sort(list, new Comparator<Pair<String, ImageIcon>>() {
        public int compare(Pair<String, ImageIcon> o1, Pair<String, ImageIcon> o2) {
            String s1 = UIRegistry.getResourceString(o1.first);
            String s2 = UIRegistry.getResourceString(o2.first);
            return s1.compareTo(s2);
        }
    });

    disciplineCBX = (ValComboBox) form.getCompById("disciplineIconCBX"); //$NON-NLS-1$

    final JLabel dispLabel = form.getCompById("disciplineIcon"); //$NON-NLS-1$
    JComboBox comboBox = disciplineCBX.getComboBox();
    comboBox.setRenderer(new DefaultListCellRenderer() {
        @SuppressWarnings("unchecked") //$NON-NLS-1$
        public Component getListCellRendererComponent(JList listArg, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {
            Pair<String, ImageIcon> item = (Pair<String, ImageIcon>) value;
            JLabel label = (JLabel) super.getListCellRendererComponent(listArg, value, index, isSelected,
                    cellHasFocus);
            if (item != null) {
                label.setIcon(item.second);
                label.setText(UIRegistry.getResourceString(item.first));
            }
            return label;
        }
    });

    int inx = 0;
    Pair<String, ImageIcon> colObj = new Pair<String, ImageIcon>("colobj_backstop", //$NON-NLS-1$
            IconManager.getIcon("colobj_backstop", IconManager.IconSize.Std16)); //$NON-NLS-1$
    comboBox.addItem(colObj);

    int cnt = 1;
    for (Pair<String, ImageIcon> item : list) {
        if (item.first.equals(iconName)) {
            inx = cnt;
        }
        comboBox.addItem(item);
        cnt++;
    }

    comboBox.addActionListener(new ActionListener() {
        @SuppressWarnings("unchecked") //$NON-NLS-1$
        public void actionPerformed(ActionEvent e) {
            JComboBox cbx = (JComboBox) e.getSource();
            Pair<String, ImageIcon> item = (Pair<String, ImageIcon>) cbx.getSelectedItem();
            if (item != null) {
                dispLabel.setIcon(IconManager.getIcon(item.first));
                form.getUIComponent().validate();
            }
        }
    });

    comboBox.setSelectedIndex(inx);

    //-----------------------------------
    // Date Field
    //-----------------------------------
    dateFieldCBX = form.getCompById("scrdateformat"); //$NON-NLS-1$
    fillDateFormat();

    //-----------------------------------
    // FormType
    //-----------------------------------
    fillFormTypes();

    //-----------------------------------
    // Do App Icon
    //-----------------------------------

    final JButton getIconBtn = form.getCompById("GetIconImage"); //$NON-NLS-1$
    final JButton clearIconBtn = form.getCompById("ClearIconImage"); //$NON-NLS-1$
    final JLabel appLabel = form.getCompById("appIcon"); //$NON-NLS-1$
    final JButton resetDefFontBtn = form.getCompById("ResetDefFontBtn"); //$NON-NLS-1$

    String imgEncoded = AppPreferences.getRemote().get(iconImagePrefName, ""); //$NON-NLS-1$
    ImageIcon innerAppImgIcon = null;
    if (StringUtils.isNotEmpty(imgEncoded)) {
        innerAppImgIcon = GraphicsUtils.uudecodeImage("", imgEncoded); //$NON-NLS-1$
        if (innerAppImgIcon != null && innerAppImgIcon.getIconWidth() != 32
                || innerAppImgIcon.getIconHeight() != 32) {
            innerAppImgIcon = null;
            clearIconBtn.setEnabled(false);
        } else {
            clearIconBtn.setEnabled(true);
        }
    }

    if (innerAppImgIcon == null) {
        innerAppImgIcon = IconManager.getIcon("AppIcon"); //$NON-NLS-1$
        clearIconBtn.setEnabled(false);
    } else {
        clearIconBtn.setEnabled(true);
    }
    appLabel.setIcon(innerAppImgIcon);

    getIconBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            chooseToolbarIcon(appLabel, clearIconBtn);
        }
    });

    clearIconBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ImageIcon appIcon = IconManager.getIcon("AppIcon");
            IconEntry entry = IconManager.getIconEntryByName(INNER_APPICON_NAME);
            entry.setIcon(appIcon);
            if (entry.getIcons().get(IconManager.IconSize.Std32) != null) {
                entry.getIcons().get(IconManager.IconSize.Std32).setImageIcon(appIcon);
            }

            appLabel.setIcon(IconManager.getIcon("AppIcon")); //$NON-NLS-1$
            clearIconBtn.setEnabled(false);
            AppPreferences.getRemote().remove(iconImagePrefName);
            form.getValidator().dataChanged(null, null, null);
        }
    });

    resetDefFontBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Font sysDefFont = UIRegistry.getDefaultFont();
            ComboBoxModel model = fontNames.getModel();
            for (int i = 0; i < model.getSize(); i++) {
                //System.out.println("["+model.getElementAt(i).toString()+"]["+sysDefFont.getFamily()+"]");
                if (model.getElementAt(i).toString().equals(sysDefFont.getFamily())) {
                    fontNames.setSelectedIndex(i);
                    clearFontSettings = true;
                    break;
                }
            }

            if (clearFontSettings) {
                fontSizes.setSelectedIndex(sysDefFont.getSize() - BASE_FONT_SIZE);
                clearFontSettings = true; // needs to be redone 
            }

            form.getValidator().dataChanged(null, null, null);
        }
    });

    //-----------------------------------
    // Do Banner Icon Size
    //-----------------------------------

    String fmtStr = "%d x %d pixels";//getResourceString("BNR_ICON_SIZE");
    bnrIconSizeCBX = form.getCompById("bnrIconSizeCBX"); //$NON-NLS-1$

    int size = AppPreferences.getLocalPrefs().getInt(BNR_ICON_SIZE, 20);
    inx = 0;
    cnt = 0;
    for (int pixelSize : pixelSizes) {
        ((DefaultComboBoxModel) bnrIconSizeCBX.getModel())
                .addElement(String.format(fmtStr, pixelSize, pixelSize));
        if (pixelSize == size) {
            inx = cnt;
        }
        cnt++;
    }

    bnrIconSizeCBX.getComboBox().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            form.getUIComponent().validate();
        }
    });

    bnrIconSizeCBX.getComboBox().setSelectedIndex(inx);

    UIValidator.setIgnoreAllValidation(this, false);
    fontNamesVCB.setChanged(false);
    fontSizesVCB.setChanged(false);

    form.getValidator().validateForm();
}

From source file:grupob.TipoProceso.java

public TipoProceso() {
    initComponents();/*  w  w  w  .j ava 2 s  . c o  m*/
    initInstitucional();
    //        listaRegiones.add(new Region(1,"Lima",15000));
    //        listaRegiones.add(new Region(1,"Arequipa",10000));
    //        listaRegiones.add(new Region(1,"Junin",12000));
    TipoProcesoVotacion tipoNacional = Manager.queryProcesoById(1);
    TipoProcesoVotacion tipoRegional = Manager.queryProcesoById(2);
    TipoProcesoVotacion tipoDistrital = Manager.queryProcesoById(3);
    Calendar cal = Calendar.getInstance();
    Date dateActual = cal.getTime();
    textConfGeneral.setText(Recorte.rutaGeneral);
    textConfHuellas.setText(Recorte.rutaHuella);
    textConfFirmas.setText(Recorte.rutaFirma);
    /*
    Recorte.rutaGeneral = FramePrincipal.rutaGeneral;
    Recorte.rutaHuella = FramePrincipal.rutaHuella;
    Recorte.rutaFirma = FramePrincipal.rutaFirma;*/

    if (tipoNacional != null && tipoNacional.getId() != 0) {
        if (!tipoNacional.getFechaInicio2().after(dateActual)) {
            fechai1Nacional.setDate(tipoNacional.getFechaInicio1().getTime());
            fechai2Nacional.setDate(tipoNacional.getFechaInicio2().getTime());
            fechaf1Nacional.setDate(tipoNacional.getFechaFin1().getTime());
            fechaf2Nacional.setDate(tipoNacional.getFechaFin2().getTime());
        }
        if ((tipoNacional.getFechaInicio1().before(dateActual)) && (cal.before(tipoNacional.getFechaFin2()))) {
            botonGuardarNacional.setEnabled(false);
        }
        if (tipoNacional.getFechaFin2().before(dateActual)) {
            botonGuardarNacional.setEnabled(true);
        }
    }
    if (tipoRegional != null && tipoRegional.getId() != 0) {
        if (!tipoRegional.getFechaInicio2().after(dateActual)) {
            fechai1Regiones.setDate(tipoRegional.getFechaInicio1().getTime());
            fechai2Regiones.setDate(tipoRegional.getFechaInicio2().getTime());
            fechaf1Regiones.setDate(tipoRegional.getFechaFin1().getTime());
            fechaf2Regiones.setDate(tipoRegional.getFechaFin2().getTime());
            porcentajeRegional.setText("" + tipoRegional.getPorcentajeMinimo() * 100);
        }
        if ((tipoRegional.getFechaInicio1().before(dateActual)) && (cal.before(tipoRegional.getFechaFin2()))) {
            botonGuardarRegional.setEnabled(false);
        }
        if (tipoRegional.getFechaFin2().before(dateActual)) {
            botonGuardarRegional.setEnabled(true);
        }
    }
    if (tipoDistrital != null && tipoDistrital.getId() != 0) {
        if (!tipoRegional.getFechaInicio2().after(dateActual)) {
            fechai1Distritos.setDate(tipoDistrital.getFechaInicio1().getTime());
            fechai2Distritos.setDate(tipoDistrital.getFechaInicio2().getTime());
            fechaf1Distritos.setDate(tipoDistrital.getFechaFin1().getTime());
            fechaf2Distritos.setDate(tipoDistrital.getFechaFin2().getTime());
            porcentajeDistrital.setText("" + tipoDistrital.getPorcentajeMinimo() * 100);
        }
        if ((tipoDistrital.getFechaInicio1().before(dateActual))
                && (cal.before(tipoDistrital.getFechaFin2()))) {
            botonGuardarDistrital.setEnabled(false);
            //                addRowRegional.setEnabled(false);
            //                jTable6.setEnabled(false);
        }
        if (tipoDistrital.getFechaFin2().before(dateActual)) {
            botonGuardarDistrital.setEnabled(true);
            //                addRowRegional.setEnabled(true);
        }
    }
    agregarDatos();
    agregarDatosDistritos();
    if (listaRegiones != null) {
        jTableRegiones.getColumn("Eliminar").setCellRenderer(new ButtonRenderer());
        jTableRegiones.getColumn("Eliminar").setCellEditor(new botonEliminarRegiones());
    }
    if (listaDistritos != null) {
        jTableDistritos.getColumn("Eliminar").setCellRenderer(new ButtonRenderer());
        jTableDistritos.getColumn("Eliminar").setCellEditor(new botonEliminarDistritos());
    }

    TableColumn sColumn = jTableDistritos.getColumnModel().getColumn(2);
    ArrayList<Region> lReg = Manager.queryAllRegion();
    JComboBox comboBox = new JComboBox();
    for (int i = 0; i < lReg.size(); i++) {
        comboBox.addItem(lReg.get(i).getNombre());
    }
    sColumn.setCellEditor(new DefaultCellEditor(comboBox));

    TableColumn instColumn = tblInstitucional.getColumnModel().getColumn(2);
    ArrayList<Local> lLoc = Manager.queryAllLocales();
    JComboBox comboBoxLocal = new JComboBox();
    for (int i = 0; i < lLoc.size(); i++) {
        comboBoxLocal.addItem(lLoc.get(i).getNombre());
    }
    instColumn.setCellEditor(new DefaultCellEditor(comboBoxLocal));

    ChangeListener changeListener = new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {

            JTabbedPane sourceTabbedPane = (JTabbedPane) e.getSource();
            int index = sourceTabbedPane.getSelectedIndex();
            switch (index) {
            case 3:
                cargarDatosLocal();
                return;

            default:
                return;
            }

        }
    };

    jconfiguracion.addChangeListener(changeListener);

}