Example usage for javax.swing JComboBox JComboBox

List of usage examples for javax.swing JComboBox JComboBox

Introduction

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

Prototype

public JComboBox(Vector<E> items) 

Source Link

Document

Creates a JComboBox that contains the elements in the specified Vector.

Usage

From source file:br.ufrgs.enq.jcosmo.ui.COSMOSACDialog.java

public COSMOSACDialog() {
    super("JCOSMO Simple");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new BorderLayout());

    db = COSMOSACDataBase.getInstance();

    COSMOSAC models[] = new COSMOSAC[5];
    models[0] = new COSMOSAC();
    models[1] = new COSMOPAC();
    models[2] = new COSMOSAC_SVP();
    models[3] = new COSMOSAC_G();
    models[4] = new PCMSAC();
    modelBox = new JComboBox(models);
    modelBox.addActionListener(this);

    JPanel north = new JPanel(new GridLayout(0, 2));
    add(north, BorderLayout.NORTH);
    JPanel northAba1 = new JPanel(new GridLayout(0, 4));
    JPanel northAba2 = new JPanel(new GridLayout(0, 2));

    //Where the GUI is created:
    JMenuBar menuBar;//  w w  w  .j av a 2  s .  c o  m
    JMenu file, help;
    JMenuItem menuItem;

    //Create the menu bar.
    menuBar = new JMenuBar();

    // the file menu
    file = new JMenu("File");
    file.setMnemonic(KeyEvent.VK_F);
    menuBar.add(file);
    menuItem = new JMenuItem("Quit", KeyEvent.VK_Q);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, ActionEvent.ALT_MASK));
    menuItem.setActionCommand(QUIT);
    menuItem.addActionListener(this);
    file.add(menuItem);

    // the help menu
    help = new JMenu("Help");
    file.setMnemonic(KeyEvent.VK_H);
    menuBar.add(help);
    menuItem = new JMenuItem("About", KeyEvent.VK_A);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
    menuItem.setActionCommand(ABOUT);
    menuItem.addActionListener(this);
    help.add(menuItem);

    setJMenuBar(menuBar);

    listModel = new DefaultListModel();
    list = new JList(listModel);
    list.setBorder(BorderFactory.createTitledBorder("compounds"));
    list.setVisibleRowCount(2);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane listScrollPane = new JScrollPane(list);

    JButton addButton = new JButton("Add");
    addButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            new AddCompoundDialog(COSMOSACDialog.this);
        }
    });

    removeButton = new JButton("Remove");
    removeButton.addActionListener(this);
    visibRemove(false);

    JButton calcButton = new JButton("Calculate");
    calcButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            rebuildChart();
            rebuildSigmaProfiles();
        }
    });

    JButton refreshButton = new JButton("Refresh");
    refreshButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            rebuildSigmaProfiles();
        }
    });

    ignoreSGButton = new JCheckBox("Ignore SG");
    ignoreSGButton.setToolTipText("Toogles the ignore flag for the Staverman-Guggenheim term");
    ignoreSGButton.addActionListener(this);

    JPanel but = new JPanel(new GridLayout(0, 1));
    but.add(addButton, BorderLayout.EAST);
    but.add(removeButton, BorderLayout.EAST);
    but.add(modelBox);
    north.add(listScrollPane);
    north.add(but);

    northAba1.add(new JLabel("Temperature [K]"));
    northAba1.add(temperature = new JTextField(10));
    temperature.setText("298");

    northAba1.add(new JLabel("Sigma HB"));
    northAba1.add(sigmaHB = new JTextField(10));
    northAba1.add(new JLabel("Sigma HB2"));
    northAba1.add(sigmaHB2 = new JTextField(10));
    northAba1.add(new JLabel("Sigma HB3"));
    northAba1.add(sigmaHB3 = new JTextField(10));

    northAba1.add(new JLabel("Charge HB"));
    northAba1.add(chargeHB = new JTextField(10));

    northAba1.add(new JLabel("Sigma Disp"));
    northAba1.add(sigmaDisp = new JTextField(10));
    northAba1.add(new JLabel("Charge Disp"));
    northAba1.add(chargeDisp = new JTextField(10));

    northAba1.add(new JLabel("Beta"));
    northAba1.add(beta = new JTextField(10));
    northAba1.add(new JLabel("fpol"));
    northAba1.add(fpol = new JTextField(10));
    northAba1.add(new JLabel("Anorm"));
    northAba1.add(anorm = new JTextField(10));

    northAba1.add(ignoreSGButton);
    northAba1.add(calcButton);
    northAba2.add(new JLabel(""));
    northAba2.add(refreshButton);

    //      chart = new JLineChart();
    //      add(chart, BorderLayout.CENTER);
    //      chart.setTitle("Gamma Plot");
    //      chart.setSubtitle("");
    //      chart.setXAxisLabel("Mole Fraction, x_1");
    //      chart.setYAxisLabel("ln gamma, gE/RT");
    //      chart.setSource(getTitle());
    //      chart.setLegendPosition(LegendPosition.BOTTOM);
    //      chart.setShapesVisible(true);

    JFreeChart chart = ChartFactory.createXYLineChart(null, "Mole Fraction, x_1", "ln gamma, gE/RT", null,
            PlotOrientation.VERTICAL, true, true, false);
    plot = (XYPlot) chart.getPlot();
    plot.getDomainAxis().setAutoRange(false);
    plot.getDomainAxis().setRange(new Range(0.0, 1.0));

    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);

    XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) plot.getRenderer();
    r.setUseFillPaint(true);
    r.setBaseFillPaint(Color.white);
    r.setBaseShapesVisible(true);

    JFreeChart sigmaProfileChart = ChartFactory.createXYLineChart(null, "sigma", "P^x", null,
            PlotOrientation.VERTICAL, true, true, false);
    sigmaProfilePlot = sigmaProfileChart.getXYPlot();
    sigmaProfilePlot.getDomainAxis().setAutoRange(false);
    sigmaProfilePlot.getDomainAxis().setRange(new Range(-0.025, 0.025));

    //      sigmaProfilePlot.setBackgroundPaint(Color.lightGray);
    //      sigmaProfilePlot.setDomainGridlinePaint(Color.white);
    //      sigmaProfilePlot.setRangeGridlinePaint(Color.white);

    JFreeChart chartSegGamma = ChartFactory.createXYLineChart(null, "sigma", "Segment Gamma", null,
            PlotOrientation.VERTICAL, true, true, false);
    plotSegGamma = (XYPlot) chartSegGamma.getPlot();

    JPanel south = new JPanel();
    south.setLayout(new FlowLayout());
    south.add(new JLabel("<html>ln &gamma;<sup>&infin;</sup><sub>1</sub>:</html>"));
    south.add(lnGammaInf1Label = new JLabel());
    south.add(new JLabel("<html>ln &gamma;<sup>&infin;</sup><sub>2</sub>:</html>"));
    south.add(lnGammaInf2Label = new JLabel());
    south.add(Box.createHorizontalStrut(20));
    south.add(new JLabel("<html>&gamma;<sup>&infin;</sup><sub>1</sub>:</html>"));
    south.add(gammaInf1Label = new JLabel());
    south.add(new JLabel("<html>&gamma;<sup>&infin;</sup><sub>2</sub>:</html>"));
    south.add(gammaInf2Label = new JLabel());

    JPanel aba1 = new JPanel(new BorderLayout());
    aba1.add(northAba1, BorderLayout.NORTH);
    JPanel chartsPanel = new JPanel(new GridLayout(0, 2));
    aba1.add(chartsPanel, BorderLayout.CENTER);
    chartsPanel.add(new ChartPanel(chart));
    chartsPanel.add(new ChartPanel(chartSegGamma));
    aba1.add(south, BorderLayout.SOUTH);

    JPanel aba2 = new JPanel(new BorderLayout());
    aba2.add(northAba2, BorderLayout.NORTH);
    aba2.add(chartPanel = new ChartPanel(sigmaProfileChart), BorderLayout.CENTER);

    JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.addTab("gamma", aba1);
    tabbedPane.addTab("sigma", aba2);
    add(tabbedPane, BorderLayout.CENTER);

    //      cosmosac.setAEffPrime(6.596176570595075);
    //      cosmosac.setCoord(11.614599507917934);
    //      cosmosac.setVnorm(56.36966406129967);
    //      cosmosac.setAnorm(41.56058649432742);
    //      cosmosac.setCHB(65330.19484947528);
    //      cosmosac.setSigmaHB(0.008292411048046008);

    //Display the window.
    setSize(800, 600);
    setLocationRelativeTo(null);
    modelBox.setSelectedIndex(0);
    setVisible(true);

    // test for a mixture
    //      addList("WATER");
    //      addList("H3O+1");
    //      addList("OH-1");
    //      addList("CL-1");
    //      addList("OXYGEN");
    //      addList("sec-butylamine");
    //      addList("hydrogen-fluoride");
    //      addList("ACETONE");
    //      addList("METHANOL");
    //      addList("ACETONE.opt");
    //      addList("METHANOL.opt");
    //      addList("METHYL-ETHYL-KETONE");
    //      addList("ETHANOL");
    //      addList("N-HEPTANE");
    //      addList("PROPIONIC-ACID");
    //      addList("EMIM");
    //      addList("NTF2");
    //      addList("DCA");
    //      addList("N-OCTANE");
    addList("ETHYLENE CARBONATE");
    addList("BENZENE");
    addList("TOLUENE");
    removeButton.setEnabled(true);
}

