List of usage examples for javax.swing JComboBox setSelectedIndex
@BeanProperty(bound = false, preferred = true, description = "The item at index is selected.") public void setSelectedIndex(int anIndex)
anIndex
. From source file:imageuploader.ImgWindow.java
private void setExplicitSelectionManager(JComboBox comboBox) { class ExplicitSelectionManager implements KeyListener, FocusListener { private JComboBox src; private KeyListener superKeyListener; ExplicitSelectionManager(JComboBox src) { this.src = src; // we like what the default key listener does, but not the action command // it uses for ActionEvents it fires for plain text type-ahead characters this.superKeyListener = src.getKeyListeners()[0]; // we only have one src.removeKeyListener(superKeyListener); // will be replace right away, below }//from w w w. ja v a2s. c o m @Override public void keyTyped(KeyEvent e) { // basic combo box has no code in keyTyped } @Override public void keyPressed(KeyEvent e) { // in the default JComboBox implementation, the KeySelectionManager is // called from keyPressed. I'm fine with the implementation of // the default, but I don't want it firing ActionEvents that will cause // model updates src.setActionCommand("comboBoxMovement"); this.superKeyListener.keyPressed(e); src.setActionCommand("comboBoxChanged"); if (e.getKeyCode() == 10) { src.setSelectedIndex(src.getSelectedIndex()); } } @Override public void keyReleased(KeyEvent e) { // basic combo box has no code in keyReleased } @Override public void focusGained(FocusEvent e) { } @Override // this will also give us the event we want, if the user decides to Tab out of // the combo box, instead of hitting Enter public void focusLost(FocusEvent e) { src.setSelectedIndex(src.getSelectedIndex()); } } ExplicitSelectionManager newSelectionManager = new ExplicitSelectionManager(comboBox); comboBox.addKeyListener(newSelectionManager); comboBox.addFocusListener(newSelectionManager); }
From source file:com.intuit.tank.tools.debugger.ActionProducer.java
public void setChoiceComboBoxOptions(JComboBox<TankClientChoice> cb) { cb.removeAllItems();/*from www. jav a 2 s . co m*/ try { TankHttpClientDefinitionContainer clientDefinitions = agentServiceClient.getClientDefinitions(); for (TankHttpClientDefinition def : clientDefinitions.getDefinitions()) { TankClientChoice c = new TankClientChoice(def.getName(), def.getClassName()); cb.addItem(c); if (def.getClassName().equals(clientDefinitions.getDefaultDefinition())) { cb.setSelectedItem(c); } } } catch (Exception e) { // set to default cb.addItem( new TankClientChoice("Apache HttpClient 3.1", "com.intuit.tank.httpclient3.TankHttpClient3")); cb.addItem( new TankClientChoice("Apache HttpClient 4.5", "com.intuit.tank.httpclient4.TankHttpClient4")); cb.setSelectedIndex(1); } }
From source file:main.UIController.java
/************* TO GREGORIAN *************/ public void updateDayComboImladris() { UI window = this.getUi(); JComboBox yen = window.getYen(); JTextField loa = window.getLoa(); JComboBox period = window.getPeriod(); JComboBox day = window.getDayOfLoa(); JButton convert = window.getToGregorian(); JTextPane result = window.getResGregorian(); int yenNum = yen.getSelectedIndex() + 1; String value = loa.getText(); if (!value.isEmpty()) { try {//from ww w. java 2s .com int loaNum = Integer.parseInt(value); if (loaNum > 0 && loaNum <= 144) { int periodNum = period.getSelectedIndex() + 1; if (periodNum == ImladrisCalendar.YESTARE || periodNum == ImladrisCalendar.METTARE) { day.setEnabled(false); day.setModel(new DefaultComboBoxModel()); convert.setEnabled(true); result.setText(""); } else { int daySel = 0; if (day.isEnabled()) { daySel = day.getSelectedIndex() + 1; } ArrayList<Integer> days = ImladrisInfo.getInstance().getDaysArray(yenNum, loaNum, periodNum); day.setModel(new DefaultComboBoxModel(days.toArray())); if (daySel > 0 && daySel <= days.size()) { day.setSelectedIndex(daySel - 1); } day.setEnabled(true); convert.setEnabled(true); result.setText(""); } } else { day.setEnabled(false); convert.setEnabled(false); day.setModel(new DefaultComboBoxModel()); result.setText(""); } } catch (NumberFormatException e) { day.setEnabled(false); convert.setEnabled(false); day.setModel(new DefaultComboBoxModel()); result.setText(""); } } else { day.setEnabled(false); convert.setEnabled(false); day.setModel(new DefaultComboBoxModel()); result.setText(""); } }
From source file:ffx.ui.ModelingPanel.java
private void initCommandComboBox(JComboBox commands) { commands.setActionCommand("FFXCommand"); commands.setMaximumSize(xyzCommands.getPreferredSize()); commands.setEditable(false);// w w w . ja v a 2 s . c om commands.setToolTipText("Select a Modeling Command"); commands.setSelectedIndex(0); commands.addActionListener(this); }
From source file:io.github.jeddict.jpa.modeler.source.generator.ui.GenerateCodeDialog.java
private void populateProjectCombo(JComboBox projectCombo, ProjectInfo projectInfo) { ProjectCellRenderer projectCellRenderer = new ProjectCellRenderer(projectCombo.getRenderer()); projectCombo.setRenderer(projectCellRenderer); List<Project> list = getJavaProjects(); if (list == null || list.isEmpty()) { enableExistingProjectElementGroup(false); } else {//w ww. j av a 2 s .c o m DefaultComboBoxModel projectsModel = new DefaultComboBoxModel(list.toArray()); projectCombo.setModel(projectsModel); // Issue Fix #5850 Project modelerProject = FileOwnerQuery.getOwner(modelerFileObject); if (modelerProject != null) { projectCombo.setSelectedItem(modelerProject); } else { projectCombo.setSelectedIndex(-1); } selectProject(projectCombo, projectInfo); } }
From source file:ch.admin.hermes.etl.load.HermesETLApplication.java
/** * CommandLine parse und fehlende Argumente verlangen * @param args Args//from ww w. ja v a 2 s . co m * @throws ParseException */ private static void parseCommandLine(String[] args) throws Exception { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // HACK um UTF-8 CharSet fuer alle Dateien zu setzen (http://stackoverflow.com/questions/361975/setting-the-default-java-character-encoding) System.setProperty("file.encoding", "UTF-8"); Field charset = Charset.class.getDeclaredField("defaultCharset"); charset.setAccessible(true); charset.set(null, null); // commandline Options - FremdsystemSite, Username und Password Options options = new Options(); options.addOption("s", true, "Zielsystem - URL"); options.addOption("u", true, "Zielsystem - Username"); options.addOption("p", true, "Zielsystem - Password"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); site = cmd.getOptionValue("s"); user = cmd.getOptionValue("u"); passwd = cmd.getOptionValue("p"); // restliche Argumente pruefen - sonst usage ausgeben String[] others = cmd.getArgs(); if (others.length >= 1 && (others[0].endsWith(".js") || others[0].endsWith(".ftl"))) script = others[0]; if (others.length >= 2 && others[1].endsWith(".xml")) model = others[1]; // Dialog mit allen Werten zusammenstellen JComboBox<String> scenarios = new JComboBox<String>(crawler.getScenarios()); JTextField tsite = new JTextField(45); tsite.setText(site); JTextField tuser = new JTextField(16); tuser.setText(user); JPasswordField tpasswd = new JPasswordField(16); tpasswd.setText(passwd); final JTextField tscript = new JTextField(45); tscript.setText(script); final JTextField tmodel = new JTextField(45); tmodel.setText(model); JPanel myPanel = new JPanel(new GridLayout(6, 2)); myPanel.add(new JLabel("Szenario (von http://www.hermes.admin.ch):")); myPanel.add(scenarios); myPanel.add(new JLabel("XML Model:")); myPanel.add(tmodel); JPanel pmodel = new JPanel(); pmodel.add(tmodel); JButton bmodel = new JButton("..."); pmodel.add(bmodel); bmodel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { model = getFile("Szenario XML Model", new String[] { "XML Model" }, new String[] { ".xml" }); if (model != null) tmodel.setText(model); } }); myPanel.add(pmodel); scenarios.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { try { Object o = e.getItem(); tmodel.setText(crawler.getModelURL(o.toString())); scenario = o.toString(); } catch (Exception e1) { } } }); // Script myPanel.add(new JLabel("Umwandlungs-Script:")); JPanel pscript = new JPanel(); pscript.add(tscript); JButton bscript = new JButton("..."); pscript.add(bscript); myPanel.add(pscript); bscript.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { script = getFile("JavaScript/Freemarker Umwandlungs-Script", new String[] { "JavaScript", "Freemarker" }, new String[] { ".js", ".ftl" }); if (script != null) tscript.setText(script); } }); // Zielsystem Angaben myPanel.add(new JLabel("Zielsystem URL:")); myPanel.add(tsite); myPanel.add(new JLabel("Zielsystem Benutzer:")); myPanel.add(tuser); myPanel.add(new JLabel("Zielsystem Password:")); myPanel.add(tpasswd); // Trick um Feld scenario und model zu setzen. if (scenarios.getItemCount() >= 8) scenarios.setSelectedIndex(8); // Dialog int result = JOptionPane.showConfirmDialog(null, myPanel, "HERMES 5 XML Model nach Fremdsystem/Format", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { site = tsite.getText(); user = tuser.getText(); passwd = new String(tpasswd.getPassword()); model = tmodel.getText(); script = tscript.getText(); } else System.exit(1); if (model == null || script == null || script.trim().length() == 0) usage(); if (script.endsWith(".js")) if (site == null || user == null || passwd == null || user.trim().length() == 0 || passwd.trim().length() == 0) usage(); }
From source file:com.marginallyclever.makelangelo.MainGUI.java
protected boolean ChooseImageConversionOptions(boolean isDXF) { final JDialog driver = new JDialog(mainframe, translator.get("ConversionOptions"), true); driver.setLayout(new GridBagLayout()); final String[] choices = machineConfiguration.getKnownMachineNames(); final JComboBox<String> machine_choice = new JComboBox<String>(choices); machine_choice.setSelectedIndex(machineConfiguration.getCurrentMachineIndex()); final JSlider input_paper_margin = new JSlider(JSlider.HORIZONTAL, 0, 50, 100 - (int) (machineConfiguration.paper_margin * 100)); input_paper_margin.setMajorTickSpacing(10); input_paper_margin.setMinorTickSpacing(5); input_paper_margin.setPaintTicks(false); input_paper_margin.setPaintLabels(true); //final JCheckBox allow_metrics = new JCheckBox(String.valueOf("I want to add the distance drawn to the // total")); //allow_metrics.setSelected(allowMetrics); final JCheckBox reverse_h = new JCheckBox(translator.get("FlipForGlass")); reverse_h.setSelected(machineConfiguration.reverseForGlass); final JButton cancel = new JButton(translator.get("Cancel")); final JButton save = new JButton(translator.get("Start")); String[] filter_names = new String[image_converters.size()]; Iterator<Filter> fit = image_converters.iterator(); int i = 0;/*from w ww. j av a2 s . c o m*/ while (fit.hasNext()) { Filter f = fit.next(); filter_names[i++] = f.GetName(); } final JComboBox<String> input_draw_style = new JComboBox<String>(filter_names); input_draw_style.setSelectedIndex(GetDrawStyle()); GridBagConstraints c = new GridBagConstraints(); //c.gridwidth=4; c.gridx=0; c.gridy=0; driver.add(allow_metrics,c); int y = 0; c.anchor = GridBagConstraints.EAST; c.gridwidth = 1; c.gridx = 0; c.gridy = y; driver.add(new JLabel(translator.get("MenuLoadMachineConfig")), c); c.anchor = GridBagConstraints.WEST; c.gridwidth = 2; c.gridx = 1; c.gridy = y++; driver.add(machine_choice, c); if (!isDXF) { c.anchor = GridBagConstraints.EAST; c.gridwidth = 1; c.gridx = 0; c.gridy = y; driver.add(new JLabel(translator.get("ConversionStyle")), c); c.anchor = GridBagConstraints.WEST; c.gridwidth = 3; c.gridx = 1; c.gridy = y++; driver.add(input_draw_style, c); } c.anchor = GridBagConstraints.EAST; c.gridwidth = 1; c.gridx = 0; c.gridy = y; driver.add(new JLabel(translator.get("PaperMargin")), c); c.anchor = GridBagConstraints.WEST; c.gridwidth = 3; c.gridx = 1; c.gridy = y++; driver.add(input_paper_margin, c); c.anchor = GridBagConstraints.WEST; c.gridwidth = 1; c.gridx = 1; c.gridy = y++; driver.add(reverse_h, c); c.anchor = GridBagConstraints.EAST; c.gridwidth = 1; c.gridx = 2; c.gridy = y; driver.add(save, c); c.anchor = GridBagConstraints.WEST; c.gridwidth = 1; c.gridx = 3; c.gridy = y++; driver.add(cancel, c); startConvertingNow = false; ActionListener driveButtons = new ActionListener() { public void actionPerformed(ActionEvent e) { Object subject = e.getSource(); if (subject == save) { long new_uid = Long.parseLong(choices[machine_choice.getSelectedIndex()]); machineConfiguration.LoadConfig(new_uid); SetDrawStyle(input_draw_style.getSelectedIndex()); machineConfiguration.paper_margin = (100 - input_paper_margin.getValue()) * 0.01; machineConfiguration.reverseForGlass = reverse_h.isSelected(); machineConfiguration.SaveConfig(); // if we aren't connected, don't show the new if (connectionToRobot != null && !connectionToRobot.isRobotConfirmed()) { // Force update of graphics layout. previewPane.updateMachineConfig(); // update window title mainframe.setTitle( translator.get("TitlePrefix") + Long.toString(machineConfiguration.robot_uid) + translator.get("TitleNotConnected")); } startConvertingNow = true; driver.dispose(); } if (subject == cancel) { driver.dispose(); } } }; save.addActionListener(driveButtons); cancel.addActionListener(driveButtons); driver.getRootPane().setDefaultButton(save); driver.pack(); driver.setVisible(true); return startConvertingNow; }
From source file:it.imtech.metadata.MetaUtility.java
private JComboBox getComboLangBox(String value) { LinkedHashMap<String, String> comboLang = new LinkedHashMap<String, String>(); int sel_index = 0; int index = 0; for (Map.Entry<String, String> vc : languages.entrySet()) { comboLang.put(vc.getValue(), vc.getKey()); if (Globals.CURRENT_LOCALE.getLanguage().equals(vc.getValue()) && value == null) { sel_index = index;/* w w w . j a v a 2s .co m*/ } else if (value != null) { if (value.equals(vc.getValue())) { sel_index = index; } } index++; } final ComboMapImpl model = new ComboMapImpl(); model.putAllLinked(comboLang); JComboBox result = new javax.swing.JComboBox(model); result.setSelectedIndex(sel_index); model.specialRenderCombo(result); return result; }
From source file:it.imtech.metadata.MetaUtility.java
private JComboBox addClassificationChoice(JPanel choice, final String sequence, final String panelname) { int selected = 0; int index = 0; int count = 1; for (Map.Entry<String, String> vc : availableClassifications.entrySet()) { if (count == 1 && !selectedClassificationList.containsKey(panelname + "---" + sequence)) { selected = index;/*w ww . j a va 2s. c o m*/ selectedClassificationList.put(panelname + "---" + sequence, vc.getKey()); } if (selectedClassificationList.containsKey(panelname + "---" + sequence)) { if (selectedClassificationList.get(panelname + "---" + sequence).equals(vc.getKey())) { selected = index; } } index++; } try { classifications_reader(sequence, panelname); } catch (Exception ex) { logger.error(ex.getMessage()); } final ComboMapImpl model = new ComboMapImpl(); model.putAllLinked(availableClassifications); JComboBox result = new javax.swing.JComboBox(model); result.setSelectedIndex(selected); model.specialRenderCombo(result); result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { BookImporter.getInstance().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); JComboBox comboBox = (JComboBox) event.getSource(); Map.Entry<String, String> c = (Map.Entry<String, String>) comboBox.getSelectedItem(); selectedClassificationList.put(panelname + "---" + sequence, c.getKey()); BookImporter.getInstance() .createComponentMap(BookImporter.getInstance().metadatapanels.get(panelname).getPanel()); JPanel innerPanel = (JPanel) BookImporter.getInstance() .getComponentByName(panelname + "---ImPannelloClassif---" + sequence); innerPanel.removeAll(); try { classifications_reader(sequence, panelname); addClassification(innerPanel, classificationMID, sequence, panelname); } catch (Exception ex) { logger.error(ex.getMessage()); } innerPanel.revalidate(); BookImporter.getInstance().setCursor(null); } }); return result; }
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 a 2 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; }