Example usage for javax.swing JComboBox setSelectedIndex

List of usage examples for javax.swing JComboBox setSelectedIndex

Introduction

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

Prototype

@BeanProperty(bound = false, preferred = true, description = "The item at index is selected.")
public void setSelectedIndex(int anIndex) 

Source Link

Document

Selects the item at index anIndex.

Usage

From source file:eu.apenet.dpt.standalone.gui.eaccpf.EacCpfControlPanel.java

private PanelBuilder buildMainPanel(PanelBuilder builder, CellConstraints cc) {

    JLabel jLabelIdInTheApeEACCPF = new JLabel(this.labels.getString("eaccpf.control.idintheapeeaccpf"));
    builder.add(jLabelIdInTheApeEACCPF, cc.xy(1, rowNb));
    //extracted from dashboard implementation
    Random random = new Random();
    String value = "";
    //      String mainagencycode = (this.eaccpf.getControl().getMaintenanceAgency().getAgencyCode()!=null && this.eaccpf.getControl().getMaintenanceAgency().getAgencyCode().getValue()!=null )?this.eaccpf.getControl().getMaintenanceAgency().getAgencyCode().getValue():"";
    if (this.eaccpf.getControl().getRecordId().getValue() == null
            || this.eaccpf.getControl().getRecordId().getValue().isEmpty()) {
        int fakeId = random.nextInt(1000000000);
        value = Integer.toString(fakeId);
        //         value = "eac_" + mainagencycode + "_" + Integer.toString(fakeId);
    } else {/*from   w w  w.  j a v  a  2 s .c  o  m*/
        value = this.eaccpf.getControl().getRecordId().getValue();
    }
    JTextField jTextFieldIdInTheApeEACCPF = new JTextField(value);
    jTextFieldIdInTheApeEACCPF.setEnabled(false); //put like disabled, it's not editable
    builder.add(jTextFieldIdInTheApeEACCPF, cc.xy(3, rowNb));
    this.idAutogeneratedControl = jTextFieldIdInTheApeEACCPF.getText(); //It's not shown because field is autogenerated and it's not editabled (eaccpf object has no access to this value by form)
    setNextRow();

    JLabel jLabelLinkPersonResponsible = new JLabel(
            this.labels.getString("eaccpf.control.personinstitutionresponsiblefordescription"));
    builder.add(jLabelLinkPersonResponsible, cc.xy(1, rowNb));
    String content = "";
    if (StringUtils.isNotEmpty(responsible)) {
        content = responsible;
    } else if (this.eaccpf.getControl().getMaintenanceHistory().getMaintenanceEvent().size() > 0
            && this.eaccpf.getControl().getMaintenanceHistory().getMaintenanceEvent()
                    .get(this.eaccpf.getControl().getMaintenanceHistory().getMaintenanceEvent().size() - 1)
                    .getAgent() != null
            && this.eaccpf.getControl().getMaintenanceHistory().getMaintenanceEvent()
                    .get(this.eaccpf.getControl().getMaintenanceHistory().getMaintenanceEvent().size() - 1)
                    .getAgent().getContent() != null
            && !this.eaccpf.getControl().getMaintenanceHistory().getMaintenanceEvent()
                    .get(this.eaccpf.getControl().getMaintenanceHistory().getMaintenanceEvent().size() - 1)
                    .getAgent().getContent().isEmpty()) {
        content = this.eaccpf.getControl().getMaintenanceHistory().getMaintenanceEvent()
                .get(this.eaccpf.getControl().getMaintenanceHistory().getMaintenanceEvent().size() - 1)
                .getAgent().getContent();
    } else {
        content = MAINTENANCE_AGENT_HUMAN;
    }

    JTextField jTextFieldPersonResponsible = new JTextField(content);
    builder.add(jTextFieldPersonResponsible, cc.xy(3, rowNb));
    this.personInstitutionResponsibleTextField = jTextFieldPersonResponsible;
    setNextRow();
    JLabel jLabelIdentifierForPersonResponsible = new JLabel(
            this.labels.getString("eaccpf.control.identifierofinstitutionresponsible") + "*");
    builder.add(jLabelIdentifierForPersonResponsible, cc.xy(1, rowNb));
    content = eaccpf.getControl().getMaintenanceAgency().getAgencyCode().getValue() != null
            ? eaccpf.getControl().getMaintenanceAgency().getAgencyCode().getValue()
            : "";
    JTextField jTextFieldIdentifierForPersonResponsible = new JTextField(content);
    builder.add(jTextFieldIdentifierForPersonResponsible, cc.xy(3, rowNb));
    this.idControl = jTextFieldIdentifierForPersonResponsible;
    setNextRow();

    if (StringUtils.isEmpty(content)) {
        builder.add(createErrorLabel(this.labels.getString("eaccpf.control.error.emptyidentifier")),
                cc.xyw(1, this.rowNb, 3));
        setNextRow();
    }
    if (this.eaccpf.getControl().getOtherRecordId().isEmpty()) {
        OtherRecordId newOtherRecordId = new OtherRecordId();
        newOtherRecordId.setLocalType(EacCpfPanel.LOCAL_TYPE_ORIGINAL);
        this.eaccpf.getControl().getOtherRecordId().add(newOtherRecordId);
    }

    List<OtherRecordId> otherRecordIds = this.eaccpf.getControl().getOtherRecordId();

    this.localIdentifierForInstitution = new ArrayList<JTextField>(otherRecordIds.size());
    this.listIdentifierType = new ArrayList<JTextField>(otherRecordIds.size());

    for (OtherRecordId otherRecordId : otherRecordIds) {
        // Create element.
        JTextField jTextFieldLocalIdentifierPersonResponsible = new JTextField(otherRecordId.getContent());
        JTextField jTextFieldIdentifierType = new JTextField(otherRecordId.getLocalType());

        // Add elements to the list.
        this.localIdentifierForInstitution.add(jTextFieldLocalIdentifierPersonResponsible);
        this.listIdentifierType.add(jTextFieldIdentifierType);
        builder.addLabel(this.labels.getString("eaccpf.control.otherRecordIdentifier"), cc.xy(1, this.rowNb));
        builder.add(jTextFieldLocalIdentifierPersonResponsible, cc.xy(3, this.rowNb));
        this.setNextRow();
    }

    JButton nextTabBtn = new ButtonTab(this.labels.getString("eaccpf.control.addlocalidentifier"));
    builder.add(nextTabBtn, cc.xy(1, this.rowNb));
    nextTabBtn.addActionListener(new AddLocalIdentifier(eaccpf, tabbedPane, model));
    setNextRow();

    builder.addLabel(this.labels.getString("eaccpf.control.usedlanguagesandscriptsfordescription"),
            cc.xyw(1, this.rowNb, 7));
    setNextRow();

    builder.addLabel(labels.getString("eaccpf.commons.select.language") + "*" + ":", cc.xy(1, rowNb));
    LanguageWithScript languageWithScript = new LanguageWithScript(firstLanguage, firstScript, labels);
    JComboBox<String> scriptBox = languageWithScript.getScriptBox();
    //fix for script part, it's not selecting values
    boolean found = false;
    int size = scriptBox.getModel().getSize();
    for (int i = 0; !found && i < size; i++) {
        String element = scriptBox.getModel().getElementAt(i);
        if (element != null && element.equalsIgnoreCase(firstScript)) {
            scriptBox.setSelectedIndex(i);
            found = true;
        }
    }
    //end fix for script part
    builder.add(languageWithScript.getLanguageBox(), cc.xy(3, rowNb));
    this.languageFirst = languageWithScript.getLanguageBox();
    builder.addLabel(labels.getString("eaccpf.control.selectascript") + "*" + ":", cc.xy(5, rowNb));
    builder.add(languageWithScript.getScriptBox(), cc.xy(7, rowNb));
    this.scriptFirst = languageWithScript.getScriptBox();
    this.languageWithScript = languageWithScript;
    setNextRow();

    return builder;
}

