List of usage examples for javax.swing.event ListSelectionListener ListSelectionListener
ListSelectionListener
From source file:view.App.java
public void addData(final List<SpreadObject> spreadList) { Object rows[][] = new Object[spreadList.size()][4]; for (int j = 0; j < spreadList.size(); j++) { SpreadObject currPair = spreadList.get(j); int lastIndexBase = currPair.getBaseStock().getData().size(); int lastIndexSec = currPair.getSecondStock().getData().size(); DailyData firstVal = currPair.getBaseStock().getData().get(lastIndexBase - 1); DailyData secVal = currPair.getSecondStock().getData().get(lastIndexSec - 1); // int size = currPair.getData().size(); rows[j][0] = currPair.getBaseStock().getTicker(); rows[j][1] = firstVal.getAverVolatile().toPlainString(); rows[j][2] = currPair.getSecondStock().getTicker(); rows[j][3] = secVal.getAverVolatile().toPlainString(); }// w ww . j ava2 s. co m DefaultTableModel model = new DefaultTableModel(rows, new String[] { "", "MA Value", "", "MA Value" }) { public boolean isCellEditable(int row, int column) { return false; }; void reset() { this.setColumnCount(0); } }; jTable1.setModel(model); jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent arg0) { int selectedRow = jTable1.getSelectedRow(); SpreadObject obj = spreadList.get(selectedRow); renderChart(obj); } }); }
From source file:marytts.tools.redstart.AdminWindow.java
private void buildPromptTable() { this.promptArray = this.currentSession.getPromptArray(); System.out.println("Loading prompts..."); Test.output("Array contains " + promptArray.length + " prompts."); // Make column names array String[] columnNames = new String[3]; columnNames[REC_STATUS_COLUMN] = "Status"; columnNames[BASENAME_COLUMN] = "Basename"; columnNames[PROMPT_TEXT_COLUMN] = "Prompt Preview"; // Now create the table itself JTable table = new JTable(new PromptTableModel(promptArray, columnNames, redAlertMode)); table.setColumnSelectionAllowed(false); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Set alignment for the status colum to centered DefaultTableCellRenderer renderer = new ClippingColorRenderer(); renderer.setHorizontalAlignment(JTextField.CENTER); table.getColumnModel().getColumn(REC_STATUS_COLUMN).setCellRenderer(renderer); // Set selection highlight colour to light blue table.setSelectionBackground(new java.awt.Color(153, 204, 255)); // Add listeners table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent evt) { displayPromptText();//from w ww.j a va 2 s. co m } }); // Store the table in an instance field accessible to the entire class this.jTable_PromptSet = table; Thread recordingStatusInitialiser = new Thread() { public void run() { updateAllRecStatus(); } }; recordingStatusInitialiser.start(); // Display table in the appropriate component pane jScrollPane_PromptSet.setViewportView(table); if (promptArray.length > 0) { table.setRowSelectionInterval(0, 0); // Show first row of prompt table as selected displayPromptText(); // Display the prompt text for the first prompt in the prompt display pane } setColumnWidths(); System.out.println("Total " + table.getRowCount() + " prompts loaded."); }
From source file:edu.ku.brc.specify.utilapps.RegisterApp.java
/** * @return//from w ww . ja v a2 s . com */ private JPanel getStatsPane(final String chartPrefixTitle, final Collection<RegProcEntry> entries, final String tableName) { CellConstraints cc = new CellConstraints(); PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "f:p:g")); final Hashtable<String, String> keyDescPairsHash = rp.getAllDescPairsHash(); final Hashtable<String, String> desc2KeyPairsHash = new Hashtable<String, String>(); for (String key : keyDescPairsHash.keySet()) { desc2KeyPairsHash.put(keyDescPairsHash.get(key), key); } Vector<String> keywords = new Vector<String>(); for (String keyword : getKeyWordsList(entries)) { if (keyword.endsWith("_name") || keyword.endsWith("_type") || keyword.endsWith("ISA_Number") || keyword.endsWith("reg_isa")) { //keywords.add(keyword); } else { String desc = keyDescPairsHash.get(keyword); //System.out.println("["+keyword+"]->["+desc+"]"); if (desc != null) { keywords.add(desc); } else { System.out.println("Desc for keyword[" + keyword + "] is null."); } } } Vector<Object[]> rvList = BasicSQLUtils .query("SELECT DISTINCT(Name) FROM registeritem WHERE SUBSTRING(Name, 1, 4) = 'num_'"); for (Object[] array : rvList) { keywords.add((String) array[0]); } Collections.sort(keywords); final JList list = new JList(keywords); pb.add(UIHelper.createScrollPane(list), cc.xy(1, 1)); list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { String statName = (String) list.getSelectedValue(); if (desc2KeyPairsHash.get(statName) != null) { statName = desc2KeyPairsHash.get(statName); } DateType dateType = convertDateType(statName); if (dateType == DateType.None) { Vector<Pair<String, Integer>> values; if (statName.startsWith("num_")) { values = getCollNumValuesFromList(statName); Hashtable<String, Boolean> hash = new Hashtable<String, Boolean>(); for (Pair<String, Integer> p : values) { if (hash.get(p.first) == null) { hash.put(p.first, true); } else { int i = 0; String name = p.first; while (hash.get(p.first) != null) { p.first = name + " _" + i; i++; } hash.put(p.first, true); } //p.first += "(" + p.second.toString() + ")"; } } else { values = getCollValuesFromList(statName); } Collections.sort(values, countComparator); Vector<Pair<String, Integer>> top10Values = new Vector<Pair<String, Integer>>(); for (int i = 1; i < Math.min(11, values.size()); i++) { top10Values.insertElementAt(values.get(values.size() - i), 0); } createBarChart(chartPrefixTitle + " " + statName, statName, top10Values); } else { String desc = getByDateDesc(dateType); Vector<Pair<String, Integer>> values = tableName.equals("track") ? getDateValuesFromListByTable(dateType, tableName) : getDateValuesFromList(dateType); Collections.sort(values, titleComparator); createBarChart(chartPrefixTitle + " " + desc, desc, values); } } } }); return pb.getPanel(); }
From source file:de.tor.tribes.ui.windows.TribeTribeAttackFrame.java
/** * Creates new form TribeTribeAttackFrame *//* ww w .ja v a2s.co m*/ public TribeTribeAttackFrame() { initComponents(); centerPanel = new GenericTestPanel(); jMainPanel.add(centerPanel, BorderLayout.CENTER); centerPanel.setChildComponent(jxAttackPlanerPanel); buildMenu(); capabilityInfoPanel1.addActionListener(this, jSourcesTable); capabilityInfoPanel2.addActionListener(this, jResultsTable); KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK, false); KeyStroke bbCopy = KeyStroke.getKeyStroke(KeyEvent.VK_B, ActionEvent.CTRL_MASK, false); KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK, false); KeyStroke cut = KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK, false); KeyStroke delete = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, false); jSourcesTable.registerKeyboardAction(TribeTribeAttackFrame.this, "Copy", copy, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); jVictimTable.registerKeyboardAction(TribeTribeAttackFrame.this, "Copy", copy, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); jResultsTable.registerKeyboardAction(TribeTribeAttackFrame.this, "Copy", copy, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); jSourcesTable.registerKeyboardAction(TribeTribeAttackFrame.this, "Paste", paste, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); jVictimTable.registerKeyboardAction(TribeTribeAttackFrame.this, "Paste", paste, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); jSourcesTable.registerKeyboardAction(TribeTribeAttackFrame.this, "Cut", cut, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); jVictimTable.registerKeyboardAction(TribeTribeAttackFrame.this, "Cut", cut, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); jSourcesTable.registerKeyboardAction(TribeTribeAttackFrame.this, "Delete", delete, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); jVictimTable.registerKeyboardAction(TribeTribeAttackFrame.this, "Delete", delete, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); jResultsTable.registerKeyboardAction(TribeTribeAttackFrame.this, "Delete", delete, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); jResultsTable.registerKeyboardAction(TribeTribeAttackFrame.this, "BBCopy", bbCopy, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); Action noFind = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { //no find } }; jSourcesTable.getActionMap().put("find", noFind); jVictimTable.getActionMap().put("find", noFind); jResultsTable.getActionMap().put("find", noFind); jSourcesTable.getSelectionModel().addListSelectionListener(TribeTribeAttackFrame.this); jVictimTable.getSelectionModel().addListSelectionListener(TribeTribeAttackFrame.this); jResultsTable.getSelectionModel().addListSelectionListener(TribeTribeAttackFrame.this); jideTabbedPane1.setTabShape(JideTabbedPane.SHAPE_OFFICE2003); jideTabbedPane1.setTabColorProvider(JideTabbedPane.ONENOTE_COLOR_PROVIDER); jideTabbedPane1.setBoldActiveTab(true); TagManager.getSingleton().addManagerListener(TribeTribeAttackFrame.this); logPanel = new AlgorithmLogPanel(); mLogFrame = new JFrame("Informationen zur Berechnung"); mLogFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); mLogFrame.setLayout(new BorderLayout()); mLogFrame.add(logPanel); mLogFrame.pack(); mTroopSplitDialog = new TroopSplitDialog(TribeTribeAttackFrame.this, true); mSettingsPanel = new SettingsPanel(this); jSettingsContentPanel.add(mSettingsPanel, BorderLayout.CENTER); jAttackResultDetailsFrame.pack(); jTargetResultDetailsFrame.pack(); dragSource = DragSource.getDefaultDragSource(); dragSource.createDefaultDragGestureRecognizer(TribeTribeAttackFrame.this, DnDConstants.ACTION_COPY_OR_MOVE, TribeTribeAttackFrame.this); new DropTarget(jSourcesTable, TribeTribeAttackFrame.this); new DropTarget(jVictimTable, TribeTribeAttackFrame.this); for (MouseListener l : jAllTargetsComboBox.getMouseListeners()) { jAllTargetsComboBox.removeMouseListener(l); } jAllTargetsComboBox.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { fireAddFilteredTargetVillages(); } }); filterDialog = new TroopFilterDialog(this, true); // <editor-fold defaultstate="collapsed" desc="Add selection listeners"> jVillageGroupList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { fireFilterSourceVillagesByGroupEvent(); } } }); jSourceContinentList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { fireFilterSourceContinentEvent(); } } }); jTargetTribeList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { fireFilterTargetByTribeEvent(); } } }); jTargetContinentList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { fireFilterTargetByContinentEvent(); } } }); jTargetAllyList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { fireFilterTargetByAllyEvent(); } } }); // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" Init HelpSystem "> if (!Constants.DEBUG) { GlobalOptions.getHelpBroker().enableHelp(jSourcePanel, "pages.attack_planer_source", GlobalOptions.getHelpBroker().getHelpSet()); GlobalOptions.getHelpBroker().enableHelp(jTargetPanel, "pages.attack_planer_target", GlobalOptions.getHelpBroker().getHelpSet()); GlobalOptions.getHelpBroker().enableHelp(mSettingsPanel, "pages.attack_planer_settings", GlobalOptions.getHelpBroker().getHelpSet()); GlobalOptions.getHelpBroker().enableHelpKey(jResultFrame.getRootPane(), "pages.attack_planer_results", GlobalOptions.getHelpBroker().getHelpSet()); GlobalOptions.getHelpBroker().enableHelpKey(jTargetResultDetailsFrame.getRootPane(), "pages.attack_planer_results_details_targets", GlobalOptions.getHelpBroker().getHelpSet()); GlobalOptions.getHelpBroker().enableHelpKey(jAttackResultDetailsFrame.getRootPane(), "pages.attack_planer_results_details_sources", GlobalOptions.getHelpBroker().getHelpSet()); GlobalOptions.getHelpBroker().enableHelpKey(getRootPane(), "pages.attack_planer", GlobalOptions.getHelpBroker().getHelpSet()); } // </editor-fold> }
From source file:com.diversityarrays.kdxplore.heatmap.AskForPositionNamesAndTraitInstancePanel.java
public AskForPositionNamesAndTraitInstancePanel(int nPositionsWanted, int nTraitInstancesWanted, List<ValueRetriever<?>> positionAndPlotRetrievers, Map<TraitInstance, SimpleStatistics<?>> statsByTraitInstance, final Closure<Boolean> enableActionNotifier, CurationContext context) { super(new BorderLayout()); if (nPositionsWanted > 3) { // coz we only do X,Y,Z !! throw new IllegalArgumentException("At most 3 position names can be chosen"); }// w w w. ja v a 2 s .co m nPositionNamesToChoose = nPositionsWanted; nTraitInstancesToChoose = nTraitInstancesWanted; this.enableActionNotifier = enableActionNotifier; // this.traitInstanceIsAvailable = traitInstanceIsAvailable; this.statsByTraitInstance = statsByTraitInstance; traitInstancesX = new ArrayList<TraitInstance>(statsByTraitInstance.keySet()); Collections.sort(traitInstancesX, TraitHelper.COMPARATOR); List<ValueRetriever<?>> list = new ArrayList<ValueRetriever<?>>(); list.addAll(positionAndPlotRetrievers); Function<TraitInstance, List<KdxSample>> sampleProvider = new Function<TraitInstance, List<KdxSample>>() { @Override public List<KdxSample> apply(TraitInstance ti) { return context.getPlotInfoProvider().getSampleMeasurements(ti); } }; for (TraitInstance ti : traitInstancesX) { try { ValidationRule vrule = ValidationRule.create(ti.trait.getTraitValRule()); validationRuleByTraitInstance.put(ti, vrule); TraitInstanceValueRetriever<?> tivr = TraitInstanceValueRetriever .getValueRetriever(context.getTrial(), ti, sampleProvider); list.add(tivr); } catch (InvalidRuleException e) { validationRuleExceptionByTraitInstance.put(ti, e); } } tableModel.initialise(list); Box buttons = Box.createVerticalBox(); final List<AxisChoiceAction> axisChoiceActions = new ArrayList<>(); for (AxisChoice ac : AxisChoice.values()) { AxisChoiceAction action = new AxisChoiceAction(ac); action.setEnabled(false); axisChoiceActions.add(action); } buttons.add(new JLabel("Select Axis:")); for (AxisChoiceAction action : axisChoiceActions) { if (AxisChoice.Z == action.axisChoice) { buttons.add(Box.createVerticalStrut(10)); } buttons.add(new JButton(action)); if (AxisChoice.NOT_SELECTED == action.axisChoice) { buttons.add(Box.createVerticalStrut(10)); } } buttons.add(Box.createVerticalGlue()); table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { int mrow = -1; int vrow = table.getSelectedRow(); if (vrow >= 0) { mrow = table.convertRowIndexToModel(vrow); } if (mrow >= 0) { ValueRetriever<?> vr = tableModel.valueRetrievers.get(mrow); boolean isTraitInstance = vr instanceof TraitInstanceValueRetriever; for (AxisChoiceAction action : axisChoiceActions) { switch (action.axisChoice) { case NOT_SELECTED: case X: case Y: action.setEnabled(true); break; case Z: action.setEnabled(isTraitInstance); break; default: action.setEnabled(false); break; } } } else { for (AxisChoiceAction action : axisChoiceActions) { action.setEnabled(false); } } } } }); table.setDefaultRenderer(AxisChoice.class, new AxisChoiceRenderer("Not available", "*")); table.setDefaultRenderer(TraitInstance.class, new TraitInstanceRenderer()); String text = nTraitInstancesToChoose <= 1 ? "Select Axes and Value:" : "Select Axes and Values:"; JPanel traitInstancesPanel = new JPanel(new BorderLayout()); traitInstancesPanel.setBorder(new EmptyBorder(0, 10, 0, 0)); traitInstancesPanel.add(new JLabel(text), BorderLayout.NORTH); traitInstancesPanel.add(new JScrollPane(table), BorderLayout.CENTER); add(buttons, BorderLayout.WEST); add(traitInstancesPanel, BorderLayout.CENTER); if (!tableModel.excluded.isEmpty()) { JLabel lbl = new JLabel("TraitInstances without plottable data have been excluded"); lbl.setHorizontalAlignment(JLabel.CENTER); add(lbl, BorderLayout.SOUTH); // StringBuilder sb = new StringBuilder("<HTML>No Data:"); // for (ValueRetriever<?> vr : tableModel.excluded) { // sb.append("<BR>").append(StringUtil.htmlEscape(vr.getDisplayName())); // } // add(new JScrollPane(new JLabel(sb.toString())), BorderLayout.SOUTH); } }
From source file:com.microsoft.intellij.ui.AppInsightsMngmtPanel.java
private ListSelectionListener createAccountsTableListener() { return new ListSelectionListener() { @Override//from w w w . ja v a2 s. c o m public void valueChanged(ListSelectionEvent e) { boolean buttonsEnabled = insightsTable.getSelectedRow() > -1; detailsButton.setEnabled(buttonsEnabled); removeButton.setEnabled(buttonsEnabled); } }; }
From source file:edu.ku.brc.af.ui.forms.formatters.UIFormatterEditorDlg.java
/** * // w w w . j a v a 2 s . c o m */ private void hookFieldsTblSelectionListener() { if (fieldsTblSL == null) { fieldsTblSL = new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { checkForChanges(); int inx = fieldsTbl.getSelectedRow(); if (inx > -1) { currentField = fields.get(inx); fieldTypeCbx.setSelectedIndex(currentField.getType().ordinal()); isIncChk.setSelected(currentField.isIncrementer()); fieldTxt.setText(currentField.getValue()); sizeSpinner.setValue(Math.max(1, currentField.getSize())); enabledEditorUI(true); } else { fieldTypeCbx.setSelectedIndex(-1); enabledEditorUI(false); } fieldHasChanged = false; updateEnabledState(); } } }; } fieldsTbl.getSelectionModel().addListSelectionListener(fieldsTblSL); }
From source file:Main_Window.java
public void Send_Receive_Data_Google_Service(boolean State) { try {/*w ww . jav a 2 s . c o m*/ ServerAddress = new URL("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + Double.parseDouble(Latitude_TextField.getText()) + "," + Double.parseDouble(Longitude_TextField.getText()) + "&radius=" + Double.parseDouble(Radius_TextField.getText()) + "&opennow=" + Boolean.toString(State) + "&types=" + Categories.getSelectedItem().toString() + "&key=" + API_KEY); //DELTE String str = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + Double.parseDouble(Latitude_TextField.getText()) + "," + Double.parseDouble(Longitude_TextField.getText()) + "&radius=" + Double.parseDouble(Radius_TextField.getText()) + "&opennow=" + Boolean.toString(State) + "&types=" + Categories.getSelectedItem().toString() + "&key=" + API_KEY; System.out.println(" To url einai -> " + str); //set up out communications stuff Connection = null; //Set up the initial connection Connection = (HttpURLConnection) ServerAddress.openConnection(); Connection.setRequestMethod("GET"); Connection.setDoOutput(true); //Set the DoOutput flag to true if you intend to use the URL connection for output Connection.setDoInput(true); Connection.setRequestProperty("Content-type", "text/xml"); //Sets the general request property Connection.setAllowUserInteraction(false); Encode_String = URLEncoder.encode("test", "UTF-8"); Connection.setRequestProperty("Content-length", "" + Encode_String.length()); Connection.setReadTimeout(10000); // A non-zero value specifies the timeout when reading from Input stream when a connection is established to a resource. //If the timeout expires before there is data available for read, a java.net.SocketTimeoutException is raised. } catch (IOException IOE) { JOptionPane.showMessageDialog(null, "Error -> " + IOE.getLocalizedMessage(), "Exception - IOException", JOptionPane.ERROR_MESSAGE, null); } try { wr = new DataOutputStream(Connection.getOutputStream()); //open output stream to write } catch (IOException IOE) { JOptionPane.showMessageDialog(null, "Error -> " + IOE.getLocalizedMessage(), "Exception - IOException", JOptionPane.ERROR_MESSAGE, null); } try { wr.writeBytes("q=" + strData); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Error -> " + ex.getLocalizedMessage(), "Exception - IOException", JOptionPane.ERROR_MESSAGE, null); } try { wr.flush(); //Force all data to write in channel } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Error -> " + ex.getLocalizedMessage(), "Exception - IOException", JOptionPane.ERROR_MESSAGE, null); } try { //read the result from the server Buffered_Reader = new BufferedReader(new InputStreamReader(Connection.getInputStream())); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Error -> " + ex.getLocalizedMessage(), "Exception - IOException", JOptionPane.ERROR_MESSAGE, null); } jsonParser = new JSONParser(); //JSON Parser try { JsonObject = (JSONObject) jsonParser.parse(Buffered_Reader); //Parse whole BuffererReader IN Object JSONArray Results_Array_Json = (JSONArray) JsonObject.get("results"); //take whole array - from json format //results - is as string unique that contains all the essential information such as arrays, and strings. So to extract all info we extract results into JSONarray //And this comes up due to json format for (int i = 0; i < Results_Array_Json.size(); i++) // Loop over each each part of array that contains info we must extract { JSONObject o = (JSONObject) Results_Array_Json.get(i); try { //We assume that for every POI exists for sure an address !!! thats why the code is not insida a try-catch Temp_Name = (String) o.get("name"); Temp_Address = (String) o.get("vicinity"); JSONObject Str_1 = (JSONObject) o.get("geometry"); //Geometry is object so extract geometry JSONArray Photo_1 = (JSONArray) o.get("photos"); JSONObject Photo_2 = (JSONObject) Photo_1.get(0); String Photo_Ref = (String) Photo_2.get("photo_reference"); JSONObject Str_2 = (JSONObject) Str_1.get("location"); Temp_X = (double) Str_2.get("lat"); Temp_Y = (double) Str_2.get("lng"); //In case some POI has no Rating try { //Inside try-catch block because may some POI has no rating Temp_Rating = (double) o.get("rating"); Point POI_Object = new Point(Temp_Name, Temp_Address, Photo_Ref, Temp_Rating, Temp_X, Temp_Y); POI_List.add(POI_Object); //Add POI in List to keep it } catch (Exception Er) { //JOptionPane.showMessageDialog ( null, "No rating for this POI " ) ; Point POI_Object_2 = new Point(Temp_Name, Temp_Address, Photo_Ref, 0.0, Temp_X, Temp_Y); POI_List.add(POI_Object_2); //Add POI in List to keep it } } catch (Exception E) { //JOptionPane.showMessageDialog ( this, "Error -> " + E.getLocalizedMessage ( ) + ", " + E.getMessage ( ) ) ; } o.clear(); } } catch (ParseException PE) { JOptionPane.showMessageDialog(this, "Error -> " + PE.getLocalizedMessage(), "Parse, inside while JSON ERROR", JOptionPane.ERROR_MESSAGE, null); } catch (IOException IOE) { JOptionPane.showMessageDialog(this, "Error -> " + IOE.getLocalizedMessage(), "IOExcpiton", JOptionPane.ERROR_MESSAGE, null); } if (POI_List.isEmpty()) { JOptionPane.showMessageDialog(this, "No Results"); } else { //Calculate Distance every POI from Longitude and latitude of User for (int k = 0; k < POI_List.size(); k++) { double D1 = Double.parseDouble(Latitude_TextField.getText()) - POI_List.get(k).Get_Distance_X(); double D2 = Double.parseDouble(Longitude_TextField.getText()) - POI_List.get(k).Get_Distance_Y(); double a = pow(sin(D1 / 2), 2) + cos(POI_List.get(k).Get_Distance_X()) * cos(Double.parseDouble(Latitude_TextField.getText())) * pow(sin(D2 / 2), 2); double c = 2 * atan2(sqrt(a), sqrt(1 - a)); double d = 70000 * c; // (where R is the radius of the Earth) in meters //add to list Distances_List.add(d); } //COPY array because Distances_List will be corrupted for (int g = 0; g < Distances_List.size(); g++) { Distances_List_2.add(Distances_List.get(g)); } for (int l = 0; l < Distances_List.size(); l++) { int Dou = Distances_List.indexOf(Collections.min(Distances_List)); //Take the min , but the result is the position that the min is been placed Number_Name N = new Number_Name(POI_List.get(Dou).Get_Name()); //Create an object with the name of POI in the min position in the POI_List Temp_List.add(N); Distances_List.set(Dou, 9999.99); //Make the number in the min position so large so be able to find the next min } String[] T = new String[Temp_List.size()]; //String array to holds all names of POIS that are going to be dispayled in ascending order //DISPLAY POI IN JLIST - Create String Array with Names in ascending order to create JList for (int h = 0; h < Temp_List.size(); h++) { T[h] = Temp_List.get(h).Get_Name(); } //System.out.println ( " Size T -> " + T.length ) ; //Make JList and put String names list = new JList(T); list.setForeground(Color.BLACK); list.setBackground(Color.GRAY); list.setBounds(550, 140, 400, 400); //list.setSelectionMode ( ListSelectionModel.SINGLE_SELECTION ) ; JScrollPane p = new JScrollPane(list); P.add(p); setContentPane(pane); //OK list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { String selected = list.getSelectedValue().toString(); System.out.println("Selected string" + selected); for (int n = 0; n < POI_List.size(); n++) { if (selected.equals(POI_List.get(n).Get_Name())) { try { //read the result from the server BufferedImage img = null; URL u = new URL( "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=" + POI_List.get(n).Get_Photo_Ref() + "&key=" + API_KEY); Image image = ImageIO.read(u); IMAGE_LABEL.setText(""); IMAGE_LABEL.setIcon(new ImageIcon(image)); IMAGE_LABEL.setBounds(550, 310, 500, 200); //SOSOSOSOSOS pane.add(IMAGE_LABEL); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Error -> " + ex.getLocalizedMessage(), "Exception - IOException", JOptionPane.ERROR_MESSAGE, null); } Distance_L.setBounds(550, 460, 350, 150); Distance_L.setText(""); Distance_L.setText( "Distance from the current location: " + Distances_List_2.get(n) + "m"); pane.add(Distance_L); Address_L.setBounds(550, 500, 350, 150); Address_L.setText(""); Address_L.setText("Address: " + POI_List.get(n).Get_Address()); pane.add(Address_L); Rating_L.setBounds(550, 540, 350, 150); Rating_L.setText(""); Rating_L.setText("Rating: " + POI_List.get(n).Get_Rating()); pane.add(Rating_L); } } } }); } //Else not empty }
From source file:ru.apertum.qsystem.client.forms.FAdmin.java
/** * Creates new form FAdmin//from www .j av a 2 s. c om */ public FAdmin() { addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent e) { } @Override public void windowClosing(WindowEvent e) { timer.stop(); } @Override public void windowClosed(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { Uses.closeSplash(); } @Override public void windowDeactivated(WindowEvent e) { } }); initComponents(); setTitle(getTitle() + " " + Uses.getLocaleMessage("project.name" + FAbout.getCMRC_SUFF())); try { setIconImage( ImageIO.read(FAdmin.class.getResource("/ru/apertum/qsystem/client/forms/resources/admin.png"))); } catch (IOException ex) { System.err.println(ex); } // final Toolkit kit = Toolkit.getDefaultToolkit(); setLocation((Math.round(kit.getScreenSize().width - getWidth()) / 2), (Math.round(kit.getScreenSize().height - getHeight()) / 2)); // ? ? final JFrame fr = this; tray = QTray.getInstance(fr, "/ru/apertum/qsystem/client/forms/resources/admin.png", getLocaleMessage("tray.caption")); tray.addItem(getLocaleMessage("tray.caption"), (ActionEvent e) -> { setVisible(true); setState(JFrame.NORMAL); }); tray.addItem("-", (ActionEvent e) -> { }); tray.addItem(getLocaleMessage("tray.exit"), (ActionEvent e) -> { dispose(); System.exit(0); }); int ii = 1; final ButtonGroup bg = new ButtonGroup(); final String currLng = Locales.getInstance().getLangCurrName(); for (String lng : Locales.getInstance().getAvailableLocales()) { final JRadioButtonMenuItem item = new JRadioButtonMenuItem( org.jdesktop.application.Application.getInstance(ru.apertum.qsystem.QSystem.class).getContext() .getActionMap(FAdmin.class, fr).get("setCurrentLang")); bg.add(item); item.setSelected(lng.equals(currLng)); item.setText(lng); // NOI18N item.setName("QRadioButtonMenuItem" + (ii++)); // NOI18N menuLangs.add(item); } // ?? ??. listUsers.addListSelectionListener((ListSelectionEvent e) -> { userListChange(); }); // ?? ??. listResponse.addListSelectionListener((ListSelectionEvent e) -> { responseListChange(); }); listSchedule.addListSelectionListener((ListSelectionEvent e) -> { scheduleListChange(); }); listCalendar.addListSelectionListener(new ListSelectionListener() { private int oldSelectedValue = 0; private int tmp = 0; public int getOldSelectedValue() { return oldSelectedValue; } public void setOldSelectedValue(int oldSelectedValue) { this.oldSelectedValue = tmp; this.tmp = oldSelectedValue; } private boolean canceled = false; @Override public void valueChanged(ListSelectionEvent e) { if (canceled) { canceled = false; } else { if (tableCalendar.getModel() instanceof CalendarTableModel) { final CalendarTableModel model = (CalendarTableModel) tableCalendar.getModel(); if (!model.isSaved()) { final int res = JOptionPane.showConfirmDialog(null, getLocaleMessage("calendar.change.title"), getLocaleMessage("calendar.change.caption"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); switch (res) { case 0: // ? ?? model.save(); calendarListChange(); setOldSelectedValue(listCalendar.getSelectedIndex()); break; case 1: // ?? ?? calendarListChange(); setOldSelectedValue(listCalendar.getSelectedIndex()); break; case 2: // ?? ??? canceled = true; listCalendar.setSelectedIndex(getOldSelectedValue()); break; } } else { calendarListChange(); setOldSelectedValue(listCalendar.getSelectedIndex()); } } else { calendarListChange(); setOldSelectedValue(listCalendar.getSelectedIndex()); } } } }); // ?? ? ??. treeServices.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); treeInfo.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); /* treeServices.setCellRenderer(new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); setText(((Element) value).attributeValue(Uses.TAG_NAME)); return this; } });*/ treeServices.addTreeSelectionListener((TreeSelectionEvent e) -> { serviceListChange(); }); treeInfo.addTreeSelectionListener((TreeSelectionEvent e) -> { infoListChange(); }); textFieldStartTime.setInputVerifier(DateVerifier); textFieldFinishTime.setInputVerifier(DateVerifier); // ? loadSettings(); // ? ?. startTimer(); // loadConfig(); spinnerPropServerPort.getModel().addChangeListener(new ChangeNet()); spinnerPropClientPort.getModel().addChangeListener(new ChangeNet()); spinnerWebServerPort.getModel().addChangeListener(new ChangeNet()); spinnerServerPort.getModel().addChangeListener(new ChangeSettings()); spinnerClientPort.getModel().addChangeListener(new ChangeSettings()); spinnerUserRS.getModel().addChangeListener(new ChangeUser()); //? . final Helper helper = Helper.getHelp("ru/apertum/qsystem/client/help/admin.hs"); helper.setHelpListener(menuItemHelp); helper.enableHelpKey(jPanel1, "introduction"); helper.enableHelpKey(jPanel3, "monitoring"); helper.enableHelpKey(jPanel4, "configuring"); helper.enableHelpKey(jPanel8, "net"); helper.enableHelpKey(jPanel17, "schedulers"); helper.enableHelpKey(jPanel19, "calendars"); helper.enableHelpKey(jPanel2, "infoSystem"); helper.enableHelpKey(jPanel13, "responses"); helper.enableHelpKey(jPanel18, "results"); treeServices.setTransferHandler(new TransferHandler() { @Override public boolean canImport(TransferHandler.TransferSupport info) { final JTree.DropLocation dl = (JTree.DropLocation) info.getDropLocation(); if (dl.getChildIndex() == -1) { return false; } // Get the string that is being dropped. final Transferable t = info.getTransferable(); final QService data; try { data = (QService) t.getTransferData(DataFlavor.stringFlavor); return (data.getParent().getId() .equals(((QService) dl.getPath().getLastPathComponent()).getId())); } catch (UnsupportedFlavorException | IOException e) { return false; } } @Override public boolean importData(TransferHandler.TransferSupport info) { if (!info.isDrop()) { return false; } final QService data; try { data = (QService) info.getTransferable().getTransferData(DataFlavor.stringFlavor); } catch (UnsupportedFlavorException | IOException e) { System.err.println(e); return false; } final JTree.DropLocation dl = (JTree.DropLocation) info.getDropLocation(); final TreePath tp = dl.getPath(); final QService parent = (QService) tp.getLastPathComponent(); ((QServiceTree) treeServices.getModel()).moveNode(data, parent, dl.getChildIndex()); return true; } @Override public int getSourceActions(JComponent c) { return MOVE; } @Override protected Transferable createTransferable(JComponent c) { return (QService) ((JTree) c).getLastSelectedPathComponent(); } }); treeServices.setDropMode(DropMode.INSERT); // ? final AnnotationSessionFactoryBean as = (AnnotationSessionFactoryBean) Spring.getInstance().getFactory() .getBean("conf"); if (as.getServers().size() > 1) { final JMenu menu = new JMenu(getLocaleMessage("admin.servers")); as.getServers().stream().map((ser) -> { final JMenuItem mi1 = new JMenuItem(as); mi1.setText(ser.isCurrent() ? "<html><u><i>" + ser.getName() + "</i></u>" : ser.getName()); return mi1; }).forEach((mi1) -> { menu.add(mi1); }); jMenuBar1.add(menu, 4); jMenuBar1.add(new JLabel( "<html><span style='font-size:13.0pt;color:red'> [" + as.getName() + "]")); } comboBoxVoices.setVisible(false); }
From source file:de.codesourcery.eve.skills.ui.components.impl.AssetListComponent.java
@Override protected JPanel createPanel() { // Merge controls. final JPanel mergeControlsPanel = new JPanel(); mergeControlsPanel.setLayout(new GridBagLayout()); mergeControlsPanel.setBorder(BorderFactory.createTitledBorder("Merging")); int y = 0;//from w w w . java2 s . c o m // merge by type mergeAssetsByType.setSelected(true); mergeAssetsByType.addActionListener(actionListener); mergeControlsPanel.add(mergeAssetsByType, constraints(0, y).anchorWest().end()); mergeControlsPanel.add(new JLabel("Merge assets by type", SwingConstants.LEFT), constraints(1, y++).width(2).end()); // "ignore different packaging" ignorePackaging.setSelected(true); ignorePackaging.addActionListener(actionListener); mergeControlsPanel.add(new JLabel(""), constraints(0, y).anchorWest().end()); mergeControlsPanel.add(ignorePackaging, constraints(1, y).anchorWest().end()); final JLabel label1 = new JLabel("Merge different packaging", SwingConstants.RIGHT); mergeControlsPanel.add(label1, constraints(2, y++).end()); // "ignore different locations" ignoreLocations.setSelected(true); ignoreLocations.addActionListener(actionListener); mergeControlsPanel.add(new JLabel(""), constraints(0, y).anchorWest().end()); mergeControlsPanel.add(ignoreLocations, constraints(1, y).anchorWest().end()); final JLabel label2 = new JLabel("Merge different locations", SwingConstants.RIGHT); mergeControlsPanel.add(label2, constraints(2, y++).end()); linkComponentEnabledStates(mergeAssetsByType, ignoreLocations, ignorePackaging, label1, label2); /* * Filter controls. */ final JPanel filterControlsPanel = new JPanel(); filterControlsPanel.setLayout(new GridBagLayout()); filterControlsPanel.setBorder(BorderFactory.createTitledBorder("Filters")); y = 0; // filter by location combo box filterByLocation.addActionListener(actionListener); locationComboBox.addActionListener(actionListener); filterByLocation.setSelected(false); linkComponentEnabledStates(filterByLocation, locationComboBox); locationComboBox.setRenderer(new LocationRenderer()); locationComboBox.setPreferredSize(new Dimension(150, 20)); locationComboBox.setModel(locationModel); filterControlsPanel.add(filterByLocation, constraints(0, y).end()); filterControlsPanel.add(locationComboBox, constraints(1, y++).end()); // filter by type combo box filterByType.addActionListener(actionListener); typeComboBox.addActionListener(actionListener); filterByType.setSelected(false); linkComponentEnabledStates(filterByType, typeComboBox); typeComboBox.setPreferredSize(new Dimension(150, 20)); typeComboBox.setModel(typeModel); filterControlsPanel.add(filterByType, constraints(0, y).end()); filterControlsPanel.add(typeComboBox, constraints(1, y++).end()); // filter by item category combobox filterByCategory.addActionListener(actionListener); categoryComboBox.addActionListener(actionListener); categoryComboBox.setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); setText(getDisplayName((InventoryCategory) value)); setEnabled(categoryComboBox.isEnabled()); return this; } }); filterByCategory.setSelected(false); linkComponentEnabledStates(filterByCategory, categoryComboBox); categoryComboBox.setPreferredSize(new Dimension(150, 20)); categoryComboBox.setModel(categoryModel); filterControlsPanel.add(filterByCategory, constraints(0, y).end()); filterControlsPanel.add(categoryComboBox, constraints(1, y++).end()); // filter by item group combobox filterByGroup.addActionListener(actionListener); groupComboBox.addActionListener(actionListener); filterByGroup.setSelected(false); linkComponentEnabledStates(filterByGroup, groupComboBox); groupComboBox.setPreferredSize(new Dimension(150, 20)); groupComboBox.setModel(groupModel); filterControlsPanel.add(filterByGroup, constraints(0, y).end()); filterControlsPanel.add(groupComboBox, constraints(1, y++).end()); /* * Table panel. */ table = new JTable() { @Override public TableCellRenderer getCellRenderer(int row, int column) { // subclassing hack is needed because table // returns different renderes depending on column type final TableCellRenderer result = super.getCellRenderer(row, column); return new TableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { final Component comp = result.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); final int modelRow = table.convertRowIndexToModel(row); final Asset asset = model.getRow(modelRow); final StringBuilder label = new StringBuilder("<HTML><BODY>"); label.append(asset.getItemId() + " - flags: " + asset.getFlags() + "<BR>"); if (asset.hasMultipleLocations()) { label.append("<BR>"); for (ILocation loc : asset.getLocations()) { label.append(loc.getDisplayName()).append("<BR>"); } } label.append("</BODY></HTML>"); ((JComponent) comp).setToolTipText(label.toString()); return comp; } }; } }; model.setViewFilter(this.viewFilter); table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { updateSelectedVolume(); } }); FixedBooleanTableCellRenderer.attach(table); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setModel(model); table.setBorder(BorderFactory.createLineBorder(Color.BLACK)); table.setRowSorter(model.getRowSorter()); popupMenuBuilder.addItem("Refine...", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { final List<Asset> assets = getSelectedAssets(); if (assets == null || assets.isEmpty()) { return; } final ICharacter c = selectionProvider.getSelectedItem(); final RefiningComponent comp = new RefiningComponent(c); comp.setItemsToRefine(assets); ComponentWrapper.wrapComponent("Refining", comp).setVisible(true); } @Override public boolean isEnabled() { return table.getSelectedRow() != -1; } }); popupMenuBuilder.addItem("Copy selection to clipboard (text)", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { final List<Asset> assets = getSelectedAssets(); if (assets == null || assets.isEmpty()) { return; } new PlainTextTransferable(toPlainText(assets)).putOnClipboard(); } @Override public boolean isEnabled() { return table.getSelectedRow() != -1; } }); popupMenuBuilder.addItem("Copy selection to clipboard (CSV)", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { final List<Asset> assets = getSelectedAssets(); if (assets == null || assets.isEmpty()) { return; } final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(new PlainTextTransferable(toCsv(assets)), null); } @Override public boolean isEnabled() { return table.getSelectedRow() != -1; } }); table.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); this.popupMenuBuilder.attach(table); final JScrollPane scrollPane = new JScrollPane(table); /* * Name filter */ final JPanel nameFilterPanel = new JPanel(); nameFilterPanel.setLayout(new GridBagLayout()); nameFilterPanel.setBorder(BorderFactory.createTitledBorder("Filter by name")); nameFilterPanel.setPreferredSize(new Dimension(150, 70)); nameFilter.setColumns(10); nameFilter.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { model.viewFilterChanged(); } @Override public void insertUpdate(DocumentEvent e) { model.viewFilterChanged(); } @Override public void removeUpdate(DocumentEvent e) { model.viewFilterChanged(); } }); nameFilterPanel.add(nameFilter, constraints(0, 0).resizeHorizontally().end()); final JButton clearButton = new JButton("Clear"); clearButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { nameFilter.setText(null); } }); nameFilterPanel.add(clearButton, constraints(1, 0).noResizing().end()); // Selected volume final JPanel selectedVolumePanel = this.selectedVolume.getPanel(); // add control panels to result panel final JPanel topPanel = new JPanel(); topPanel.setLayout(new GridBagLayout()); topPanel.add(mergeControlsPanel, constraints(0, 0).height(2).weightX(0).anchorWest().end()); topPanel.add(filterControlsPanel, constraints(1, 0).height(2).anchorWest().weightX(0).end()); topPanel.add(nameFilterPanel, constraints(2, 0).height(1).anchorWest().useRemainingWidth().end()); topPanel.add(selectedVolumePanel, constraints(2, 1).height(1).anchorWest().useRemainingWidth().end()); final JSplitPane splitPane = new ImprovedSplitPane(JSplitPane.VERTICAL_SPLIT, topPanel, scrollPane); splitPane.setDividerLocation(0.3d); final JPanel content = new JPanel(); content.setLayout(new GridBagLayout()); content.add(splitPane, constraints().resizeBoth().useRemainingSpace().end()); return content; }