From source file:net.lldp.checksims.ui.results.ScrollViewer.java

/**
 * Create a scroll viewer from a sortable Matrix Viewer
 * @param results the sortableMatrix to view
 * @param toRevalidate frame to revalidate sometimes
 *//* w  w  w  .j a va  2 s .  co m*/
public ScrollViewer(SimilarityMatrix exportMatrix, SortableMatrixViewer results, JFrame toRevalidate) {
    resultsView = new JScrollPane(results);
    setBackground(Color.black);
    resultsView.addComponentListener(new ComponentListener() {

        @Override
        public void componentHidden(ComponentEvent arg0) {
        }

        @Override
        public void componentMoved(ComponentEvent arg0) {
        }

        @Override
        public void componentResized(ComponentEvent ce) {
            Dimension size = ce.getComponent().getSize();
            results.padToSize(size);
        }

        @Override
        public void componentShown(ComponentEvent arg0) {
        }
    });

    resultsView.getViewport().addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            Rectangle r = resultsView.getViewport().getViewRect();
            results.setViewAt(r);
        }
    });

    resultsView.setBackground(Color.black);
    sidebar = new JPanel();

    setPreferredSize(new Dimension(900, 631));
    setMinimumSize(new Dimension(900, 631));
    sidebar.setPreferredSize(new Dimension(200, 631));
    sidebar.setMaximumSize(new Dimension(200, 3000));
    resultsView.setMinimumSize(new Dimension(700, 631));
    resultsView.setPreferredSize(new Dimension(700, 631));

    sidebar.setBackground(Color.GRAY);

    setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));

    this.add(sidebar);
    this.add(resultsView);

    resultsView.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    resultsView.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    resultsView.getVerticalScrollBar().setUnitIncrement(16);
    resultsView.getHorizontalScrollBar().setUnitIncrement(16);

    Integer[] presetThresholds = { 80, 60, 40, 20, 0 };
    JComboBox<Integer> threshHold = new JComboBox<Integer>(presetThresholds);
    threshHold.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent event) {
            if (event.getStateChange() == ItemEvent.SELECTED) {
                Integer item = (Integer) event.getItem();
                results.updateThreshold(item / 100.0);
                toRevalidate.revalidate();
                toRevalidate.repaint();
            }
        }
    });
    threshHold.setSelectedIndex(0);
    results.updateThreshold((Integer) threshHold.getSelectedItem() / 100.0);

    JTextField student1 = new JTextField(15);
    JTextField student2 = new JTextField(15);

    KeyListener search = new KeyListener() {

        @Override
        public void keyPressed(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
            results.highlightMatching(student1.getText(), student2.getText());
            toRevalidate.revalidate();
            toRevalidate.repaint();
        }

        @Override
        public void keyTyped(KeyEvent e) {
        }
    };

    student1.addKeyListener(search);
    student2.addKeyListener(search);

    Collection<MatrixPrinter> printerNameSet = MatrixPrinterRegistry.getInstance()
            .getSupportedImplementations();
    JComboBox<MatrixPrinter> exportAs = new JComboBox<>(new Vector<>(printerNameSet));
    JButton exportAsSave = new JButton("Save");

    JFileChooser fc = new JFileChooser();

    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setCurrentDirectory(new java.io.File("."));
    fc.setDialogTitle("Save results");

    exportAsSave.addActionListener(ae -> {
        MatrixPrinter method = (MatrixPrinter) exportAs.getSelectedItem();

        int err = fc.showDialog(toRevalidate, "Save");
        if (err == JFileChooser.APPROVE_OPTION) {
            try {
                FileUtils.writeStringToFile(fc.getSelectedFile(), method.printMatrix(exportMatrix));
            } catch (InternalAlgorithmError | IOException e1) {
                // TODO log / show error
            }
        }
    });

    JPanel thresholdLabel = new JPanel();
    JPanel studentSearchLabel = new JPanel();
    JPanel fileOutputLabel = new JPanel();

    thresholdLabel.setBorder(BorderFactory.createTitledBorder("Matching Threshold"));
    studentSearchLabel.setBorder(BorderFactory.createTitledBorder("Student Search"));
    fileOutputLabel.setBorder(BorderFactory.createTitledBorder("Save Results"));

    thresholdLabel.add(threshHold);
    studentSearchLabel.add(student1);
    studentSearchLabel.add(student2);
    fileOutputLabel.add(exportAs);
    fileOutputLabel.add(exportAsSave);

    studentSearchLabel.setPreferredSize(new Dimension(200, 100));
    studentSearchLabel.setMinimumSize(new Dimension(200, 100));
    thresholdLabel.setPreferredSize(new Dimension(200, 100));
    thresholdLabel.setMinimumSize(new Dimension(200, 100));
    fileOutputLabel.setPreferredSize(new Dimension(200, 100));
    fileOutputLabel.setMinimumSize(new Dimension(200, 100));

    sidebar.setMaximumSize(new Dimension(200, 4000));

    sidebar.add(thresholdLabel);
    sidebar.add(studentSearchLabel);
    sidebar.add(fileOutputLabel);
}