From source file:ec.util.chart.swing.JTimeSeriesRendererSupportDemo.java

private Component createToolBar() {
    JToolBar result = new JToolBar();
    result.setFloatable(false);// w ww.  j a v a 2  s.  c o m

    result.add(RANDOM_DATA.toAction(chart)).setIcon(FontAwesome.FA_RANDOM.getIcon(getForeground(), 16f));

    JComboBox<RendererType> types = new JComboBox<>(
            support.getSupportedRendererTypes().toArray(new RendererType[0]));
    types.setMaximumSize(new Dimension(150, 100));
    types.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            RendererType type = (RendererType) e.getItem();
            chart.getXYPlot().setRenderer(support.createRenderer(type));
            chart.getXYPlot().setBackgroundPaint(support.getPlotColor());
            chart.setBackgroundPaint(colorSchemeSupport.getBackColor());
        }
    });
    types.setSelectedIndex(1);
    result.add(types);

    return result;
}

From source file:main.UIController.java

/******** FROM GREGORIAN **********/

public void updateDayComboGregorian() {
    UI window = this.getUi();

    JTextField year = window.getYear();
    JComboBox month = window.getMonth();
    JComboBox day = window.getDay();
    JButton convert = window.getToImladris();
    JTextPane result = window.getResImladris();
    String value = year.getText();
    if (!value.isEmpty()) {
        try {/*  w w w.j  a va2  s  .c o  m*/
            int yearNum = Integer.parseInt(value);
            if (yearNum > 0 && yearNum <= GregorianInfo.MAX_SUPPORTED_YEAR) {
                int monthNum = month.getSelectedIndex() + 1;
                int daySel = 0;
                if (day.isEnabled()) {
                    daySel = day.getSelectedIndex() + 1;
                }
                ArrayList<Integer> days = GregorianInfo.getInstance().getDaysArray(yearNum, monthNum);
                day.setModel(new DefaultComboBoxModel(days.toArray()));
                if (daySel > 0 && daySel <= days.size()) {
                    day.setSelectedIndex(daySel - 1);
                }
                day.setEnabled(true);
                convert.setEnabled(true);
                result.setText("");
            } else {
                day.setEnabled(false);
                convert.setEnabled(false);
                day.setModel(new DefaultComboBoxModel());
                result.setText("");
            }
        } catch (NumberFormatException e) {
            day.setEnabled(false);
            convert.setEnabled(false);
            day.setModel(new DefaultComboBoxModel());
            result.setText("");
        }
    } else {
        day.setEnabled(false);
        convert.setEnabled(false);
        day.setModel(new DefaultComboBoxModel());
        result.setText("");
    }
}

From source file:geovista.network.gui.NodeLinkView.java

