List of usage examples for javax.swing JComboBox removeAllItems
public void removeAllItems()
From source file:de.mprengemann.intellij.plugin.androidicons.dialogs.IconImporter.java
private void prepareSpinner(JComboBox comboBox, ActionListener listener) { comboBox.removeActionListener(listener); comboBox.setSelectedItem(null);// w w w. ja v a2 s .c o m comboBox.removeAllItems(); }
From source file:com.sec.ose.osi.ui.frm.main.manage.dialog.JDlgProjectCreate.java
private void refresh(JComboBox<String> jComboBoxClonedFrom) { jComboBoxClonedFrom.removeAllItems(); if (names != null) { jComboBoxClonedFrom.addItem(""); for (String name : names) { jComboBoxClonedFrom.addItem(name); }// w ww . j a va 2s. c o m } ((JTextField) jComboBoxClonedFrom.getEditor().getEditorComponent()).setText(""); }
From source file:net.sf.mzmine.modules.visualization.spectra.SpectraVisualizerWindow.java
public void loadRawData(Scan scan) { logger.finest("Loading scan #" + scan.getScanNumber() + " from " + dataFile + " for spectra visualizer"); spectrumDataSet = new ScanDataSet(scan); this.currentScan = scan; // If the plot mode has not been set yet, set it accordingly if (spectrumPlot.getPlotMode() == null) { if (currentScan.isCentroided()) { spectrumPlot.setPlotMode(PlotMode.CENTROID); toolBar.setCentroidButton(false); } else {/*from w w w. ja v a 2s. c o m*/ spectrumPlot.setPlotMode(PlotMode.CONTINUOUS); toolBar.setCentroidButton(true); } } // Clean up the MS/MS selector combo final JComboBox msmsSelector = bottomPanel.getMSMSSelector(); // We disable the MSMS selector first and then enable it again later // after updating the items. If we skip this, the size of the // selector may not be adjusted properly (timing issues?) msmsSelector.setEnabled(false); msmsSelector.removeAllItems(); boolean msmsVisible = false; // Add parent scan to MS/MS selector combo NumberFormat rtFormat = MZmineCore.getConfiguration().getRTFormat(); NumberFormat mzFormat = MZmineCore.getConfiguration().getMZFormat(); NumberFormat intensityFormat = MZmineCore.getConfiguration().getIntensityFormat(); int parentNumber = currentScan.getParentScanNumber(); if ((currentScan.getMSLevel() > 1) && (parentNumber > 0)) { Scan parentScan = dataFile.getScan(parentNumber); if (parentScan != null) { String itemText = "Parent scan #" + parentNumber + ", RT: " + rtFormat.format(parentScan.getRetentionTime()) + ", precursor m/z: " + mzFormat.format(currentScan.getPrecursorMZ()); if (currentScan.getPrecursorCharge() > 0) itemText += " (chrg " + currentScan.getPrecursorCharge() + ")"; msmsSelector.addItem(itemText); msmsVisible = true; } } // Add all fragment scans to MS/MS selector combo int fragmentScans[] = currentScan.getFragmentScanNumbers(); if (fragmentScans != null) { for (int fragment : fragmentScans) { Scan fragmentScan = dataFile.getScan(fragment); if (fragmentScan == null) continue; final String itemText = "Fragment scan #" + fragment + ", RT: " + rtFormat.format(fragmentScan.getRetentionTime()) + ", precursor m/z: " + mzFormat.format(fragmentScan.getPrecursorMZ()); // Updating the combo in other than Swing thread may cause // exception SwingUtilities.invokeLater(new Runnable() { public void run() { msmsSelector.addItem(itemText); } }); msmsVisible = true; } } msmsSelector.setEnabled(true); // Update the visibility of MS/MS selection combo bottomPanel.setMSMSSelectorVisible(msmsVisible); // Set window and plot titles String title = "[" + dataFile.getName() + "] scan #" + currentScan.getScanNumber(); String subTitle = "MS" + currentScan.getMSLevel(); if (currentScan.getMSLevel() > 1) { subTitle += " (" + mzFormat.format(currentScan.getPrecursorMZ()) + " precursor m/z)"; } subTitle += ", RT " + rtFormat.format(currentScan.getRetentionTime()); DataPoint basePeak = currentScan.getHighestDataPoint(); if (basePeak != null) { subTitle += ", base peak: " + mzFormat.format(basePeak.getMZ()) + " m/z (" + intensityFormat.format(basePeak.getIntensity()) + ")"; } setTitle(title); spectrumPlot.setTitle(title, subTitle); // Set plot data set spectrumPlot.removeAllDataSets(); spectrumPlot.addDataSet(spectrumDataSet, scanColor, false); // Reload peak list bottomPanel.rebuildPeakListSelector(); }
From source file:com.intuit.tank.tools.debugger.ActionProducer.java
public void setChoiceComboBoxOptions(JComboBox<TankClientChoice> cb) { cb.removeAllItems(); try {//from ww w.j a va 2 s . c o m TankHttpClientDefinitionContainer clientDefinitions = agentServiceClient.getClientDefinitions(); for (TankHttpClientDefinition def : clientDefinitions.getDefinitions()) { TankClientChoice c = new TankClientChoice(def.getName(), def.getClassName()); cb.addItem(c); if (def.getClassName().equals(clientDefinitions.getDefaultDefinition())) { cb.setSelectedItem(c); } } } catch (Exception e) { // set to default cb.addItem( new TankClientChoice("Apache HttpClient 3.1", "com.intuit.tank.httpclient3.TankHttpClient3")); cb.addItem( new TankClientChoice("Apache HttpClient 4.5", "com.intuit.tank.httpclient4.TankHttpClient4")); cb.setSelectedIndex(1); } }
From source file:com.diversityarrays.kdxplore.curate.SampleEntryPanel.java
private void doRepopulateStatsControls() { for (StatType statType : StatType.values()) { Object statValue = statType.getStatValue(kdsmartSampleStatistics); statButtonByStatType.get(statType).setEnabled(statValue != null); Component component = statComponentByStatType.get(statType); if (statType != StatType.MODE) { component.setEnabled(statValue != null); ((JButton) component).setText(statValue == null ? "" : statValue.toString()); //$NON-NLS-1$ } else {// w ww .j a v a 2 s.co m @SuppressWarnings("unchecked") JComboBox<String> comboBox = (JComboBox<String>) component; comboBox.removeAllItems(); String[] modesArray = (String.valueOf(statValue)).split(",", -1); //$NON-NLS-1$ List<String> modes = Arrays.asList(modesArray); if (modes.size() > 1) { comboBox.setEnabled(true); for (String s : modes) { if (s.trim() != null) { comboBox.addItem(s.trim()); } } } else { comboBox.setEnabled(true); comboBox.addItem(String.valueOf(statValue)); } } } }
From source file:edu.virginia.iath.oxygenplugins.juel.JUELPluginMenu.java
public JUELPluginMenu(StandalonePluginWorkspace spw, LocalOptions ops) { super(name, true); ws = spw;/* w w w . j ava2 s . co m*/ options = ops; // setup the options //options.readStorage(); // Find names JMenuItem search = new JMenuItem("Find Name"); search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent selection) { String label = "Find Name"; final JTextField lastName = new JTextField("", 30); lastName.setPreferredSize(new Dimension(350, 25)); //JTextField projectName = new JTextField("", 30); final JComboBox possibleVals = new JComboBox(); possibleVals.setEnabled(false); possibleVals.setPreferredSize(new Dimension(350, 25)); JButton search = new JButton("Search"); search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent selection) { // query the database try { String json = ""; String line; URL url = new URL("http://juel.iath.virginia.edu/academical_db/people/find_people?term=" + lastName.getText()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { json += line; } JSONArray obj = new JSONArray(json); // Read the JSON and update possibleVals possibleVals.removeAllItems(); possibleVals.setEnabled(false); for (int i = 0; i < obj.length(); i++) { JSONObject cur = obj.getJSONObject(i); String name = cur.getString("label"); String id = String.format("P%05d", cur.getInt("value")); possibleVals.addItem(new ComboBoxObject(name, id)); possibleVals.setEnabled(true); } } catch (Exception e) { e.printStackTrace(); possibleVals.setEnabled(false); } return; } }); search.setPreferredSize(new Dimension(100, 25)); JButton insert = new JButton("Insert"); insert.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent sel) { // Insert into the page // Get the selected value, grab the ID, then insert into the document // Get the editor WSTextEditorPage ed = null; WSEditor editorAccess = ws .getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA); if (editorAccess != null && editorAccess.getCurrentPage() instanceof WSTextEditorPage) { ed = (WSTextEditorPage) editorAccess.getCurrentPage(); } String result = "key=\"" + ((ComboBoxObject) possibleVals.getSelectedItem()).id + "\""; // Update the text in the document ed.beginCompoundUndoableEdit(); int selectionOffset = ed.getSelectionStart(); ed.deleteSelection(); javax.swing.text.Document doc = ed.getDocument(); try { if (selectionOffset > 0 && !doc.getText(selectionOffset - 1, 1).equals(" ")) result = " " + result; if (selectionOffset > 0 && !doc.getText(selectionOffset, 1).equals(" ") && !doc.getText(selectionOffset, 1).equals(">")) result = result + " "; doc.insertString(selectionOffset, result, javax.swing.text.SimpleAttributeSet.EMPTY); } catch (javax.swing.text.BadLocationException b) { // Okay if it doesn't work } ed.endCompoundUndoableEdit(); return; } }); insert.setPreferredSize(new Dimension(100, 25)); java.awt.GridLayout layoutOuter = new java.awt.GridLayout(3, 1); java.awt.FlowLayout layout = new java.awt.FlowLayout(FlowLayout.RIGHT); // rows, columns JPanel addPanel = new JPanel(); JPanel addPanelInner = new JPanel(); addPanel.setLayout(layoutOuter); addPanel.add(new JLabel("Search for last name, then choose a full name from the list below")); addPanelInner.setLayout(layout); addPanelInner.add(new JLabel("Search Last Name: ")); addPanelInner.add(lastName); addPanelInner.add(search); addPanel.add(addPanelInner); addPanelInner = new JPanel(); addPanelInner.setLayout(layout); addPanelInner.add(new JLabel("Narrow Search: ")); addPanelInner.add(possibleVals); addPanelInner.add(insert); addPanel.add(addPanelInner); JOptionPane.showMessageDialog((java.awt.Frame) ws.getParentFrame(), addPanel, label, JOptionPane.PLAIN_MESSAGE); } }); this.add(search); // Find places search = new JMenuItem("Find Place"); search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent selection) { String label = "Find Place"; final JTextField searchText = new JTextField("", 30); searchText.setPreferredSize(new Dimension(350, 25)); //JTextField projectName = new JTextField("", 30); final JComboBox possibleVals = new JComboBox(); possibleVals.setEnabled(false); possibleVals.setPreferredSize(new Dimension(350, 25)); JButton search = new JButton("Search"); search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent selection) { // query the database try { String json = ""; String line; URL url = new URL( "http://academical.village.virginia.edu/academical_db/places/find_places?term=" + searchText.getText()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { json += line; } JSONArray obj = new JSONArray(json); // Read the JSON and update possibleVals possibleVals.removeAllItems(); possibleVals.setEnabled(false); for (int i = 0; i < obj.length(); i++) { JSONObject cur = obj.getJSONObject(i); String id = String.format("PL%04d", cur.getInt("value")); String name = cur.getString("label") + " (" + id + ")"; possibleVals.addItem(new ComboBoxObject(name, id)); possibleVals.setEnabled(true); } } catch (Exception e) { e.printStackTrace(); possibleVals.setEnabled(false); } return; } }); search.setPreferredSize(new Dimension(100, 25)); JButton insert = new JButton("Insert"); insert.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent sel) { // Insert into the page // Get the selected value, grab the ID, then insert into the document // Get the editor WSTextEditorPage ed = null; WSEditor editorAccess = ws .getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA); if (editorAccess != null && editorAccess.getCurrentPage() instanceof WSTextEditorPage) { ed = (WSTextEditorPage) editorAccess.getCurrentPage(); } String result = "key=\"" + ((ComboBoxObject) possibleVals.getSelectedItem()).id + "\""; // Update the text in the document ed.beginCompoundUndoableEdit(); int selectionOffset = ed.getSelectionStart(); ed.deleteSelection(); javax.swing.text.Document doc = ed.getDocument(); try { if (selectionOffset > 0 && !doc.getText(selectionOffset - 1, 1).equals(" ")) result = " " + result; if (selectionOffset > 0 && !doc.getText(selectionOffset, 1).equals(" ") && !doc.getText(selectionOffset, 1).equals(">")) result = result + " "; doc.insertString(selectionOffset, result, javax.swing.text.SimpleAttributeSet.EMPTY); } catch (javax.swing.text.BadLocationException b) { // Okay if it doesn't work } ed.endCompoundUndoableEdit(); return; } }); insert.setPreferredSize(new Dimension(100, 25)); java.awt.GridLayout layoutOuter = new java.awt.GridLayout(3, 1); java.awt.FlowLayout layout = new java.awt.FlowLayout(FlowLayout.RIGHT); // rows, columns JPanel addPanel = new JPanel(); JPanel addPanelInner = new JPanel(); addPanel.setLayout(layoutOuter); addPanel.add(new JLabel("Search for a place name, then choose one from the list below")); addPanelInner.setLayout(layout); addPanelInner.add(new JLabel("Search Keyword: ")); addPanelInner.add(searchText); addPanelInner.add(search); addPanel.add(addPanelInner); addPanelInner = new JPanel(); addPanelInner.setLayout(layout); addPanelInner.add(new JLabel("Narrow Search: ")); addPanelInner.add(possibleVals); addPanelInner.add(insert); addPanel.add(addPanelInner); JOptionPane.showMessageDialog((java.awt.Frame) ws.getParentFrame(), addPanel, label, JOptionPane.PLAIN_MESSAGE); } }); this.add(search); // Find corporate bodies search = new JMenuItem("Find Corporate Body"); search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent selection) { String label = "Find Corporate Body"; final JTextField searchText = new JTextField("", 30); searchText.setPreferredSize(new Dimension(350, 25)); //JTextField projectName = new JTextField("", 30); final JComboBox possibleVals = new JComboBox(); possibleVals.setEnabled(false); possibleVals.setPreferredSize(new Dimension(350, 25)); JButton search = new JButton("Search"); search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent selection) { // query the database try { String json = ""; String line; URL url = new URL( "http://academical.village.virginia.edu/academical_db/corporate_bodies/find?term=" + searchText.getText()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { json += line; } JSONArray obj = new JSONArray(json); // Read the JSON and update possibleVals possibleVals.removeAllItems(); possibleVals.setEnabled(false); for (int i = 0; i < obj.length(); i++) { JSONObject cur = obj.getJSONObject(i); String id = String.format("CB%04d", cur.getInt("value")); String name = cur.getString("label") + " (" + id + ")"; possibleVals.addItem(new ComboBoxObject(name, id)); possibleVals.setEnabled(true); } } catch (Exception e) { e.printStackTrace(); possibleVals.setEnabled(false); } return; } }); search.setPreferredSize(new Dimension(100, 25)); JButton insert = new JButton("Insert"); insert.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent sel) { // Insert into the page // Get the selected value, grab the ID, then insert into the document // Get the editor WSTextEditorPage ed = null; WSEditor editorAccess = ws .getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA); if (editorAccess != null && editorAccess.getCurrentPage() instanceof WSTextEditorPage) { ed = (WSTextEditorPage) editorAccess.getCurrentPage(); } String result = "key=\"" + ((ComboBoxObject) possibleVals.getSelectedItem()).id + "\""; // Update the text in the document ed.beginCompoundUndoableEdit(); int selectionOffset = ed.getSelectionStart(); ed.deleteSelection(); javax.swing.text.Document doc = ed.getDocument(); try { if (selectionOffset > 0 && !doc.getText(selectionOffset - 1, 1).equals(" ")) result = " " + result; if (selectionOffset > 0 && !doc.getText(selectionOffset, 1).equals(" ") && !doc.getText(selectionOffset, 1).equals(">")) result = result + " "; doc.insertString(selectionOffset, result, javax.swing.text.SimpleAttributeSet.EMPTY); } catch (javax.swing.text.BadLocationException b) { // Okay if it doesn't work } ed.endCompoundUndoableEdit(); return; } }); insert.setPreferredSize(new Dimension(100, 25)); java.awt.GridLayout layoutOuter = new java.awt.GridLayout(3, 1); java.awt.FlowLayout layout = new java.awt.FlowLayout(FlowLayout.RIGHT); // rows, columns JPanel addPanel = new JPanel(); JPanel addPanelInner = new JPanel(); addPanel.setLayout(layoutOuter); addPanel.add(new JLabel("Search for a corporate body, then one from the list below")); addPanelInner.setLayout(layout); addPanelInner.add(new JLabel("Search Keyword: ")); addPanelInner.add(searchText); addPanelInner.add(search); addPanel.add(addPanelInner); addPanelInner = new JPanel(); addPanelInner.setLayout(layout); addPanelInner.add(new JLabel("Narrow Search: ")); addPanelInner.add(possibleVals); addPanelInner.add(insert); addPanel.add(addPanelInner); JOptionPane.showMessageDialog((java.awt.Frame) ws.getParentFrame(), addPanel, label, JOptionPane.PLAIN_MESSAGE); } }); this.add(search); // Find Courses search = new JMenuItem("Find Course"); search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent selection) { String label = "Find Course"; final JTextField searchText = new JTextField("", 30); searchText.setPreferredSize(new Dimension(350, 25)); //JTextField projectName = new JTextField("", 30); final JComboBox possibleVals = new JComboBox(); possibleVals.setEnabled(false); possibleVals.setPreferredSize(new Dimension(350, 25)); JButton search = new JButton("Search"); search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent selection) { // query the database try { String json = ""; String line; URL url = new URL( "http://academical.village.virginia.edu/academical_db/courses/find?term=" + searchText.getText()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { json += line; } JSONArray obj = new JSONArray(json); // Read the JSON and update possibleVals possibleVals.removeAllItems(); possibleVals.setEnabled(false); for (int i = 0; i < obj.length(); i++) { JSONObject cur = obj.getJSONObject(i); String id = String.format("C%04d", cur.getInt("value")); String name = cur.getString("label") + " (" + id + ")"; possibleVals.addItem(new ComboBoxObject(name, id)); possibleVals.setEnabled(true); } } catch (Exception e) { e.printStackTrace(); possibleVals.setEnabled(false); } return; } }); search.setPreferredSize(new Dimension(100, 25)); JButton insert = new JButton("Insert"); insert.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent sel) { // Insert into the page // Get the selected value, grab the ID, then insert into the document // Get the editor WSTextEditorPage ed = null; WSEditor editorAccess = ws .getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA); if (editorAccess != null && editorAccess.getCurrentPage() instanceof WSTextEditorPage) { ed = (WSTextEditorPage) editorAccess.getCurrentPage(); } String result = "key=\"" + ((ComboBoxObject) possibleVals.getSelectedItem()).id + "\""; // Update the text in the document ed.beginCompoundUndoableEdit(); int selectionOffset = ed.getSelectionStart(); ed.deleteSelection(); javax.swing.text.Document doc = ed.getDocument(); try { if (selectionOffset > 0 && !doc.getText(selectionOffset - 1, 1).equals(" ")) result = " " + result; if (selectionOffset > 0 && !doc.getText(selectionOffset, 1).equals(" ") && !doc.getText(selectionOffset, 1).equals(">")) result = result + " "; doc.insertString(selectionOffset, result, javax.swing.text.SimpleAttributeSet.EMPTY); } catch (javax.swing.text.BadLocationException b) { // Okay if it doesn't work } ed.endCompoundUndoableEdit(); return; } }); insert.setPreferredSize(new Dimension(100, 25)); java.awt.GridLayout layoutOuter = new java.awt.GridLayout(3, 1); java.awt.FlowLayout layout = new java.awt.FlowLayout(FlowLayout.RIGHT); // rows, columns JPanel addPanel = new JPanel(); JPanel addPanelInner = new JPanel(); addPanel.setLayout(layoutOuter); addPanel.add(new JLabel("Search for a course, then choose one from the list below")); addPanelInner.setLayout(layout); addPanelInner.add(new JLabel("Search Keyword: ")); addPanelInner.add(searchText); addPanelInner.add(search); addPanel.add(addPanelInner); addPanelInner = new JPanel(); addPanelInner.setLayout(layout); addPanelInner.add(new JLabel("Narrow Search: ")); addPanelInner.add(possibleVals); addPanelInner.add(insert); addPanel.add(addPanelInner); JOptionPane.showMessageDialog((java.awt.Frame) ws.getParentFrame(), addPanel, label, JOptionPane.PLAIN_MESSAGE); } }); this.add(search); }
From source file:com.net2plan.gui.utils.viewEditTopolTables.specificTables.AdvancedJTable_demand.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<Demand> tableVisibleDemands = getVisibleElementsInTable(); JMenuItem offeredTrafficToAll = new JMenuItem("Set offered traffic to all"); offeredTrafficToAll.addActionListener(new ActionListener() { @Override//from www .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 demands in the table", 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("Please, introduce a non-negative number", "Error setting offered traffic"); } } NetPlan netPlan = callback.getDesign(); try { for (Demand d : tableVisibleDemands) d.setOfferedTraffic(h_d); callback.getVisualizationState().resetPickedState(); callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set offered traffic to all demands in the table"); } } }); options.add(offeredTrafficToAll); JMenuItem scaleOfferedTrafficToAll = new JMenuItem("Scale offered traffic all demands in the table"); scaleOfferedTrafficToAll.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double scalingFactor; while (true) { String str = JOptionPane.showInputDialog(null, "Scaling factor to multiply to all offered traffics", "Scale offered traffic", JOptionPane.QUESTION_MESSAGE); if (str == null) return; try { scalingFactor = Double.parseDouble(str); if (scalingFactor < 0) throw new RuntimeException(); break; } catch (Throwable ex) { ErrorHandling.showErrorDialog("Please, introduce a non-negative number", "Error setting offered traffic"); } } try { for (Demand d : tableVisibleDemands) d.setOfferedTraffic(d.getOfferedTraffic() * scalingFactor); callback.getVisualizationState().resetPickedState(); callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to scale demand offered traffics"); } } }); options.add(scaleOfferedTrafficToAll); JMenuItem setServiceTypes = new JMenuItem( "Set traversed resource types (to one or all demands in the table)"); setServiceTypes.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { NetPlan netPlan = callback.getDesign(); try { Demand d = netPlan.getDemandFromId((Long) itemId); String[] headers = StringUtils.arrayOf("Order", "Type"); Object[][] data = { null, null }; DefaultTableModel model = new ClassAwareTableModelImpl(data, headers); AdvancedJTable table = new AdvancedJTable(model); JButton addRow = new JButton("Add new traversed resource type"); addRow.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object[] newRow = { table.getRowCount(), "" }; ((DefaultTableModel) table.getModel()).addRow(newRow); } }); JButton removeRow = new JButton("Remove selected"); removeRow.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ((DefaultTableModel) table.getModel()).removeRow(table.getSelectedRow()); for (int t = 0; t < table.getRowCount(); t++) table.getModel().setValueAt(t, t, 0); } }); JButton removeAllRows = new JButton("Remove all"); removeAllRows.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { while (table.getRowCount() > 0) ((DefaultTableModel) table.getModel()).removeRow(0); } }); List<String> oldTraversedResourceTypes = d.getServiceChainSequenceOfTraversedResourceTypes(); Object[][] newData = new Object[oldTraversedResourceTypes.size()][headers.length]; for (int i = 0; i < oldTraversedResourceTypes.size(); i++) { newData[i][0] = i; newData[i][1] = oldTraversedResourceTypes.get(i); } ((DefaultTableModel) table.getModel()).setDataVector(newData, headers); JPanel pane = new JPanel(); JPanel pane2 = new JPanel(); pane.setLayout(new BorderLayout()); pane2.setLayout(new BorderLayout()); pane.add(new JScrollPane(table), BorderLayout.CENTER); pane2.add(addRow, BorderLayout.WEST); pane2.add(removeRow, BorderLayout.EAST); pane2.add(removeAllRows, BorderLayout.SOUTH); pane.add(pane2, BorderLayout.SOUTH); final String[] optionsArray = new String[] { "Set to selected demand", "Set to all demands", "Cancel" }; int result = JOptionPane.showOptionDialog(null, pane, "Set traversed resource types", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, optionsArray, optionsArray[0]); if ((result != 0) && (result != 1)) return; final boolean setToAllDemands = (result == 1); List<String> newTraversedResourcesTypes = new LinkedList<>(); for (int j = 0; j < table.getRowCount(); j++) { String travResourceType = table.getModel().getValueAt(j, 1).toString(); newTraversedResourcesTypes.add(travResourceType); } if (setToAllDemands) { for (Demand dd : tableVisibleDemands) if (!dd.getRoutes().isEmpty()) throw new Net2PlanException( "It is not possible to set the resource types traversed to demands with routes"); for (Demand dd : tableVisibleDemands) dd.setServiceChainSequenceOfTraversedResourceTypes(newTraversedResourcesTypes); } else { if (!d.getRoutes().isEmpty()) throw new Net2PlanException( "It is not possible to set the resource types traversed to demands with routes"); d.setServiceChainSequenceOfTraversedResourceTypes(newTraversedResourcesTypes); } callback.getVisualizationState().resetPickedState(); callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set traversed resource types"); } } }); options.add(setServiceTypes); if (itemId != null && netPlan.isMultilayer()) { final long demandId = (long) itemId; if (netPlan.getDemandFromId(demandId).isCoupled()) { JMenuItem decoupleDemandItem = new JMenuItem("Decouple demand"); decoupleDemandItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { netPlan.getDemandFromId(demandId).decouple(); model.setValueAt("", row, 3); callback.getVisualizationState().resetPickedState(); callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } }); options.add(decoupleDemandItem); } else { JMenuItem createUpperLayerLinkFromDemandItem = new JMenuItem("Create upper layer link from demand"); createUpperLayerLinkFromDemandItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Collection<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 the link", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result != JOptionPane.OK_OPTION) return; try { long layerId = (long) ((StringLabeller) layerSelector.getSelectedItem()) .getObject(); netPlan.getDemandFromId(demandId) .coupleToNewLinkCreated(netPlan.getNetworkLayerFromId(layerId)); callback.getVisualizationState() .recomputeCanvasTopologyBecauseOfLinkOrNodeAdditionsOrRemovals(); callback.updateVisualizationAfterChanges( Sets.newHashSet(NetworkElementType.DEMAND, NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); break; } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Error creating upper layer link from demand"); } } } }); options.add(createUpperLayerLinkFromDemandItem); JMenuItem coupleDemandToLink = new JMenuItem("Couple demand to upper layer link"); coupleDemandToLink.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Collection<Long> layerIds = netPlan.getNetworkLayerIds(); final JComboBox layerSelector = new WiderJComboBox(); final JComboBox linkSelector = 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.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (layerSelector.getSelectedIndex() >= 0) { long selectedLayerId = (Long) ((StringLabeller) layerSelector.getSelectedItem()) .getObject(); NetworkLayer selectedLayer = netPlan.getNetworkLayerFromId(selectedLayerId); linkSelector.removeAllItems(); Collection<Link> links_thisLayer = netPlan.getLinks(selectedLayer); for (Link link : links_thisLayer) { if (link.isCoupled()) continue; String originNodeName = link.getOriginNode().getName(); String destinationNodeName = link.getDestinationNode().getName(); linkSelector.addItem(StringLabeller.unmodifiableOf(link.getId(), "e" + link.getIndex() + " [n" + link.getOriginNode().getIndex() + " (" + originNodeName + ") -> n" + link.getDestinationNode().getIndex() + " (" + destinationNodeName + ")]")); } } if (linkSelector.getItemCount() == 0) { linkSelector.setEnabled(false); } else { linkSelector.setSelectedIndex(0); linkSelector.setEnabled(true); } } }); layerSelector.setSelectedIndex(-1); layerSelector.setSelectedIndex(0); JPanel pane = new JPanel(new MigLayout("", "[][grow]", "[][]")); pane.add(new JLabel("Select layer: ")); pane.add(layerSelector, "growx, wrap"); pane.add(new JLabel("Select link: ")); pane.add(linkSelector, "growx, wrap"); while (true) { int result = JOptionPane.showConfirmDialog(null, pane, "Please select the upper layer link", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result != JOptionPane.OK_OPTION) return; try { long layerId = (long) ((StringLabeller) layerSelector.getSelectedItem()) .getObject(); long linkId; try { linkId = (long) ((StringLabeller) linkSelector.getSelectedItem()).getObject(); } catch (Throwable ex) { throw new RuntimeException("No link was selected"); } netPlan.getDemandFromId(demandId) .coupleToUpperLayerLink(netPlan.getLinkFromId(linkId)); callback.getVisualizationState().resetPickedState(); callback.updateVisualizationAfterChanges( Sets.newHashSet(NetworkElementType.DEMAND, NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); break; } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Error coupling upper layer link to demand"); } } } }); options.add(coupleDemandToLink); } if (numRows > 1) { JMenuItem decoupleAllDemandsItem = null; JMenuItem createUpperLayerLinksFromDemandsItem = null; final Set<Demand> coupledDemands = tableVisibleDemands.stream().filter(d -> d.isCoupled()) .collect(Collectors.toSet()); if (!coupledDemands.isEmpty()) { decoupleAllDemandsItem = new JMenuItem("Decouple all demands"); decoupleAllDemandsItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { for (Demand d : new LinkedHashSet<Demand>(coupledDemands)) d.decouple(); int numRows = model.getRowCount(); for (int i = 0; i < numRows; i++) model.setValueAt("", i, 3); callback.getVisualizationState().resetPickedState(); callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.DEMAND)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } }); } if (coupledDemands.size() < tableVisibleDemands.size()) { createUpperLayerLinksFromDemandsItem = new JMenuItem( "Create upper layer links from uncoupled demands"); createUpperLayerLinksFromDemandsItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Collection<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 (Demand demand : tableVisibleDemands) if (!demand.isCoupled()) demand.coupleToNewLinkCreated(layer); callback.getVisualizationState() .recomputeCanvasTopologyBecauseOfLinkOrNodeAdditionsOrRemovals(); callback.updateVisualizationAfterChanges( Sets.newHashSet(NetworkElementType.DEMAND, NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); break; } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Error creating upper layer links"); } } } }); } if (!options.isEmpty() && (decoupleAllDemandsItem != null || createUpperLayerLinksFromDemandsItem != null)) { options.add(new JPopupMenu.Separator()); if (decoupleAllDemandsItem != null) options.add(decoupleAllDemandsItem); if (createUpperLayerLinksFromDemandsItem != null) options.add(createUpperLayerLinksFromDemandsItem); } } } return options; }
From source file:com.net2plan.gui.utils.viewEditTopolTables.specificTables.AdvancedJTable_link.java
private List<JComponent> getExtraOptions(final int row, final Object itemId) { List<JComponent> options = new LinkedList<JComponent>(); final List<Link> rowVisibleLinks = getVisibleElementsInTable(); final NetPlan netPlan = callback.getDesign(); if (itemId != null) { final long linkId = (long) itemId; JMenuItem lengthToEuclidean_thisLink = new JMenuItem("Set link length to node-pair Euclidean distance"); lengthToEuclidean_thisLink.addActionListener(new ActionListener() { @Override/*from ww w. jav a 2s . c o m*/ public void actionPerformed(ActionEvent e) { Link link = netPlan.getLinkFromId(linkId); Node originNode = link.getOriginNode(); Node destinationNode = link.getDestinationNode(); double euclideanDistance = netPlan.getNodePairEuclideanDistance(originNode, destinationNode); link.setLengthInKm(euclideanDistance); callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } }); options.add(lengthToEuclidean_thisLink); JMenuItem lengthToHaversine_allNodes = new JMenuItem( "Set link length to node-pair Haversine distance (longitude-latitude) in km"); lengthToHaversine_allNodes.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Link link = netPlan.getLinkFromId(linkId); Node originNode = link.getOriginNode(); Node destinationNode = link.getDestinationNode(); double haversineDistanceInKm = netPlan.getNodePairHaversineDistanceInKm(originNode, destinationNode); link.setLengthInKm(haversineDistanceInKm); callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } }); options.add(lengthToHaversine_allNodes); JMenuItem scaleLinkLength_thisLink = new JMenuItem("Scale link length"); scaleLinkLength_thisLink.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double scaleFactor; while (true) { String str = JOptionPane.showInputDialog(null, "(Multiplicative) Scale factor", "Scale link length", JOptionPane.QUESTION_MESSAGE); if (str == null) return; try { scaleFactor = Double.parseDouble(str); if (scaleFactor < 0) throw new RuntimeException(); break; } catch (Throwable ex) { ErrorHandling.showErrorDialog( "Non-valid scale value. Please, introduce a non-negative number", "Error setting scale factor"); } } netPlan.getLinkFromId(linkId) .setLengthInKm(netPlan.getLinkFromId(linkId).getLengthInKm() * scaleFactor); callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } }); options.add(scaleLinkLength_thisLink); if (netPlan.isMultilayer()) { Link link = netPlan.getLinkFromId(linkId); if (link.getCoupledDemand() != null) { JMenuItem decoupleLinkItem = new JMenuItem("Decouple link (if coupled to unicast demand)"); decoupleLinkItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { netPlan.getLinkFromId(linkId).getCoupledDemand().decouple(); model.setValueAt("", row, 20); callback.getVisualizationState().resetPickedState(); callback.updateVisualizationAfterChanges( Sets.newHashSet(NetworkElementType.LINK, NetworkElementType.DEMAND)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } }); options.add(decoupleLinkItem); } else { JMenuItem createLowerLayerDemandFromLinkItem = new JMenuItem( "Create lower layer demand from link"); createLowerLayerDemandFromLinkItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Collection<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 lower layer to create the demand", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result != JOptionPane.OK_OPTION) return; try { long layerId = (long) ((StringLabeller) layerSelector.getSelectedItem()) .getObject(); Link link = netPlan.getLinkFromId(linkId); netPlan.addDemand(link.getOriginNode(), link.getDestinationNode(), link.getCapacity(), link.getAttributes(), netPlan.getNetworkLayerFromId(layerId)); callback.getVisualizationState().resetPickedState(); callback.updateVisualizationAfterChanges( Sets.newHashSet(NetworkElementType.DEMAND)); callback.getUndoRedoNavigationManager().addNetPlanChange(); break; } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Error creating lower layer demand from link"); } } } }); options.add(createLowerLayerDemandFromLinkItem); JMenuItem coupleLinkToDemand = new JMenuItem("Couple link to lower layer demand"); coupleLinkToDemand.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Collection<Long> layerIds = netPlan.getNetworkLayerIds(); final JComboBox layerSelector = new WiderJComboBox(); final JComboBox demandSelector = 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.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (layerSelector.getSelectedIndex() >= 0) { long selectedLayerId = (Long) ((StringLabeller) layerSelector .getSelectedItem()).getObject(); demandSelector.removeAllItems(); for (Demand demand : netPlan .getDemands(netPlan.getNetworkLayerFromId(selectedLayerId))) { if (demand.isCoupled()) continue; long ingressNodeId = demand.getIngressNode().getId(); long egressNodeId = demand.getEgressNode().getId(); String ingressNodeName = demand.getIngressNode().getName(); String egressNodeName = demand.getEgressNode().getName(); demandSelector.addItem(StringLabeller.unmodifiableOf(demand.getId(), "d" + demand.getId() + " [n" + ingressNodeId + " (" + ingressNodeName + ") -> n" + egressNodeId + " (" + egressNodeName + ")]")); } } if (demandSelector.getItemCount() == 0) { demandSelector.setEnabled(false); } else { demandSelector.setSelectedIndex(0); demandSelector.setEnabled(true); } } }); layerSelector.setSelectedIndex(-1); layerSelector.setSelectedIndex(0); JPanel pane = new JPanel(new MigLayout("", "[][grow]", "[][]")); pane.add(new JLabel("Select layer: ")); pane.add(layerSelector, "growx, wrap"); pane.add(new JLabel("Select demand: ")); pane.add(demandSelector, "growx, wrap"); while (true) { int result = JOptionPane.showConfirmDialog(null, pane, "Please select the lower layer demand", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result != JOptionPane.OK_OPTION) return; try { long demandId; try { demandId = (long) ((StringLabeller) demandSelector.getSelectedItem()) .getObject(); } catch (Throwable ex) { throw new RuntimeException("No demand was selected"); } netPlan.getDemandFromId(demandId) .coupleToUpperLayerLink(netPlan.getLinkFromId(linkId)); callback.getVisualizationState().resetPickedState(); callback.updateVisualizationAfterChanges( Sets.newHashSet(NetworkElementType.LINK, NetworkElementType.DEMAND)); callback.getUndoRedoNavigationManager().addNetPlanChange(); break; } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Error coupling lower layer demand to link"); } } } }); options.add(coupleLinkToDemand); } } } if (rowVisibleLinks.size() > 1) { if (!options.isEmpty()) options.add(new JPopupMenu.Separator()); JMenuItem caFixValue = new JMenuItem("Set capacity to all"); caFixValue.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double u_e; while (true) { String str = JOptionPane.showInputDialog(null, "Capacity value", "Set capacity to all table links", JOptionPane.QUESTION_MESSAGE); if (str == null) return; try { u_e = Double.parseDouble(str); if (u_e < 0) throw new NumberFormatException(); break; } catch (NumberFormatException ex) { ErrorHandling.showErrorDialog( "Non-valid capacity value. Please, introduce a non-negative number", "Error setting capacity value"); } } try { for (Link link : rowVisibleLinks) link.setCapacity(u_e); callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set capacity to all links"); } } }); options.add(caFixValue); JMenuItem caFixValueUtilization = new JMenuItem("Set capacity to match a given utilization"); caFixValueUtilization.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double utilization; while (true) { String str = JOptionPane.showInputDialog(null, "Link utilization value", "Set capacity to all table links to match a given utilization", JOptionPane.QUESTION_MESSAGE); if (str == null) return; try { utilization = Double.parseDouble(str); if (utilization <= 0) throw new NumberFormatException(); break; } catch (NumberFormatException ex) { ErrorHandling.showErrorDialog( "Non-valid link utilization value. Please, introduce a strictly positive number", "Error setting link utilization value"); } } try { for (Link link : rowVisibleLinks) link.setCapacity(link.getOccupiedCapacity() / utilization); callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set capacity to all links according to a given link utilization"); } } }); options.add(caFixValueUtilization); JMenuItem lengthToAll = new JMenuItem("Set link length to all"); lengthToAll.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double l_e; while (true) { String str = JOptionPane.showInputDialog(null, "Link length value (in km)", "Set link length to all table links", JOptionPane.QUESTION_MESSAGE); if (str == null) return; try { l_e = Double.parseDouble(str); if (l_e < 0) throw new RuntimeException(); break; } catch (Throwable ex) { ErrorHandling.showErrorDialog( "Non-valid link length value. Please, introduce a non-negative number", "Error setting link length"); } } NetPlan netPlan = callback.getDesign(); try { for (Link link : rowVisibleLinks) link.setLengthInKm(l_e); callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set link length to all links"); } } }); options.add(lengthToAll); JMenuItem lengthToEuclidean_allLinks = new JMenuItem( "Set all table link lengths to node-pair Euclidean distance"); lengthToEuclidean_allLinks.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { for (Link link : rowVisibleLinks) link.setLengthInKm(netPlan.getNodePairEuclideanDistance(link.getOriginNode(), link.getDestinationNode())); callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set link length value to all links"); } } }); options.add(lengthToEuclidean_allLinks); JMenuItem lengthToHaversine_allLinks = new JMenuItem( "Set all table link lengths to node-pair Haversine distance (longitude-latitude) in km"); lengthToHaversine_allLinks.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { NetPlan netPlan = callback.getDesign(); try { for (Link link : rowVisibleLinks) { link.setLengthInKm(netPlan.getNodePairHaversineDistanceInKm(link.getOriginNode(), link.getDestinationNode())); } callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set link length value to all links"); } } }); options.add(lengthToHaversine_allLinks); JMenuItem scaleLinkLength_allLinks = new JMenuItem("Scale all table link lengths"); scaleLinkLength_allLinks.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double scaleFactor; while (true) { String str = JOptionPane.showInputDialog(null, "(Multiplicative) Scale factor", "Scale (all) link length", JOptionPane.QUESTION_MESSAGE); if (str == null) return; try { scaleFactor = Double.parseDouble(str); if (scaleFactor < 0) throw new RuntimeException(); break; } catch (Throwable ex) { ErrorHandling.showErrorDialog( "Non-valid scale value. Please, introduce a non-negative number", "Error setting scale factor"); } } NetPlan netPlan = callback.getDesign(); try { for (Link link : rowVisibleLinks) link.setLengthInKm(link.getLengthInKm() * scaleFactor); callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to scale link length"); } } }); options.add(scaleLinkLength_allLinks); if (netPlan.isMultilayer()) { final Set<Link> coupledLinks = rowVisibleLinks.stream().filter(e -> e.isCoupled()) .collect(Collectors.toSet()); if (!coupledLinks.isEmpty()) { JMenuItem decoupleAllLinksItem = new JMenuItem("Decouple all table links"); decoupleAllLinksItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { for (Link link : coupledLinks) if (link.getCoupledDemand() == null) link.getCoupledMulticastDemand().decouple(); else link.getCoupledDemand().decouple(); int numRows = model.getRowCount(); for (int i = 0; i < numRows; i++) model.setValueAt("", i, 20); callback.getVisualizationState().resetPickedState(); callback.updateVisualizationAfterChanges( Sets.newHashSet(NetworkElementType.LINK, NetworkElementType.DEMAND)); callback.getUndoRedoNavigationManager().addNetPlanChange(); } }); options.add(decoupleAllLinksItem); } if (coupledLinks.size() < rowVisibleLinks.size()) { JMenuItem createLowerLayerDemandsFromLinksItem = new JMenuItem( "Create lower layer unicast demands from uncoupled links"); createLowerLayerDemandsFromLinksItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final JComboBox layerSelector = new WiderJComboBox(); for (NetworkLayer layer : netPlan.getNetworkLayers()) { if (layer.getId() == netPlan.getNetworkLayerDefault().getId()) continue; final String layerName = layer.getName(); String layerLabel = "Layer " + layer.getId(); if (!layerName.isEmpty()) layerLabel += " (" + layerName + ")"; layerSelector.addItem(StringLabeller.of(layer.getId(), 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 lower layer to create demands", 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 (Link link : rowVisibleLinks) if (!link.isCoupled()) link.coupleToNewDemandCreated(layer); callback.getVisualizationState() .recomputeCanvasTopologyBecauseOfLinkOrNodeAdditionsOrRemovals(); callback.updateVisualizationAfterChanges( Sets.newHashSet(NetworkElementType.LINK, NetworkElementType.DEMAND)); callback.getUndoRedoNavigationManager().addNetPlanChange(); break; } catch (Throwable ex) { ErrorHandling.showErrorDialog(ex.getMessage(), "Error creating lower layer demands"); } } } }); options.add(createLowerLayerDemandsFromLinksItem); } } } return options; }
From source file:com.entertailion.java.fling.FlingFrame.java
public FlingFrame(String appId) { super();/* w ww .j a v a 2 s .co m*/ this.appId = appId; rampClient = new RampClient(this); addWindowListener(this); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); Locale locale = Locale.getDefault(); resourceBundle = ResourceBundle.getBundle("com/entertailion/java/fling/resources/resources", locale); setTitle(MessageFormat.format(resourceBundle.getString("fling.title"), Fling.VERSION)); JPanel listPane = new JPanel(); // show list of ChromeCast devices detected on the local network listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS)); JPanel devicePane = new JPanel(); devicePane.setLayout(new BoxLayout(devicePane, BoxLayout.LINE_AXIS)); deviceList = new JComboBox(); deviceList.addActionListener(this); devicePane.add(deviceList); URL url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/refresh.png"); ImageIcon icon = new ImageIcon(url, resourceBundle.getString("button.refresh")); refreshButton = new JButton(icon); refreshButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // refresh the list of devices if (deviceList.getItemCount() > 0) { deviceList.setSelectedIndex(0); } discoverDevices(); } }); refreshButton.setToolTipText(resourceBundle.getString("button.refresh")); devicePane.add(refreshButton); url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/settings.png"); icon = new ImageIcon(url, resourceBundle.getString("settings.title")); settingsButton = new JButton(icon); settingsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JTextField transcodingExtensions = new JTextField(50); transcodingExtensions.setText(transcodingExtensionValues); JTextField transcodingParameters = new JTextField(50); transcodingParameters.setText(transcodingParameterValues); JPanel myPanel = new JPanel(new BorderLayout()); JPanel labelPanel = new JPanel(new GridLayout(3, 1)); JPanel fieldPanel = new JPanel(new GridLayout(3, 1)); myPanel.add(labelPanel, BorderLayout.WEST); myPanel.add(fieldPanel, BorderLayout.CENTER); labelPanel.add(new JLabel(resourceBundle.getString("transcoding.extensions"), JLabel.RIGHT)); fieldPanel.add(transcodingExtensions); labelPanel.add(new JLabel(resourceBundle.getString("transcoding.parameters"), JLabel.RIGHT)); fieldPanel.add(transcodingParameters); labelPanel.add(new JLabel(resourceBundle.getString("device.manual"), JLabel.RIGHT)); JPanel devicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); final JComboBox manualDeviceList = new JComboBox(); if (manualServers.size() == 0) { manualDeviceList.setVisible(false); } else { for (DialServer dialServer : manualServers) { manualDeviceList.addItem(dialServer); } } devicePanel.add(manualDeviceList); JButton addButton = new JButton(resourceBundle.getString("device.manual.add")); addButton.setToolTipText(resourceBundle.getString("device.manual.add.tooltip")); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JTextField name = new JTextField(); JTextField ipAddress = new JTextField(); Object[] message = { resourceBundle.getString("device.manual.name") + ":", name, resourceBundle.getString("device.manual.ipaddress") + ":", ipAddress }; int option = JOptionPane.showConfirmDialog(null, message, resourceBundle.getString("device.manual"), JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { try { manualServers.add( new DialServer(name.getText(), InetAddress.getByName(ipAddress.getText()))); Object selected = deviceList.getSelectedItem(); int selectedIndex = deviceList.getSelectedIndex(); deviceList.removeAllItems(); deviceList.addItem(resourceBundle.getString("devices.select")); for (DialServer dialServer : servers) { deviceList.addItem(dialServer); } for (DialServer dialServer : manualServers) { deviceList.addItem(dialServer); } deviceList.invalidate(); if (selectedIndex > 0) { deviceList.setSelectedItem(selected); } else { if (deviceList.getItemCount() == 2) { // Automatically select single device deviceList.setSelectedIndex(1); } } manualDeviceList.removeAllItems(); for (DialServer dialServer : manualServers) { manualDeviceList.addItem(dialServer); } manualDeviceList.setVisible(true); storeProperties(); } catch (UnknownHostException e1) { Log.e(LOG_TAG, "manual IP address", e1); JOptionPane.showMessageDialog(FlingFrame.this, resourceBundle.getString("device.manual.invalidip")); } } } }); devicePanel.add(addButton); JButton removeButton = new JButton(resourceBundle.getString("device.manual.remove")); removeButton.setToolTipText(resourceBundle.getString("device.manual.remove.tooltip")); removeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object selected = manualDeviceList.getSelectedItem(); manualDeviceList.removeItem(selected); if (manualDeviceList.getItemCount() == 0) { manualDeviceList.setVisible(false); } deviceList.removeItem(selected); deviceList.invalidate(); manualServers.remove(selected); storeProperties(); } }); devicePanel.add(removeButton); fieldPanel.add(devicePanel); int result = JOptionPane.showConfirmDialog(FlingFrame.this, myPanel, resourceBundle.getString("settings.title"), JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { transcodingParameterValues = transcodingParameters.getText(); transcodingExtensionValues = transcodingExtensions.getText(); storeProperties(); } } }); settingsButton.setToolTipText(resourceBundle.getString("settings.title")); devicePane.add(settingsButton); listPane.add(devicePane); // TODO volume = new JSlider(JSlider.VERTICAL, 0, 100, 0); volume.setUI(new MySliderUI(volume)); volume.setMajorTickSpacing(25); // volume.setMinorTickSpacing(5); volume.setPaintTicks(true); volume.setEnabled(true); volume.setValue(100); volume.setToolTipText(resourceBundle.getString("volume.title")); volume.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); if (!source.getValueIsAdjusting()) { int position = (int) source.getValue(); rampClient.volume(position / 100.0f); } } }); JPanel centerPanel = new JPanel(new BorderLayout()); // centerPanel.add(volume, BorderLayout.WEST); centerPanel.add(DragHereIcon.makeUI(this), BorderLayout.CENTER); listPane.add(centerPanel); scrubber = new JSlider(JSlider.HORIZONTAL, 0, 100, 0); scrubber.addChangeListener(this); scrubber.setMajorTickSpacing(25); scrubber.setMinorTickSpacing(5); scrubber.setPaintTicks(true); scrubber.setEnabled(false); listPane.add(scrubber); // panel of playback buttons JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); label = new JLabel("00:00:00"); buttonPane.add(label); url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/play.png"); icon = new ImageIcon(url, resourceBundle.getString("button.play")); playButton = new JButton(icon); playButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { rampClient.play(); } }); buttonPane.add(playButton); url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/pause.png"); icon = new ImageIcon(url, resourceBundle.getString("button.pause")); pauseButton = new JButton(icon); pauseButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { rampClient.pause(); } }); buttonPane.add(pauseButton); url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/stop.png"); icon = new ImageIcon(url, resourceBundle.getString("button.stop")); stopButton = new JButton(icon); stopButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { rampClient.stop(); setDuration(0); scrubber.setValue(0); scrubber.setEnabled(false); } }); buttonPane.add(stopButton); listPane.add(buttonPane); getContentPane().add(listPane); createProgressDialog(); startWebserver(); discoverDevices(); }
From source file:com.osparking.osparking.Settings_System.java
/** * Initialize some controls on the system settings change GUI. *///ww w . j ava 2 s .c o m public Settings_System(ControlGUI mainForm) { prepareComPortControls(); initComponents(); changedControls = new ChangedComponentSave(SettingsSaveButton, SettingsCancelButton, SettingsCloseButton); setIconImages(OSPiconList); augmentComponentMap(this, componentMap); tuneComponentSize(); this.mainForm = mainForm; if (mainForm == null) isStand_Alone = true; else { EBD_DisplaySettings = mainForm.EBD_DisplaySettings; } addPWStrengthItems(); addMaxArrivalItems(); maxArrivalCBoxIndex = findCBoxIndex(ImageDurationCBox, maxMaintainDate); addOperationLoggingLevelOptions(); addPopSizeOptions(); /** * Initialize device combobox items. */ for (int gate = 1; gate <= gateCount; gate++) { //<editor-fold desc="-- Combo Box item init for device and connection type of each gate"> JComboBox comboBx = ((JComboBox) getComponentByName("Camera" + gate + "_TypeCBox")); if (comboBx != null) { comboBx.removeAllItems(); for (CameraType type : CameraType.values()) { if (type == CameraType.CarButton) { if (gate == 1) { comboBx.addItem(type); } } else { comboBx.addItem(type); } } } comboBx = ((JComboBox) getComponentByName("E_Board" + gate + "_TypeCBox")); if (comboBx != null) { comboBx.removeAllItems(); for (E_BoardType type : E_BoardType.values()) { comboBx.addItem(type); } } comboBx = ((JComboBox) getComponentByName("GateBar" + gate + "_TypeCBox")); if (comboBx != null) { comboBx.removeAllItems(); for (GateBarType type : GateBarType.values()) { comboBx.addItem(type); } } for (DeviceType devType : DeviceType.values()) { comboBx = ((JComboBox) getComponentByName(devType.name() + gate + "_connTypeCBox")); if (comboBx != null) { comboBx.removeAllItems(); for (ConnectionType connType : ConnectionType.values()) { if (devType != Camera || connType == ConnectionType.TCP_IP) { comboBx.addItem(connType.getLabel()); } } } } //</editor-fold> } loadComponentValues(); makeEnterActAsTab(); setLocation(0, 0); // Enable data manager button for the admin if (loginID.equals(ADMIN_ID)) { manageData.setEnabled(true); } }