From source file:OAT.ui.util.UiUtil.java

public static void addComboCell(TableColumn column, Object[] items) {
    column.setCellEditor(new DefaultCellEditor(new JComboBox(items)));
}

From source file:ShowDocument.java

public URLWindow(AppletContext appletContext) {
    super("Show a Document!");
    this.appletContext = appletContext;

    JPanel contentPane = new JPanel(new GridBagLayout());
    setContentPane(contentPane);/*from w  ww.ja v a 2s .c  om*/
    contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;

    JLabel label1 = new JLabel("URL of document to show: ", JLabel.TRAILING);
    add(label1, c);

    urlField = new JTextField("http://java.sun.com/", 20);
    label1.setLabelFor(urlField);
    urlField.addActionListener(this);
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.weightx = 1.0;
    add(urlField, c);

    JLabel label2 = new JLabel("Window/frame to show it in: ", JLabel.TRAILING);
    c.gridwidth = 1;
    c.weightx = 0.0;
    add(label2, c);

    String[] strings = { "(browser's choice)", //don't specify
            "My Personal Window", //a window named "My Personal Window"
            "_blank", //a new, unnamed window
            "_self", "_parent", "_top" //the Frame that contained this applet
    };
    choice = new JComboBox(strings);
    label2.setLabelFor(choice);
    c.fill = GridBagConstraints.NONE;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.insets = new Insets(5, 0, 0, 0);
    c.anchor = GridBagConstraints.LINE_START;
    add(choice, c);

    JButton button = new JButton("Show document");
    button.addActionListener(this);
    c.weighty = 1.0;
    c.ipadx = 10;
    c.ipady = 10;
    c.insets = new Insets(10, 0, 0, 0);
    c.anchor = GridBagConstraints.PAGE_END;
    add(button, c);
}