protected void addControls(final JPanel jp) {

    // Satellite/*  ww  w .  j  av a  2  s  . c om*/
    // JComboBox modeBox = graphMouse.getModeComboBox();
    // modeBox.addItemListener(((DefaultModalGraphMouse)satellite.getGraphMouse()).getModeListener());

    // Control Panel
    jp.setBackground(Color.WHITE);
    jp.setLayout(new BorderLayout());
    jp.add(vv, BorderLayout.CENTER);
    JPanel control_panel = new JPanel(new GridLayout(5, 1));
    jp.add(control_panel, BorderLayout.EAST);

    // File_Layout Panel
    Class[] combos = getCombos();
    final JComboBox jcb = new JComboBox(combos);
    jcb.setRenderer(new DefaultListCellRenderer() {
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            String valueString = value.toString();
            valueString = valueString.substring(valueString.lastIndexOf('.') + 1);
            return super.getListCellRendererComponent(list, valueString, index, isSelected, cellHasFocus);
        }
    });

    jcb.addActionListener(new LayoutChooser(jcb, vv));
    jcb.setSelectedItem(FRLayout.class);
    final Box file_layout_panel = Box.createVerticalBox();
    file_layout_panel.setBorder(BorderFactory.createTitledBorder("File_Layout"));
    final JComboBox graph_chooser = new JComboBox(g_names);
    graph_chooser.addActionListener(new GraphChooser(jcb));
    JPanel layoutPanel = new JPanel();
    jcb.setAlignmentX(Component.CENTER_ALIGNMENT);
    layoutPanel.add(jcb);
    graph_chooser.setAlignmentX(Component.CENTER_ALIGNMENT);
    layoutPanel.add(graph_chooser);
    file_layout_panel.add(layoutPanel);

    // Basic Operation Panel

    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());
        }
    });
    JButton reset = new JButton("reset");
    reset.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Layout<Integer, Number> layout = vv.getGraphLayout();
            layout.initialize();
            Relaxer relaxer = vv.getModel().getRelaxer();
            if (relaxer != null) {
                relaxer.stop();
                relaxer.prerelax();
                relaxer.relax();
            }
        }
    });

    // Tranform and picking part
    final DefaultModalGraphMouse<Integer, Number> graphMouse = new DefaultModalGraphMouse<Integer, Number>();
    vv.setGraphMouse(graphMouse);
    JComboBox modeBox = graphMouse.getModeComboBox();
    modeBox.addItemListener(((DefaultModalGraphMouse<Integer, Number>) vv.getGraphMouse()).getModeListener());

    JButton collapse = new JButton("Collapse");
    JButton expand = new JButton("Expand");

    final Box basic_panel = Box.createVerticalBox();
    basic_panel.setBorder(BorderFactory.createTitledBorder("Basic_Operation"));
    JPanel zoomPanel = new JPanel();
    // plus.setAlignmentX(Component.CENTER_ALIGNMENT);
    zoomPanel.add(plus);
    // minus.setAlignmentX(Component.CENTER_ALIGNMENT);
    zoomPanel.add(minus);
    // modeBox.setAlignmentX(Component.CENTER_ALIGNMENT);
    zoomPanel.add(modeBox);
    // reset.setAlignmentX(Component.CENTER_ALIGNMENT);
    zoomPanel.add(reset);
    // collapse.setAlignmentY(Component.CENTER_ALIGNMENT);
    zoomPanel.add(collapse);
    // expand.setAlignmentY(Component.CENTER_ALIGNMENT);
    zoomPanel.add(expand);

    basic_panel.add(zoomPanel);

    // Vertex Part
    String[] vertexScoreType = { "VertexScore", "Degree", "BarycenterScorer", "BetweennessCentrality",
            "ClosenessCentrality", "DistanceCentralityScorer", "EigenvectorCentrality" };
    final JComboBox vertexScoreList = new JComboBox(vertexScoreType);
    vertexScoreList.setSelectedIndex(0);

    vertexScoreList.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            // Renderer.VertexLabel.Position position =
            // (Renderer.VertexLabel.Position)e.getItem();
            // vv.getRenderer().getVertexLabelRenderer().setPosition(position);
            if (vertexScoreList.getSelectedIndex() == 0) {

                // vertexScores = new VertexScoreTransformer<Integer,
                // Double>(voltage_scores);
                // vv.getRenderContext().setVertexShapeTransformer(new
                // ConstantTransformer(null));
                // vssa.setScaling(false);
                vv.getRenderContext().setVertexLabelTransformer(nonvertexLabel);
                vv.repaint();
            }

            if (vertexScoreList.getSelectedIndex() == 1) {
                // vertexScores = new VertexScoreTransformer<Integer,
                // Double>(degreeScorer);
                /*
                 * vssa = new
                 * VertexShapeSizeAspect<Integer,Number>((Graph<Integer
                 * ,Number>)g, transformerDegree);
                 * vv.getRenderContext().setVertexShapeTransformer(vssa);
                 * vssa.setScaling(true);
                 */

                vv.getRenderContext().setVertexLabelTransformer(vertexLabelDegree);
                vv.repaint();
            }
            if (vertexScoreList.getSelectedIndex() == 2) {
                vssa = new VertexShapeSizeAspect<Integer, Number>((Graph<Integer, Number>) g,
                        transformerBarycenter);
                vv.getRenderContext().setVertexShapeTransformer(vssa);
                vssa.setScaling(true);
                vv.getRenderContext().setVertexLabelTransformer(vertexLabelBarycenter);
                vv.repaint();
            }

            if (vertexScoreList.getSelectedIndex() == 3) {

                // betweennessCentrality= new BetweennessCentrality(g);
                // voltages = new VertexScoreTransformer<Integer,
                // Double>(betweennessCentrality);
                vssa = new VertexShapeSizeAspect<Integer, Number>((Graph<Integer, Number>) g,
                        transformerBetweenness);
                vv.getRenderContext().setVertexShapeTransformer(vssa);
                vssa.setScaling(true);
                vv.getRenderContext().setVertexLabelTransformer(vertexLabelBetweenness);
                vv.repaint();
            }
            if (vertexScoreList.getSelectedIndex() == 4) {
                vssa = new VertexShapeSizeAspect<Integer, Number>((Graph<Integer, Number>) g,
                        transformerCloseness);
                vv.getRenderContext().setVertexShapeTransformer(vssa);
                vssa.setScaling(true);
                vv.getRenderContext().setVertexLabelTransformer(vertexLabelCloseness);
                vv.repaint();
            }
            if (vertexScoreList.getSelectedIndex() == 5) {
                vssa = new VertexShapeSizeAspect<Integer, Number>((Graph<Integer, Number>) g,
                        transformerDistanceCentrality);
                vv.getRenderContext().setVertexShapeTransformer(vssa);
                vssa.setScaling(true);
                vv.getRenderContext().setVertexLabelTransformer(vertexLabelDistanceCentrality);
                vv.repaint();
            }
            if (vertexScoreList.getSelectedIndex() == 6) {
                vssa = new VertexShapeSizeAspect<Integer, Number>((Graph<Integer, Number>) g,
                        transformerEigenvector);
                vv.getRenderContext().setVertexShapeTransformer(vssa);
                vssa.setScaling(true);
                vv.getRenderContext().setVertexLabelTransformer(vertexLabelEigenvector);
                vv.repaint();
            }

        }
    });
    // cb.setSelectedItem(Renderer.VertexLabel.Position.SE);

    /*
     * v_shape = new JCheckBox("shape by degree");
     * v_shape.addActionListener(this); v_size = new
     * JCheckBox("size by vertexScores"); 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);
    e_labels = new JCheckBox("show edge labels");
    e_labels.addActionListener(this);

    // Vertex Panel
    final Box vertex_panel = Box.createVerticalBox();
    vertex_panel.setBorder(BorderFactory.createTitledBorder("Vertices"));
    // vertex_panel.add(v_stroke);
    vertex_panel.add(vertexScoreList);
    // vertex_panel.add(v_degree_labels);
    /*
     * vertex_panel.add(v_shape); vertex_panel.add(v_size);
     * vertex_panel.add(v_aspect);
     */
    vertex_panel.add(v_small);

    // Edge Part
    final Box edge_panel = Box.createVerticalBox();
    edge_panel.setBorder(BorderFactory.createTitledBorder("Edges"));
    edge_panel.add(e_labels);

    final JToggleButton groupVertices = new JToggleButton("Group Clusters");
    // Create slider to adjust the number of edges to remove when clustering
    final JSlider edgeBetweennessSlider = new JSlider(JSlider.HORIZONTAL);
    edgeBetweennessSlider.setBackground(Color.WHITE);
    edgeBetweennessSlider.setPreferredSize(new Dimension(210, 50));
    edgeBetweennessSlider.setPaintTicks(true);
    edgeBetweennessSlider.setMaximum(g.getEdgeCount());
    edgeBetweennessSlider.setMinimum(0);
    edgeBetweennessSlider.setValue(0);
    edgeBetweennessSlider.setMajorTickSpacing(10);
    edgeBetweennessSlider.setPaintLabels(true);
    edgeBetweennessSlider.setPaintTicks(true);

    // Cluster Part
    final Box cluster_panel = Box.createVerticalBox();
    cluster_panel.setBorder(BorderFactory.createTitledBorder("Cluster"));
    cluster_panel.add(edgeBetweennessSlider);

    final String COMMANDSTRING = "Edges removed for clusters: ";
    final String eastSize = COMMANDSTRING + edgeBetweennessSlider.getValue();

    final TitledBorder sliderBorder = BorderFactory.createTitledBorder(eastSize);
    cluster_panel.setBorder(sliderBorder);
    cluster_panel.add(Box.createVerticalGlue());
    groupVertices.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            clusterAndRecolor(layout, edgeBetweennessSlider.getValue(), similarColors,
                    e.getStateChange() == ItemEvent.SELECTED);
            vv.repaint();
        }
    });

    clusterAndRecolor(layout, 0, similarColors, groupVertices.isSelected());

    edgeBetweennessSlider.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            JSlider source = (JSlider) e.getSource();
            if (!source.getValueIsAdjusting()) {
                int numEdgesToRemove = source.getValue();
                clusterAndRecolor(layout, numEdgesToRemove, similarColors, groupVertices.isSelected());
                sliderBorder.setTitle(COMMANDSTRING + edgeBetweennessSlider.getValue());
                cluster_panel.repaint();
                vv.validate();
                vv.repaint();
            }
        }
    });
    cluster_panel.add(groupVertices);

    control_panel.add(file_layout_panel);
    control_panel.add(vertex_panel);
    control_panel.add(edge_panel);
    control_panel.add(cluster_panel);
    control_panel.add(basic_panel);
}

From source file:ca.canucksoftware.ipkpackager.IpkPackagerView.java

private void setFlag(javax.swing.JComboBox comboBox, String flag) {
    if (flag.equals("RestartJava")) {
        comboBox.setSelectedIndex(1);
    } else if (flag.equals("RestartLuna")) {
        comboBox.setSelectedIndex(2);/*from   w  w  w  . ja v a  2s .  co  m*/
    } else if (flag.equals("RestartDevice")) {
        comboBox.setSelectedIndex(2);
    } else {
        comboBox.setSelectedIndex(0);
    }
}

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

public static void createLinkDemandGUI(final NetworkElementType networkElementType,
        final IVisualizationCallback callback) {
    final NetPlan netPlan = callback.getDesign();
    final JComboBox originNodeSelector = new WiderJComboBox();
    final JComboBox destinationNodeSelector = new WiderJComboBox();

    for (Node node : netPlan.getNodes()) {
        final String nodeName = node.getName();
        String nodeLabel = "Node " + node.getIndex();
        if (!nodeName.isEmpty())
            nodeLabel += " (" + nodeName + ")";

        originNodeSelector.addItem(StringLabeller.of(node.getId(), nodeLabel));
        destinationNodeSelector.addItem(StringLabeller.of(node.getId(), nodeLabel));
    }/*from  w  w  w  . j  a  va 2s.  c  o  m*/

    ItemListener nodeListener = new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            long originNodeId = (long) ((StringLabeller) originNodeSelector.getSelectedItem()).getObject();
            long destinationNodeId = (long) ((StringLabeller) destinationNodeSelector.getSelectedItem())
                    .getObject();
            callback.putTransientColorInElementTopologyCanvas(
                    Arrays.asList(netPlan.getNodeFromId(originNodeId)), Color.GREEN);
            callback.putTransientColorInElementTopologyCanvas(
                    Arrays.asList(netPlan.getNodeFromId(destinationNodeId)), Color.CYAN);
        }
    };

    originNodeSelector.addItemListener(nodeListener);
    destinationNodeSelector.addItemListener(nodeListener);

    originNodeSelector.setSelectedIndex(0);
    destinationNodeSelector.setSelectedIndex(1);

    JPanel pane = new JPanel();
    pane.add(networkElementType == NetworkElementType.LINK ? new JLabel("Origin node: ")
            : new JLabel("Ingress node: "));
    pane.add(originNodeSelector);
    pane.add(Box.createHorizontalStrut(15));
    pane.add(networkElementType == NetworkElementType.LINK ? new JLabel("Destination node: ")
            : new JLabel("Egress node: "));
    pane.add(destinationNodeSelector);

    while (true) {
        int result = JOptionPane.showConfirmDialog(null, pane,
                "Please enter end nodes for the new " + networkElementType, JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.QUESTION_MESSAGE);
        if (result != JOptionPane.OK_OPTION)
            return;

        try {
            long originNodeId = (long) ((StringLabeller) originNodeSelector.getSelectedItem()).getObject();
            long destinationNodeId = (long) ((StringLabeller) destinationNodeSelector.getSelectedItem())
                    .getObject();
            Node originNode = netPlan.getNodeFromId(originNodeId);
            Node destinationNode = netPlan.getNodeFromId(destinationNodeId);

            if (netPlan.getNodeFromId(originNodeId) == null)
                throw new Net2PlanException("Node of id: " + originNodeId + " does not exist");
            if (netPlan.getNodeFromId(destinationNodeId) == null)
                throw new Net2PlanException("Node of id: " + destinationNodeId + " does not exist");

            if (networkElementType == NetworkElementType.LINK) {
                final Link e = netPlan.addLink(originNode, destinationNode, 0, 0, 200000, null);
                callback.getVisualizationState()
                        .recomputeCanvasTopologyBecauseOfLinkOrNodeAdditionsOrRemovals();
                callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.LINK));
                callback.getVisualizationState().pickLink(e);
                callback.updateVisualizationAfterPick();
                callback.getUndoRedoNavigationManager().addNetPlanChange();

            } else {
                final Demand d = netPlan.addDemand(originNode, destinationNode, 0, null);
                callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND));
                callback.getVisualizationState().pickDemand(d);
                callback.updateVisualizationAfterPick();
                callback.getUndoRedoNavigationManager().addNetPlanChange();
            }

            break;
        } catch (Throwable ex) {
            ErrorHandling.showErrorDialog(ex.getMessage(), "Error adding " + networkElementType);
        }
    }
}

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/*from w w  w.j  a v a2 s  .  c o  m*/
        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:edu.ku.brc.specify.datamodel.busrules.AgentBusRules.java