From source file:com.orange.atk.graphAnalyser.RealtimeGraph.java

private void initComponents() {

    jListGraph = new JList(listModelGraph);
    jPanelroot = new JPanel();
    jScrollPaneListGraph = new JScrollPane();
    jListPerfGraph = new JList(listModelGraph);
    jComboBoxLeft = new JComboBox(comboModelLeft);
    jComboBoxRight = new JComboBox(comboModelRight);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    jScrollPaneListGraph.setViewportView(jListPerfGraph);

    jComboBoxLeft.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jComboBoxLeftActionPerformed(evt);
        }/*from  w w w.j  a  v  a  2  s . c om*/
    });

    jComboBoxRight.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jComboBoxRightActionPerformed(evt);
        }
    });

    jPanelroot.setLayout(new BorderLayout());
    jPanelroot.add(chartPanel, BorderLayout.CENTER);

    toolPane = new JPanel();
    toolPane.setLayout(new FlowLayout());

    toolPane.add(jComboBoxLeft);

    Box graphlistbox = Box.createVerticalBox();
    graphlistbox.add(new JLabel("List of Graph"));
    graphlistbox.add(jScrollPaneListGraph);
    toolPane.add(graphlistbox);

    toolPane.add(jComboBoxRight);

    jPanelroot.add(toolPane, BorderLayout.NORTH);

    setContentPane(jPanelroot);

    //a small size for small screen
    //  setMaximumSize(new Dimension(600,500));
    pack();

}

From source file:com.eviware.soapui.support.editor.inspectors.auth.ExpirationTimeChooser.java

private JComboBox createTimeUnitCombo(boolean enableManualTimeControls) {
    JComboBox timeUnitCombo = new JComboBox(TIME_UNIT_OPTIONS);
    timeUnitCombo.setName(TIME_UNIT_COMBO_NAME);
    timeUnitCombo.setEnabled(enableManualTimeControls);

    TimeUnitConfig.Enum timeUnit = profile.getManualAccessTokenExpirationTimeUnit();
    timeUnitCombo.setSelectedItem(WordUtils.capitalize(timeUnit.toString().toLowerCase()));

    return timeUnitCombo;
}

From source file:gov.loc.repository.bagger.ui.NewBagFrame.java

private void layoutBagVersionSelection(JPanel contentPane, int row) {
    //contents/*  w w w .  j ava 2  s .  c  om*/
    // Bag version dropdown list
    JLabel bagVersionLabel = new JLabel(bagView.getPropertyMessage("bag.label.version"));
    bagVersionLabel.setToolTipText(bagView.getPropertyMessage("bag.versionlist.help"));
    ArrayList<String> versionModel = new ArrayList<String>();
    Version[] vals = Version.values();
    for (int i = 0; i < vals.length; i++) {
        versionModel.add(vals[i].versionString);
    }

    bagVersionList = new JComboBox(versionModel.toArray());
    bagVersionList.setName(bagView.getPropertyMessage("bag.label.versionlist"));
    bagVersionList.setSelectedItem(Version.V0_96.versionString);
    bagVersionList.setToolTipText(bagView.getPropertyMessage("bag.versionlist.help"));

    GridBagConstraints glbc = null;

    JLabel spacerLabel = new JLabel();
    glbc = LayoutUtil.buildGridBagConstraints(0, row, 1, 1, 5, 50, GridBagConstraints.HORIZONTAL,
            GridBagConstraints.WEST);
    contentPane.add(bagVersionLabel, glbc);
    glbc = LayoutUtil.buildGridBagConstraints(1, row, 1, 1, 40, 50, GridBagConstraints.HORIZONTAL,
            GridBagConstraints.CENTER);
    contentPane.add(bagVersionList, glbc);
    glbc = LayoutUtil.buildGridBagConstraints(2, row, 1, 1, 40, 50, GridBagConstraints.NONE,
            GridBagConstraints.EAST);
    contentPane.add(spacerLabel, glbc);
}

From source file:net.vanosten.dings.swing.SummaryView.java

private void initComponents() {
    chartP = new JPanel();
    chartP.setLayout(new BorderLayout());
    //to begin with we show an information
    JLabel infoL = new JLabel(
            "Choose the chart type belwo and press the \"Update View\" button to show statistics.");
    infoL.setEnabled(false); //only for display
    infoL.setHorizontalAlignment(SwingConstants.CENTER);
    chartP.add(infoL, BorderLayout.CENTER);

    Vector<String> items = new Vector<String>();
    items.add("Entries by " + Toolbox.getInstance().getInfoPointer().getUnitLabel());
    items.add("Entries by " + Toolbox.getInstance().getInfoPointer().getCategoryLabel());
    items.add("Entries by Entry Type");
    items.add("Entries by Score");
    items.add("Entry Scores over Time"); //do not change sequence of elements, as showGraph() and checkChosenStattype rely on it
    chartTypeCB = new JComboBox(items);
    chartTypeCB.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            if (4 == chartTypeCB.getSelectedIndex()) {
                chosenCB.setEnabled(false);
            } else {
                chosenCB.setEnabled(true);
            }/*from  ww w  .  java  2s.  c o  m*/
        }
    });

    chosenCB = new JCheckBox("Only Selected Entries", false);
    chosenCB.setMnemonic("O".charAt(0));
}

From source file:net.pms.newgui.NetworkTab.java