/**
 * Enables/Disables both the control and the Label
 * @param id the id of the control/*from w  w  w . j av  a2 s.  c  o m*/
 * @param enabled enable it
 * @param value the value it should set
 * @param thisObj the main data object
 */
protected void enableFieldAndLabel(final String id, final boolean enabled, final String value,
        final Agent agent) {
    Component field = formViewObj.getCompById(id);
    if (field != null) {
        field.setEnabled(enabled);

        if (field instanceof TextFieldFromPickListTable) {
            String title = "";
            PickListDBAdapterIFace adaptor = ((TextFieldFromPickListTable) field).getPickListAdapter();
            if (adaptor != null) {
                for (PickListItemIFace pli : adaptor.getList()) {
                    if (pli.getValue().equals(value)) {
                        title = pli.getTitle();
                        break;
                    }
                }
                ((TextFieldFromPickListTable) field).setText(title);
            } else {
                log.error("Adapter was null for id [" + id + "] on the Agent Form.");
            }
            return;
        }

        if (field instanceof JComboBox || field instanceof ValComboBox) {
            JComboBox<?> cbx = field instanceof ValComboBox ? ((ValComboBox) field).getComboBox()
                    : (JComboBox<?>) field;
            int inx = -1;
            if (value != null) {
                AbstractListModel<?> model = (AbstractListModel<?>) cbx.getModel();
                for (int i = 0; i < model.getSize(); i++) {
                    Object item = model.getElementAt(i);
                    if (item instanceof PickListItemIFace) {
                        PickListItemIFace pli = (PickListItemIFace) item;
                        if (pli.getValue().equals(value)) {
                            inx = i;
                            break;
                        }
                    } else if (item.toString().equals(value)) {
                        inx = i;
                        break;
                    }
                }
            }
            //System.err.println("AgentBusRules - id "+id+" setting to "+inx);
            cbx.setSelectedIndex(inx);

        } else if (field instanceof JTextComponent) {
            ((JTextComponent) field).setText(value != null ? value : "");

        } else if (field instanceof PartialDateUI) {
            PartialDateUI plugin = (PartialDateUI) field;
            plugin.setValue(agent, null);

        } else {
            log.debug("******** unhandled component type: " + field);
        }
        JLabel label = formViewObj.getLabelFor(field);
        if (label != null) {
            label.setEnabled(enabled);
        }
    }
}

From source file:gdt.jgui.entity.query.JQueryPanel.java

private void setSelection(JComboBox<String> comboBox, String item$) {
    ComboBoxModel<String> model = comboBox.getModel();
    if (model != null) {
        int cnt = model.getSize();
        String[] sa = null;/*www. java2  s.  co  m*/
        if (cnt > 0) {
            sa = new String[cnt];
            for (int i = 0; i < cnt; i++)
                if (item$.equals(model.getElementAt(i))) {
                    comboBox.setSelectedIndex(i);
                    return;
                }
        }
    }
}

From source file:com.dragoniade.deviantart.ui.PreferencesDialog.java