public JComponent build() {
    FormLayout layout = new FormLayout("left:pref, 2dlu, p, 2dlu , p, 2dlu, p, 2dlu, pref:grow",
            "p, 0dlu, p, 0dlu, p, 3dlu, p, 3dlu, p, 3dlu,p, 3dlu, p, 15dlu, p, 3dlu,p, 3dlu, p,  3dlu, p, 3dlu, p, 3dlu, p,3dlu, p, 3dlu, p, 15dlu, p,3dlu, p, 3dlu, p, 15dlu, p, 3dlu, p");
    PanelBuilder builder = new PanelBuilder(layout);
    builder.setBorder(Borders.DLU4_BORDER);
    builder.setOpaque(true);/*  www .j av  a2 s.  com*/

    CellConstraints cc = new CellConstraints();

    smcheckBox = new JCheckBox(Messages.getString("NetworkTab.3"));
    smcheckBox.setContentAreaFilled(false);
    smcheckBox.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
            PMS.getConfiguration().setMinimized((e.getStateChange() == ItemEvent.SELECTED));
        }
    });
    if (PMS.getConfiguration().isMinimized()) {
        smcheckBox.setSelected(true);
    }

    JComponent cmp = builder.addSeparator(Messages.getString("NetworkTab.5"), cc.xyw(1, 1, 9));
    cmp = (JComponent) cmp.getComponent(0);
    cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));

    builder.addLabel(Messages.getString("NetworkTab.0"), cc.xy(1, 7));
    final KeyedComboBoxModel kcbm = new KeyedComboBoxModel(
            new Object[] { "bg", "ca", "zhs", "zht", "cz", "da", "nl", "en", "fi", "fr", "de", "el", "is", "it",
                    "ja", "no", "pl", "pt", "br", "ro", "ru", "sl", "es", "sv" },
            new Object[] { "Bulgarian", "Catalan", "Chinese (Simplified)", "Chinese (Traditional)", "Czech",
                    "Danish", "Dutch", "English", "Finnish", "French", "German", "Greek", "Icelandic",
                    "Italian", "Japanese", "Norwegian", "Polish", "Portuguese", "Portuguese (Brazilian)",
                    "Romanian", "Russian", "Slovenian", "Spanish", "Swedish" });
    langs = new JComboBox(kcbm);
    langs.setEditable(false);
    //langs.setSelectedIndex(0);
    String defaultLang = null;
    if (configuration.getLanguage() != null && configuration.getLanguage().length() > 0) {
        defaultLang = configuration.getLanguage();
    } else {
        defaultLang = Locale.getDefault().getLanguage();
    }
    if (defaultLang == null) {
        defaultLang = "en";
    }
    kcbm.setSelectedKey(defaultLang);
    if (langs.getSelectedIndex() == -1) {
        langs.setSelectedIndex(0);
    }

    langs.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                configuration.setLanguage((String) kcbm.getSelectedKey());

            }
        }
    });
    builder.add(langs, cc.xyw(3, 7, 7));

    builder.add(smcheckBox, cc.xyw(1, 9, 9));

    JButton service = new JButton(Messages.getString("NetworkTab.4"));
    service.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (PMS.get().installWin32Service()) {
                JOptionPane.showMessageDialog(
                        (JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
                        Messages.getString("NetworkTab.11") + Messages.getString("NetworkTab.12"),
                        "Information", JOptionPane.INFORMATION_MESSAGE);

            } else {
                JOptionPane.showMessageDialog(
                        (JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
                        Messages.getString("NetworkTab.14"), "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    });
    builder.add(service, cc.xy(1, 11));
    if (System.getProperty(LooksFrame.START_SERVICE) != null || !Platform.isWindows()) {
        service.setEnabled(false);
    }

    host = new JTextField(PMS.getConfiguration().getServerHostname());
    host.addKeyListener(new KeyListener() {

        @Override
        public void keyPressed(KeyEvent e) {
        }

        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
            configuration.setHostname(host.getText());
            PMS.get().getFrame().setReloadable(true);
        }
    });
    // host.setEnabled( StringUtils.isBlank(configuration.getNetworkInterface())) ;
    port = new JTextField(configuration.getServerPort() != 5001 ? "" + configuration.getServerPort() : "");
    port.addKeyListener(new KeyListener() {

        @Override
        public void keyPressed(KeyEvent e) {
        }

        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
            try {
                String p = port.getText();
                if (StringUtils.isEmpty(p)) {
                    p = "5001";
                }
                int ab = Integer.parseInt(p);
                configuration.setServerPort(ab);
                PMS.get().getFrame().setReloadable(true);
            } catch (NumberFormatException nfe) {
            }

        }
    });

    cmp = builder.addSeparator(Messages.getString("NetworkTab.22"), cc.xyw(1, 21, 9));
    cmp = (JComponent) cmp.getComponent(0);
    cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));

    ArrayList<String> names = new ArrayList<String>();
    names.add("");
    ArrayList<String> interfaces = new ArrayList<String>();
    interfaces.add("");
    Enumeration<NetworkInterface> enm;
    try {
        enm = NetworkInterface.getNetworkInterfaces();
        while (enm.hasMoreElements()) {
            NetworkInterface ni = enm.nextElement();
            // check for interface has at least one ip address.
            if (ni.getInetAddresses().hasMoreElements()) {
                names.add(ni.getName());
                String displayName = ni.getDisplayName();
                if (displayName == null) {
                    displayName = ni.getName();
                }
                interfaces.add(displayName.trim());
            }
        }
    } catch (SocketException e1) {
        logger.error(null, e1);
    }

    final KeyedComboBoxModel networkInterfaces = new KeyedComboBoxModel(names.toArray(), interfaces.toArray());
    networkinterfacesCBX = new JComboBox(networkInterfaces);
    networkInterfaces.setSelectedKey(configuration.getNetworkInterface());
    networkinterfacesCBX.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                configuration.setNetworkInterface((String) networkInterfaces.getSelectedKey());
                //host.setEnabled( StringUtils.isBlank(configuration.getNetworkInterface())) ;
                PMS.get().getFrame().setReloadable(true);
            }
        }
    });

    ip_filter = new JTextField(PMS.getConfiguration().getIpFilter());
    ip_filter.addKeyListener(new KeyListener() {

        @Override
        public void keyPressed(KeyEvent e) {
        }

        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
            configuration.setIpFilter(ip_filter.getText());
            PMS.get().getFrame().setReloadable(true);
        }
    });

    builder.addLabel(Messages.getString("NetworkTab.20"), cc.xy(1, 23));
    builder.add(networkinterfacesCBX, cc.xyw(3, 23, 7));
    builder.addLabel(Messages.getString("NetworkTab.23"), cc.xy(1, 25));
    builder.add(host, cc.xyw(3, 25, 7));
    builder.addLabel(Messages.getString("NetworkTab.24"), cc.xy(1, 27));
    builder.add(port, cc.xyw(3, 27, 7));
    builder.addLabel(Messages.getString("NetworkTab.30"), cc.xy(1, 29));
    builder.add(ip_filter, cc.xyw(3, 29, 7));

    cmp = builder.addSeparator(Messages.getString("NetworkTab.31"), cc.xyw(1, 31, 9));
    cmp = (JComponent) cmp.getComponent(0);
    cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));

    newHTTPEngine = new JCheckBox(Messages.getString("NetworkTab.32"));
    newHTTPEngine.setSelected(PMS.getConfiguration().isHTTPEngineV2());
    newHTTPEngine.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
            PMS.getConfiguration().setHTTPEngineV2((e.getStateChange() == ItemEvent.SELECTED));
        }
    });
    builder.add(newHTTPEngine, cc.xyw(1, 33, 9));

    preventSleep = new JCheckBox(Messages.getString("NetworkTab.33"));
    preventSleep.setSelected(PMS.getConfiguration().isPreventsSleep());
    preventSleep.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
            PMS.getConfiguration().setPreventsSleep((e.getStateChange() == ItemEvent.SELECTED));
        }
    });
    builder.add(preventSleep, cc.xyw(1, 35, 9));

    cmp = builder.addSeparator(Messages.getString("NetworkTab.34"), cc.xyw(1, 37, 9));
    cmp = (JComponent) cmp.getComponent(0);
    cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));

    JPanel panel = builder.getPanel();
    JScrollPane scrollPane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    return scrollPane;
}

From source file:DownloadDialog.java

/********************************************************************
 * Constructor: DownloadDialog/* ww w. j a v  a 2s .c  o m*/
 * Purpose: constructor for download, with necessary references
/*******************************************************************/
public DownloadDialog(final MainApplication context, Scheduler scheduler_Ref, JList courseListSelected_Ref,
        JList courseListAll_Ref) {

    // Basic setup for dialog
    setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

    setTitle(TITLE);

    // Setup proper references
    this.scheduler = scheduler_Ref;
    this.courseListSelected = courseListSelected_Ref;
    this.courseListAll = courseListAll_Ref;

    // Store available terms
    storeTerms();

    // Constraints
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.insets = new Insets(10, 10, 10, 10);
    c.gridx = 0;
    c.gridy = 0;
    c.weightx = 1;
    c.weighty = 0;
    c.gridwidth = 2;

    // Main panel
    panel = new JPanel(new GridBagLayout());

    // Add term select box
    termCB = new JComboBox(termsName.toArray());
    panel.add(termCB, c);

    // Setup username and password labels
    JLabel userL = new JLabel("Username:");
    JLabel passL = new JLabel("Password:");
    c.gridwidth = 1;
    c.gridx = 0;
    c.weightx = 0;

    // Add user label
    c.gridy = 1;
    c.insets = new Insets(5, 10, 0, 10);
    panel.add(userL, c);

    // Add password label
    c.gridy = 2;
    c.insets = new Insets(0, 10, 5, 10);
    panel.add(passL, c);

    // Setup user and pass text fields
    user = new JTextField();
    pass = new JPasswordField();
    c.weightx = 1;
    c.gridx = 1;

    // Add user field
    c.gridy = 1;
    c.insets = new Insets(5, 10, 2, 10);
    panel.add(user, c);

    // Add pass field
    c.gridy = 2;
    c.insets = new Insets(2, 10, 5, 10);
    panel.add(pass, c);

    // Setup login button
    JButton login = new JButton("Login");
    login.addActionListener(this);
    c.insets = new Insets(10, 10, 10, 10);
    c.gridx = 0;
    c.gridy = 3;
    c.gridwidth = 2;
    c.weightx = 1;
    panel.add(login, c);

    // Add panel to main box
    add(panel);

    // Pack the components and give userbox focus
    pack();
    user.requestFocus();

    // Create worker to download courses
    worker = new SwingWorker<Void, Void>() {
        protected Void doInBackground() throws Exception {

            // Reset courses
            scheduler.resetCourses();

            // Constraints
            GridBagConstraints c = new GridBagConstraints();
            c.fill = GridBagConstraints.BOTH;
            c.insets = new Insets(10, 10, 10, 10);
            c.gridx = 0;
            c.weightx = 1;
            c.weighty = 0;

            // Remove all elements
            panel.removeAll();

            // Add status
            JLabel status = new JLabel("Connecting...");
            c.gridy = 0;
            panel.add(status, c);

            // Add progress bar
            JProgressBar progressBar = new JProgressBar(0, SUBJECTS.length);
            c.gridy = 1;
            panel.add(progressBar, c);
            progressBar.setPreferredSize(new Dimension(275, 12));

            // Revalidate, repaint, and pack
            //revalidate();
            repaint();
            pack();

            try {

                // Create client
                DefaultHttpClient client = new DefaultHttpClient();

                // Setup and execute initial login
                HttpGet initialLogin = new HttpGet("http://jweb.kettering.edu/cku1/twbkwbis.P_ValLogin");
                HttpResponse response = client.execute(initialLogin);
                HTMLParser.parse(response);

                // Get current term
                String term = termsValue.get(termCB.getSelectedIndex());

                // Consume entity (cookies)
                HttpEntity entity = response.getEntity();
                if (entity != null)
                    entity.consumeContent();

                // Create post for login
                HttpPost login = new HttpPost("http://jweb.kettering.edu/cku1/twbkwbis.P_ValLogin");

                // Parameters
                List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                parameters.add(new BasicNameValuePair("sid", user.getText()));
                parameters.add(new BasicNameValuePair("PIN", pass.getText()));
                login.setEntity(new UrlEncodedFormEntity(parameters));
                login.setHeader("Referer", "http://jweb.kettering.edu/cku1/twbkwbis.P_ValLogin");

                // Login !
                response = client.execute(login);

                // Store proper cookies
                List<Cookie> cookies = client.getCookieStore().getCookies();

                // Start off assuming logging in failed
                boolean loggedIn = false;

                // Check cookies for successful login
                for (int i = 0; i < cookies.size(); i++)
                    if (cookies.get(i).getName().equals("SESSID"))
                        loggedIn = true;

                // Success?
                if (loggedIn) {

                    // Consumption of feed
                    HTMLParser.parse(response);

                    // Execute GET class list page
                    HttpGet classList = new HttpGet(
                            "http://jweb.kettering.edu/cku1/bwskfcls.p_sel_crse_search");
                    classList.setHeader("Referer", "https://jweb.kettering.edu/cku1/twbkwbis.P_GenMenu");
                    response = client.execute(classList);
                    HTMLParser.parse(response);

                    // Execute GET for course page
                    HttpGet coursePage = new HttpGet(
                            "http://jweb.kettering.edu/cku1/bwckgens.p_proc_term_date?p_calling_proc=P_CrseSearch&p_term="
                                    + term);
                    coursePage.setHeader("Referer",
                            "http://jweb.kettering.edu/cku1/bwskfcls.p_sel_crse_search");
                    response = client.execute(coursePage);
                    HTMLParser.parse(response);

                    // Download every subject's data
                    for (int index = 0; index < SUBJECTS.length; index++) {

                        // Don't download if cancel was pressed
                        if (isCancelled())
                            break;

                        // Update status, progress bar, then store course
                        String subject = SUBJECTS[index];
                        status.setText("Downloading " + subject);
                        progressBar.setValue(index);
                        scheduler.storeDynamicCourse(subject, client, term);
                    }

                    // Update course list data
                    courseListAll.setListData(scheduler.getCourseIDs().toArray());

                    // Clear course list data
                    String[] empty = {};
                    courseListSelected.setListData(empty);
                    context.updatePermutations();
                    context.updateSchedule();

                    // Dispose of dialog if cancelled
                    if (!isCancelled()) {
                        dispose();
                    }

                }

                // Invalid login?
                else {

                    // Update status
                    status.setText("Invalid login.");
                }
            }

            // Failed to download?
            catch (Exception exc) {

                // Show stack trace, and update status
                exc.printStackTrace();
                status.setText("Failed downloading.");
            }

            return null;
        }
    };

    // Setup window close event to be same as cancel
    this.addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosing(WindowEvent e) {

            // Cancel all downloads then dispose
            worker.cancel(true);
            dispose();
        }
    });

    // Make sure dialog is visible
    setLocationRelativeTo(context);
    setVisible(true);

}