public PreferencesDialog(final DownloaderGUI owner, Properties config) {
    super(owner, "Preferences", true);

    HttpClientParams params = new HttpClientParams();
    params.setVersion(HttpVersion.HTTP_1_1);
    params.setSoTimeout(30000);//from  w  w w .  ja  v a 2 s . c o  m
    client = new HttpClient(params);
    setProxy(ProxyCfg.parseConfig(config));

    sample = new Deviation();
    sample.setId(15972367L);
    sample.setTitle("Fella Promo");
    sample.setArtist("devart");
    sample.setImageDownloadUrl(DOWNLOAD_URL);
    sample.setImageFilename(Deviation.extractFilename(DOWNLOAD_URL));
    sample.setCollection(new Collection(1L, "MyCollect"));
    setLayout(new BorderLayout());
    panes = new JTabbedPane(JTabbedPane.TOP);

    JPanel genPanel = new JPanel();
    BoxLayout genLayout = new BoxLayout(genPanel, BoxLayout.Y_AXIS);
    genPanel.setLayout(genLayout);
    panes.add("General", genPanel);

    JLabel userLabel = new JLabel("Username");

    userLabel.setToolTipText("The username the account you want to download the favorites from.");

    userField = new JTextField(config.getProperty(Constants.USERNAME));

    userLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    userLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    userField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    userField.setMaximumSize(new Dimension(Integer.MAX_VALUE, userField.getFont().getSize() * 2));

    genPanel.add(userLabel);
    genPanel.add(userField);

    JPanel radioPanel = new JPanel();
    BoxLayout radioLayout = new BoxLayout(radioPanel, BoxLayout.X_AXIS);
    radioPanel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    radioPanel.setBorder(new EmptyBorder(0, 5, 0, 5));

    radioPanel.setLayout(radioLayout);

    JLabel searchLabel = new JLabel("Search for");
    searchLabel
            .setToolTipText("Select what you want to download from that user: it favorites or it galleries.");
    searchLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    searchLabel.setBorder(new EmptyBorder(0, 5, 0, 5));

    selectedSearch = SEARCH.lookup(config.getProperty(Constants.SEARCH, SEARCH.getDefault().getId()));
    buttonGroup = new ButtonGroup();

    for (final SEARCH search : SEARCH.values()) {
        JRadioButton radio = new JRadioButton(search.getLabel());
        radio.setAlignmentX(JLabel.LEFT_ALIGNMENT);
        radio.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                selectedSearch = search;
            }
        });

        buttonGroup.add(radio);
        radioPanel.add(radio);
        if (search.equals(selectedSearch)) {
            radio.setSelected(true);
        }
    }

    genPanel.add(radioPanel);

    final JTextField sampleField = new JTextField("");
    sampleField.setEditable(false);

    JLabel locationLabel = new JLabel("Download location");
    locationLabel.setToolTipText("The folder pattern where you want the file to be downloaded in.");

    JLabel legendsLabel = new JLabel(
            "<html><body>Field names: %user%, %artist%, %title%, %id%, %filename%, %collection%, %ext%<br></br>Example:</body></html>");
    legendsLabel.setToolTipText("An example of where a file will be downloaded to.");

    locationString = new StringBuilder();
    locationField = new JTextField(config.getProperty(Constants.LOCATION));
    locationField.addKeyListener(new KeyListener() {

        public void keyPressed(KeyEvent e) {
            // TODO Auto-generated method stub

        }

        public void keyReleased(KeyEvent e) {
            File dest = LocationHelper.getFile(locationField.getText(), userField.getText(), sample,
                    sample.getImageFilename());
            locationString.setLength(0);
            locationString.append(dest.getAbsolutePath());
            sampleField.setText(locationString.toString());
            if (useSameForMatureBox.isSelected()) {
                locationMatureString.setLength(0);
                locationMatureString.append(sampleField.getText());
                locationMatureField.setText(locationField.getText());
            }
        }

        public void keyTyped(KeyEvent e) {
        }

    });
    locationField.addMouseListener(new MouseListener() {
        public void mouseReleased(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
            sampleField.setText(locationString.toString());
        }

        public void mouseEntered(MouseEvent e) {
            sampleField.setText(locationString.toString());
        }

        public void mouseClicked(MouseEvent e) {
        }
    });
    JLabel locationMatureLabel = new JLabel("Mature download location");
    locationMatureLabel.setToolTipText(
            "The folder pattern where you want the file marked as 'Mature' to be downloaded in.");

    locationMatureString = new StringBuilder();
    locationMatureField = new JTextField(config.getProperty(Constants.MATURE));
    locationMatureField.addKeyListener(new KeyListener() {

        public void keyPressed(KeyEvent e) {
            // TODO Auto-generated method stub

        }

        public void keyReleased(KeyEvent e) {
            File dest = LocationHelper.getFile(locationMatureField.getText(), userField.getText(), sample,
                    sample.getImageFilename());
            locationMatureString.setLength(0);
            locationMatureString.append(dest.getAbsolutePath());
            sampleField.setText(locationMatureString.toString());
        }

        public void keyTyped(KeyEvent e) {
        }

    });

    locationMatureField.addMouseListener(new MouseListener() {
        public void mouseReleased(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
            sampleField.setText(locationString.toString());
        }

        public void mouseEntered(MouseEvent e) {
            sampleField.setText(locationMatureString.toString());
        }

        public void mouseClicked(MouseEvent e) {
        }
    });

    useSameForMatureBox = new JCheckBox("Use same location for mature deviation?");
    useSameForMatureBox.setSelected(locationLabel.getText().equals(locationMatureField.getText()));
    useSameForMatureBox.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (useSameForMatureBox.isSelected()) {
                locationMatureField.setEditable(false);
                locationMatureField.setText(locationField.getText());
                locationMatureString.setLength(0);
                locationMatureString.append(locationString);
            } else {
                locationMatureField.setEditable(true);
            }

        }
    });

    File dest = LocationHelper.getFile(locationField.getText(), userField.getText(), sample,
            sample.getImageFilename());
    sampleField.setText(dest.getAbsolutePath());
    locationString.append(sampleField.getText());

    dest = LocationHelper.getFile(locationMatureField.getText(), userField.getText(), sample,
            sample.getImageFilename());
    locationMatureString.append(dest.getAbsolutePath());

    locationLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    locationLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    locationField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    locationField.setMaximumSize(new Dimension(Integer.MAX_VALUE, locationField.getFont().getSize() * 2));
    locationMatureLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    locationMatureLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    locationMatureField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    locationMatureField
            .setMaximumSize(new Dimension(Integer.MAX_VALUE, locationMatureField.getFont().getSize() * 2));
    useSameForMatureBox.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    legendsLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    legendsLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    legendsLabel.setMaximumSize(new Dimension(Integer.MAX_VALUE, legendsLabel.getFont().getSize() * 2));
    sampleField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    sampleField.setMaximumSize(new Dimension(Integer.MAX_VALUE, sampleField.getFont().getSize() * 2));

    genPanel.add(locationLabel);
    genPanel.add(locationField);

    genPanel.add(locationMatureLabel);
    genPanel.add(locationMatureField);
    genPanel.add(useSameForMatureBox);

    genPanel.add(legendsLabel);
    genPanel.add(sampleField);
    genPanel.add(Box.createVerticalBox());

    final KeyListener prxChangeListener = new KeyListener() {

        public void keyTyped(KeyEvent e) {
            proxyChangeState = true;
        }

        public void keyPressed(KeyEvent e) {
        }

        public void keyReleased(KeyEvent e) {
        }
    };

    JPanel prxPanel = new JPanel();
    BoxLayout prxLayout = new BoxLayout(prxPanel, BoxLayout.Y_AXIS);
    prxPanel.setLayout(prxLayout);
    panes.add("Proxy", prxPanel);

    JLabel prxHostLabel = new JLabel("Proxy Host");
    prxHostLabel.setToolTipText("The hostname of the proxy server");
    prxHostField = new JTextField(config.getProperty(Constants.PROXY_HOST));
    prxHostLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxHostLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    prxHostField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxHostField.setMaximumSize(new Dimension(Integer.MAX_VALUE, prxHostField.getFont().getSize() * 2));

    JLabel prxPortLabel = new JLabel("Proxy Port");
    prxPortLabel.setToolTipText("The port of the proxy server (Default 80).");

    prxPortSpinner = new JSpinner();
    prxPortSpinner.setModel(new SpinnerNumberModel(
            Integer.parseInt(config.getProperty(Constants.PROXY_PORT, "80")), 1, 65535, 1));

    prxPortLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxPortLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    prxPortSpinner.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxPortSpinner.setMaximumSize(new Dimension(Integer.MAX_VALUE, prxPortSpinner.getFont().getSize() * 2));

    JLabel prxUserLabel = new JLabel("Proxy username");
    prxUserLabel.setToolTipText("The username used for authentication, if applicable.");
    prxUserField = new JTextField(config.getProperty(Constants.PROXY_USERNAME));
    prxUserLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxUserLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    prxUserField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxUserField.setMaximumSize(new Dimension(Integer.MAX_VALUE, prxUserField.getFont().getSize() * 2));

    JLabel prxPassLabel = new JLabel("Proxy username");
    prxPassLabel.setToolTipText("The username used for authentication, if applicable.");
    prxPassField = new JPasswordField(config.getProperty(Constants.PROXY_PASSWORD));
    prxPassLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxPassLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    prxPassField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxPassField.setMaximumSize(new Dimension(Integer.MAX_VALUE, prxPassField.getFont().getSize() * 2));

    prxUseBox = new JCheckBox("Use a proxy?");
    prxUseBox.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            prxChangeListener.keyTyped(null);

            if (prxUseBox.isSelected()) {
                prxHostField.setEditable(true);
                prxPortSpinner.setEnabled(true);
                prxUserField.setEditable(true);
                prxPassField.setEditable(true);

            } else {
                prxHostField.setEditable(false);
                prxPortSpinner.setEnabled(false);
                prxUserField.setEditable(false);
                prxPassField.setEditable(false);
            }
        }
    });

    prxUseBox.setSelected(!Boolean.parseBoolean(config.getProperty(Constants.PROXY_USE)));
    prxUseBox.doClick();
    proxyChangeState = false;

    prxHostField.addKeyListener(prxChangeListener);
    prxUserField.addKeyListener(prxChangeListener);
    prxPassField.addKeyListener(prxChangeListener);
    prxPortSpinner.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            proxyChangeState = true;
        }
    });
    prxPanel.add(prxUseBox);

    prxPanel.add(prxHostLabel);
    prxPanel.add(prxHostField);

    prxPanel.add(prxPortLabel);
    prxPanel.add(prxPortSpinner);

    prxPanel.add(prxUserLabel);
    prxPanel.add(prxUserField);

    prxPanel.add(prxPassLabel);
    prxPanel.add(prxPassField);
    prxPanel.add(Box.createVerticalBox());

    final JPanel advPanel = new JPanel();
    BoxLayout advLayout = new BoxLayout(advPanel, BoxLayout.Y_AXIS);
    advPanel.setLayout(advLayout);
    panes.add("Advanced", advPanel);
    panes.addChangeListener(new ChangeListener() {

        public void stateChanged(ChangeEvent e) {
            JTabbedPane pane = (JTabbedPane) e.getSource();

            if (proxyChangeState && pane.getSelectedComponent() == advPanel) {
                Properties properties = new Properties();
                properties.setProperty(Constants.PROXY_USERNAME, prxUserField.getText().trim());
                properties.setProperty(Constants.PROXY_PASSWORD, new String(prxPassField.getPassword()).trim());
                properties.setProperty(Constants.PROXY_HOST, prxHostField.getText().trim());
                properties.setProperty(Constants.PROXY_PORT, prxPortSpinner.getValue().toString());
                properties.setProperty(Constants.PROXY_USE, Boolean.toString(prxUseBox.isSelected()));
                ProxyCfg prx = ProxyCfg.parseConfig(properties);
                setProxy(prx);
                revalidateSearcher(null);
            }
        }
    });
    JLabel domainLabel = new JLabel("Deviant Art domain name");
    domainLabel.setToolTipText("The deviantART main domain, should it ever change.");

    domainField = new JTextField(config.getProperty(Constants.DOMAIN));
    domainLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    domainLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    domainField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    domainField.setMaximumSize(new Dimension(Integer.MAX_VALUE, domainField.getFont().getSize() * 2));

    advPanel.add(domainLabel);
    advPanel.add(domainField);

    JLabel throttleLabel = new JLabel("Throttle search delay");
    throttleLabel.setToolTipText(
            "Slow down search query by inserting a pause between them. This help prevent abuse when doing a massive download.");

    throttleSpinner = new JSpinner();
    throttleSpinner.setModel(
            new SpinnerNumberModel(Integer.parseInt(config.getProperty(Constants.THROTTLE, "0")), 5, 60, 1));

    throttleLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    throttleLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    throttleSpinner.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    throttleSpinner.setMaximumSize(new Dimension(Integer.MAX_VALUE, throttleSpinner.getFont().getSize() * 2));

    advPanel.add(throttleLabel);
    advPanel.add(throttleSpinner);

    JLabel searcherLabel = new JLabel("Searcher");
    searcherLabel.setToolTipText("Select a searcher that will look for your favorites.");

    searcherBox = new JComboBox();
    searcherBox.setRenderer(new TogglingRenderer());

    final AtomicInteger index = new AtomicInteger(0);
    searcherBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JComboBox combo = (JComboBox) e.getSource();
            Object selectedItem = combo.getSelectedItem();
            if (selectedItem instanceof SearchItem) {
                SearchItem item = (SearchItem) selectedItem;
                if (item.isValid) {
                    index.set(combo.getSelectedIndex());
                } else {
                    combo.setSelectedIndex(index.get());
                }
            }
        }
    });

    try {
        for (Class<Search> clazz : SearcherClassCache.getInstance().getClasses()) {

            Search searcher = clazz.newInstance();
            String name = searcher.getName();

            SearchItem item = new SearchItem(name, clazz.getName(), true);
            searcherBox.addItem(item);
        }
        String selectedClazz = config.getProperty(Constants.SEARCHER,
                com.dragoniade.deviantart.deviation.SearchRss.class.getName());
        revalidateSearcher(selectedClazz);
    } catch (Exception e1) {
        throw new RuntimeException(e1);
    }

    searcherLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    searcherLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    searcherBox.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    searcherBox.setMaximumSize(new Dimension(Integer.MAX_VALUE, searcherBox.getFont().getSize() * 2));

    advPanel.add(searcherLabel);
    advPanel.add(searcherBox);

    advPanel.add(Box.createVerticalBox());

    add(panes, BorderLayout.CENTER);

    JButton saveBut = new JButton("Save");

    userField.setInputVerifier(new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            if (field.getText().trim().length() == 0) {
                JOptionPane.showMessageDialog(input, "The user musn't be empty.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }
            return true;
        }
    });

    locationField.setInputVerifier(new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            String content = field.getText().trim();
            if (content.length() == 0) {
                JOptionPane.showMessageDialog(input, "The location musn't be empty.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }

            if (!content.contains("%filename%") && !content.contains("%id%")) {
                JOptionPane.showMessageDialog(input,
                        "The location must contains at least a %filename% or an %id% field.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }
            return true;
        }
    });

    locationMatureField.setInputVerifier(new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            String content = field.getText().trim();
            if (content.length() == 0) {
                JOptionPane.showMessageDialog(input, "The Mature location musn't be empty.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }

            if (!content.contains("%filename%") && !content.contains("%id%")) {
                JOptionPane.showMessageDialog(input,
                        "The Mature location must contains at least a %username% or an %id% field.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }
            return true;
        }
    });

    domainField.setInputVerifier(new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            String domain = field.getText().trim();
            if (domain.length() == 0) {
                JOptionPane.showMessageDialog(input, "You must specify the deviantART main domain.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }

            if (domain.toLowerCase().startsWith("http://")) {
                JOptionPane.showMessageDialog(input,
                        "You must specify the deviantART main domain, not the full URL (aka www.deviantart.com).",
                        "Warning", JOptionPane.WARNING_MESSAGE);
                return false;
            }

            return true;
        }
    });
    locationField.setVerifyInputWhenFocusTarget(true);

    final JDialog parent = this;
    saveBut.addActionListener(new ActionListener() {

        String errorMsg = "The location is invalid or cannot be written to.";

        public void actionPerformed(ActionEvent e) {

            String username = userField.getText().trim();
            String location = locationField.getText().trim();
            String locationMature = locationMatureField.getText().trim();
            String domain = domainField.getText().trim();
            String throttle = throttleSpinner.getValue().toString();
            String searcher = searcherBox.getSelectedItem().toString();

            String prxUse = Boolean.toString(prxUseBox.isSelected());
            String prxHost = prxHostField.getText().trim();
            String prxPort = prxPortSpinner.getValue().toString();
            String prxUsername = prxUserField.getText().trim();
            String prxPassword = new String(prxPassField.getPassword()).trim();

            if (!testPath(location, username)) {
                JOptionPane.showMessageDialog(parent, errorMsg, "Error", JOptionPane.ERROR_MESSAGE);
            }
            if (!testPath(locationMature, username)) {
                JOptionPane.showMessageDialog(parent, errorMsg, "Error", JOptionPane.ERROR_MESSAGE);
            }

            Properties p = new Properties();
            p.setProperty(Constants.USERNAME, username);
            p.setProperty(Constants.LOCATION, location);
            p.setProperty(Constants.MATURE, locationMature);
            p.setProperty(Constants.DOMAIN, domain);
            p.setProperty(Constants.THROTTLE, throttle);
            p.setProperty(Constants.SEARCHER, searcher);
            p.setProperty(Constants.SEARCH, selectedSearch.getId());

            p.setProperty(Constants.PROXY_USE, prxUse);
            p.setProperty(Constants.PROXY_HOST, prxHost);
            p.setProperty(Constants.PROXY_PORT, prxPort);
            p.setProperty(Constants.PROXY_USERNAME, prxUsername);
            p.setProperty(Constants.PROXY_PASSWORD, prxPassword);

            owner.savePreferences(p);
            parent.dispose();
        }
    });

    JButton cancelBut = new JButton("Cancel");
    cancelBut.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            parent.dispose();
        }
    });

    JPanel buttonPanel = new JPanel();
    BoxLayout butLayout = new BoxLayout(buttonPanel, BoxLayout.X_AXIS);
    buttonPanel.setLayout(butLayout);

    buttonPanel.add(saveBut);
    buttonPanel.add(cancelBut);
    add(buttonPanel, BorderLayout.SOUTH);

    pack();
    setResizable(false);
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    this.setLocation((d.width - getWidth()) / 2, (d.height - getHeight()) / 2);
    setVisible(true);
}