List of usage examples for javax.swing JTextField getText
public String getText()
TextComponent
. From source file:ucar.unidata.idv.flythrough.Flythrough.java
/** * _more_//from w w w . ja va 2 s . c o m * * @param fld _more_ * @param d _more_ * * @return _more_ */ private double parse(JTextField fld, double d) { String t = fld.getText().trim(); if (t.length() == 0) { return d; } if (t.equals("-")) { return d; } try { return Misc.parseNumber(t); } catch (NumberFormatException nfe) { animationWidget.setRunning(false); logException("Parse error:" + t, nfe); return d; } }
From source file:edu.ku.brc.af.auth.UserAndMasterPasswordMgr.java
/** * Displays a dialog used for editing the Master Username and Password. * @param isLocal whether u/p is stored locally or not * @param usrName/* w ww . j a v a 2 s . c om*/ * @param dbName * @param masterPath the path to the password * @return whether to ask for the information because it wasn't found */ protected boolean askForInfo(final Boolean isLocal, final String usrName, final String dbName, final String masterPath) { loadAndPushResourceBundle("masterusrpwd"); FormLayout layout = new FormLayout("p, 2px, f:p:g, 4px, p, 4px, p, 4px, p", "p,2px,p,2px,p,2dlu,p,2dlu,p"); PanelBuilder pb = new PanelBuilder(layout); pb.setDefaultDialogBorder(); ButtonGroup group = new ButtonGroup(); final JRadioButton isNetworkRB = new JRadioButton(getResourceString("IS_NET_BASED")); final JRadioButton isPrefBasedRB = new JRadioButton(getResourceString("IS_ENCRYPTED_KEY")); isPrefBasedRB.setSelected(true); group.add(isNetworkRB); group.add(isPrefBasedRB); final JTextField keyTxt = createTextField(35); final JTextField urlTxt = createTextField(35); final JLabel keyLbl = createI18NFormLabel("ENCRYPTED_USRPWD"); final JLabel urlLbl = createI18NFormLabel("URL"); final JButton createBtn = createI18NButton("CREATE_KEY"); final JButton copyCBBtn = createIconBtn("ClipboardCopy", IconManager.IconSize.Std24, "CPY_TO_CB_TT", null); final JButton pasteCBBtn = createIconBtn("ClipboardPaste", IconManager.IconSize.Std24, "CPY_FROM_CB_TT", null); // retrieves the encrypted key for the current settings in the dialog String dbNameFromForm = AppPreferences.getLocalPrefs().get("login.databases_selected", null); if (isNotEmpty(dbNameFromForm) && isNotEmpty(usersUserName)) { String masterKey = getMasterPrefPath(usersUserName, dbNameFromForm, true); if (isNotEmpty(masterKey)) { String encryptedKey = AppPreferences.getLocalPrefs().get(masterKey, null); if (isNotEmpty(encryptedKey) && !encryptedKey.startsWith("http")) { keyTxt.setText(encryptedKey); } } } CellConstraints cc = new CellConstraints(); int y = 1; pb.add(createI18NFormLabel("MASTER_LOC"), cc.xywh(1, y, 1, 3)); pb.add(isPrefBasedRB, cc.xy(3, y)); y += 2; pb.add(isNetworkRB, cc.xy(3, y)); y += 2; pb.addSeparator("", cc.xyw(1, y, 9)); y += 2; pb.add(keyLbl, cc.xy(1, y)); pb.add(keyTxt, cc.xy(3, y)); pb.add(createBtn, cc.xy(5, y)); pb.add(copyCBBtn, cc.xy(7, y)); pb.add(pasteCBBtn, cc.xy(9, y)); y += 2; pb.add(urlLbl, cc.xy(1, y)); pb.add(urlTxt, cc.xy(3, y)); y += 2; boolean isEditMode = isLocal != null && isNotEmpty(masterPath); if (isEditMode) { isPrefBasedRB.setSelected(isLocal); if (isLocal) { keyTxt.setText(masterPath); } else { urlTxt.setText(masterPath); } } copyCBBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Copy to Clipboard UIHelper.setTextToClipboard(keyTxt.getText()); } }); pasteCBBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { keyTxt.setText(UIHelper.getTextFromClipboard()); } }); final CustomDialog dlg = new CustomDialog((Frame) null, getResourceString("MASTER_TITLE"), true, CustomDialog.OKCANCELHELP, pb.getPanel()); if (!isEditMode) { dlg.setOkLabel(getResourceString("CONT")); dlg.setCancelLabel(getResourceString("BACK")); } dlg.setHelpContext("MASTERPWD_MAIN"); dlg.createUI(); dlg.getOkBtn().setEnabled(false); urlLbl.setEnabled(false); urlTxt.setEnabled(false); copyCBBtn.setEnabled(true); pasteCBBtn.setEnabled(true); DocumentListener dl = new DocumentAdaptor() { @Override protected void changed(DocumentEvent e) { dlg.getOkBtn().setEnabled((isPrefBasedRB.isSelected() && !keyTxt.getText().isEmpty()) || (isNetworkRB.isSelected() && !urlTxt.getText().isEmpty())); } }; keyTxt.getDocument().addDocumentListener(dl); urlTxt.getDocument().addDocumentListener(dl); ChangeListener chgListener = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { boolean isNet = isNetworkRB.isSelected(); keyLbl.setEnabled(!isNet); keyTxt.setEnabled(!isNet); createBtn.setEnabled(!isNet); copyCBBtn.setEnabled(!isNet); pasteCBBtn.setEnabled(!isNet); urlLbl.setEnabled(isNet); urlTxt.setEnabled(isNet); dlg.getOkBtn().setEnabled((isPrefBasedRB.isSelected() && !keyTxt.getText().isEmpty()) || (isNetworkRB.isSelected() && !urlTxt.getText().isEmpty())); } }; isNetworkRB.addChangeListener(chgListener); isPrefBasedRB.addChangeListener(chgListener); boolean isPref = AppPreferences.getLocalPrefs().getBoolean(getIsLocalPrefPath(usrName, dbName, true), true); isNetworkRB.setSelected(!isPref); isPrefBasedRB.setSelected(isPref); createBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String[] keys = getUserNamePasswordKey(); if (keys != null && keys.length == 4) { String encryptedStr = encrypt(keys[0], keys[1], keys[3]); if (encryptedStr != null) { keyTxt.setText(encryptedStr); dlg.getOkBtn().setEnabled(true); usersUserName = keys[2]; } } } }); popResourceBundle(); dlg.setVisible(true); if (!dlg.isCancelled()) { String value; if (isNetworkRB.isSelected()) { value = StringEscapeUtils.escapeHtml(urlTxt.getText()); } else { value = keyTxt.getText(); } AppPreferences.getLocalPrefs().putBoolean(getIsLocalPrefPath(usrName, dbName, true), !isNetworkRB.isSelected()); AppPreferences.getLocalPrefs().put(getMasterPrefPath(usrName, dbName, true), value); return true; } return false; }
From source file:GUI.MainWindow.java
public void addAffectedHost() { System.out.println("==addAffectedHost"); DefaultMutableTreeNode node = (DefaultMutableTreeNode) this.VulnTree.getLastSelectedPathComponent(); if (node == null) { return;//from www . ja v a 2 s .co m } Vulnerability vuln = (Vulnerability) node.getUserObject(); //ManageAffectedHosts.setVisible(true) ; // Old way of doing it JTextField ip_address = new JTextField(); JTextField hostname = new JTextField(); JTextField port_number = new JTextField(); port_number.setText("0"); JTextField protocol = new JTextField(); protocol.setText("tcp"); Object[] message = { "IP Address:", ip_address, "Hostname:", hostname, "Port Number:", port_number, "Protocol:", protocol }; String new_ip = null; String new_hostname = null; String new_port_number = null; String new_protocol = null; while (new_ip == null || new_hostname == null || new_port_number == null || new_protocol == null) { int option = JOptionPane.showConfirmDialog(null, message, "Add affected host", JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { new_ip = ip_address.getText(); new_hostname = hostname.getText(); new_port_number = port_number.getText(); new_protocol = protocol.getText(); Host host = new Host(); host.setIp_address(new_ip); host.setHostname(new_hostname); host.setPortnumber(new_port_number); host.setProtocol(new_protocol); vuln.addAffectedHost(host); DefaultTableModel dtm = (DefaultTableModel) this.VulnAffectedHostsTable.getModel(); dtm.addRow(host.getAsVector()); dtm.fireTableDataChanged(); } else { return; // End the infinite loop } } }
From source file:GUI.MainWindow.java
public void addReference(JTree tree, JList list, Reference current) { DefaultMutableTreeNode node = ((DefaultMutableTreeNode) tree.getLastSelectedPathComponent()); if (node == null) { return;//from w w w .j a v a 2s. co m } Object obj = node.getUserObject(); if (!(obj instanceof Vulnerability)) { return; // here be monsters, most likely in the merge tree } Vulnerability vuln = (Vulnerability) obj; DefaultListModel dlm = (DefaultListModel) list.getModel(); // Build Input Field and display it JTextField description = new JTextField(); JTextField url = new JTextField(); // If current is not null then pre-set the description and risk if (current != null) { description.setText(current.getDescription()); url.setText(current.getUrl()); } JLabel error = new JLabel( "A valid URL needs to be supplied including the protocol i.e. http://www.github.com"); error.setForeground(Color.red); Object[] message = { "Description:", description, "URL:", url }; String url_string = null; Reference newref = null; while (url_string == null) { int option = JOptionPane.showConfirmDialog(null, message, "Add Reference", JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { System.out.println("User clicked ok, validating data"); String ref_desc = description.getText(); String ref_url = url.getText(); if (!ref_desc.equals("") || !ref_url.equals("")) { // Both have values // Try to validate URL try { URL u = new URL(url.getText()); u.toURI(); url_string = url.getText(); // Causes loop to end with a valid url } catch (MalformedURLException ex) { url_string = null; //ex.printStackTrace(); } catch (URISyntaxException ex) { url_string = null; //ex.printStackTrace(); } } } else if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.CLOSED_OPTION) { System.out.println("User clicked cancel/close"); return; // ends the loop without making any chages } if (url_string == null) { // We need to show an error saying that the url failed to parse Object[] message2 = { error, "Description:", description, "URL:", url }; message = message2; } } // If you get here there is a valid reference URL and description Reference ref = new Reference(description.getText(), url.getText()); if (current == null) { // Add it to the vuln vuln.addReference(ref); // Add it to the GUI dlm.addElement(ref); System.out.println("Valid reference added: " + ref); } else { // Modify it in the vuln vuln.modifyReference(current, ref); // Update the GUI dlm.removeElement(current); dlm.addElement(ref); System.out.println("Valid reference modified: " + ref); } }
From source file:eu.crisis_economics.abm.dashboard.Page_Parameters.java
/** {@inheritDoc} *///from w w w.j a v a 2 s. c o m @Override public boolean onButtonPress(final Button button) { if (Button.NEXT.equals(button)) { ParameterTree parameterTree = null; if (tabbedPane.getSelectedIndex() == SINGLE_RUN_GUI_TABINDEX) { currentModelHandler.setIntelliMethodPlugin(null); parameterTree = new ParameterTree(); final Set<ParameterInfo> invalids = new HashSet<ParameterInfo>(); @SuppressWarnings("rawtypes") final Enumeration treeValues = parameterValueComponentTree.breadthFirstEnumeration(); treeValues.nextElement(); // root element while (treeValues.hasMoreElements()) { final DefaultMutableTreeNode node = (DefaultMutableTreeNode) treeValues.nextElement(); @SuppressWarnings("unchecked") final Pair<ParameterInfo, JComponent> userData = (Pair<ParameterInfo, JComponent>) node .getUserObject(); final ParameterInfo parameterInfo = userData.getFirst(); final JComponent valueContainer = userData.getSecond(); if (parameterInfo instanceof ISubmodelGUIInfo) { final ISubmodelGUIInfo sgi = (ISubmodelGUIInfo) parameterInfo; if (sgi.getParent() != null) { final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) node.getParent(); @SuppressWarnings("unchecked") final Pair<ParameterInfo, JComponent> parentUserData = (Pair<ParameterInfo, JComponent>) parentNode .getUserObject(); final SubmodelInfo parentParameterInfo = (SubmodelInfo) parentUserData.getFirst(); if (invalids.contains(parentParameterInfo) || !classEquals(parentParameterInfo.getActualType(), sgi.getParentValue())) { invalids.add(parameterInfo); continue; } } } if (parameterInfo.isBoolean()) { final JCheckBox checkBox = (JCheckBox) valueContainer; parameterInfo.setValue(checkBox.isSelected()); } else if (parameterInfo.isEnum()) { final JComboBox comboBox = (JComboBox) valueContainer; parameterInfo.setValue(comboBox.getSelectedItem()); } else if (parameterInfo instanceof MasonChooserParameterInfo) { final JComboBox comboBox = (JComboBox) valueContainer; parameterInfo.setValue(comboBox.getSelectedIndex()); } else if (parameterInfo instanceof SubmodelInfo) { // we don't need the SubmodelInfo parameters anymore (all descendant parameters are in the tree too) // but we need to check that an actual type is provided final SubmodelInfo smi = (SubmodelInfo) parameterInfo; final JComboBox comboBox = (JComboBox) ((JPanel) valueContainer).getComponent(0); final ClassElement selected = (ClassElement) comboBox.getSelectedItem(); smi.setActualType(selected.clazz, selected.instance); if (smi.getActualType() == null) { final String errorMsg = "Please select a type from the dropdown list of " + smi.getName().replaceAll("([A-Z])", " $1"); JOptionPane.showMessageDialog(wizard, new JLabel(errorMsg), "Error", JOptionPane.ERROR_MESSAGE); return false; } //continue; } else if (parameterInfo.isFile()) { final JTextField textField = (JTextField) valueContainer.getComponent(0); if (textField.getText().trim().isEmpty()) log.warn("Empty string was specified as file parameter " + parameterInfo.getName().replaceAll("([A-Z])", " $1")); final File file = new File(textField.getToolTipText()); if (!file.exists()) { final String errorMsg = "Please specify an existing file parameter " + parameterInfo.getName().replaceAll("([A-Z])", " $1"); JOptionPane.showMessageDialog(wizard, new JLabel(errorMsg), "Error", JOptionPane.ERROR_MESSAGE); return false; } parameterInfo.setValue( ParameterInfo.getValue(textField.getToolTipText(), parameterInfo.getType())); } else if (parameterInfo instanceof MasonIntervalParameterInfo) { final JTextField textField = (JTextField) valueContainer.getComponent(0); parameterInfo.setValue( ParameterInfo.getValue(textField.getText().trim(), parameterInfo.getType())); } else { final JTextField textField = (JTextField) valueContainer; parameterInfo .setValue(ParameterInfo.getValue(textField.getText(), parameterInfo.getType())); if ("String".equals(parameterInfo.getType()) && parameterInfo.getValue() == null) parameterInfo.setValue(textField.getText().trim()); } final AbstractParameterInfo<?> batchParameterInfo = InfoConverter .parameterInfo2ParameterInfo(parameterInfo); parameterTree.addNode(batchParameterInfo); } dashboard.setOnLineCharts(onLineChartsCheckBox.isSelected()); dashboard.setDisplayAdvancedCharts(advancedChartsCheckBox.isSelected()); } if (tabbedPane.getSelectedIndex() == PARAMSWEEP_GUI_TABINDEX) { currentModelHandler.setIntelliMethodPlugin(null); boolean success = true; if (editedNode != null) success = modify(); if (success) { String invalidInfoName = checkInfos(true); if (invalidInfoName != null) { Utilities.userAlert(sweepPanel, "Please select a type from the dropdown list of " + invalidInfoName); return false; } invalidInfoName = checkInfos(false); if (invalidInfoName != null) { Utilities.userAlert(sweepPanel, "Please specify a file for parameter " + invalidInfoName); return false; } if (needWarning()) { final int result = Utilities.askUser(sweepPanel, false, "Warning", "There are two or more combination boxes that contains non-constant parameters." + " Parameters are unsynchronized:", "simulation may exit before all parameter values are assigned.", " ", "To explore all possible combinations you must use only one combination box.", " ", "Do you want to run simulation with these parameter settings?"); if (result == 0) { return false; } } try { parameterTree = createParameterTreeFromParamSweepGUI(); final ParameterNode rootNode = parameterTree.getRoot(); dumpParameterTree(rootNode); // dashboard.setOnLineCharts(onLineChartsCheckBoxPSW.isSelected()); } catch (final ModelInformationException e) { JOptionPane.showMessageDialog(wizard, new JLabel(e.getMessage()), "Error while creating runs", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); return false; } } else return false; } if (tabbedPane.getSelectedIndex() == GASEARCH_GUI_TABINDEX) { final IIntelliDynamicMethodPlugin gaPlugin = (IIntelliDynamicMethodPlugin) gaSearchHandler; currentModelHandler.setIntelliMethodPlugin(gaPlugin); boolean success = gaSearchPanel.closeActiveModification(); if (success) { String invalidInfoName = checkInfosInGeneTree(); if (invalidInfoName != null) { Utilities.userAlert(sweepPanel, "Please select a type from the dropdown list of " + invalidInfoName); return false; } final String[] errors = gaSearchHandler.checkGAModel(); if (errors != null) { Utilities.userAlert(sweepPanel, (Object[]) errors); return false; } final DefaultMutableTreeNode parameterTreeRootNode = new DefaultMutableTreeNode(); final IIntelliContext ctx = new DashboardIntelliContext(parameterTreeRootNode, gaSearchHandler.getChromosomeTree()); gaPlugin.alterParameterTree(ctx); parameterTree = InfoConverter.node2ParameterTree(parameterTreeRootNode); dashboard.setOptimizationDirection(gaSearchHandler.getFitnessFunctionDirection()); } else return false; } currentModelHandler.setParameters(parameterTree); } return true; }
From source file:com.nikonhacker.gui.EmulatorUI.java
private void openDecodeDialog() { JTextField sourceFile = new JTextField(); JTextField destinationDir = new JTextField(); FileSelectionPanel sourceFileSelectionPanel = new FileSelectionPanel("Source file", sourceFile, false); sourceFileSelectionPanel.setFileFilter(".bin", "Firmware file (*.bin)"); final JComponent[] inputs = new JComponent[] { sourceFileSelectionPanel, new FileSelectionPanel("Destination dir", destinationDir, true) }; if (JOptionPane.OK_OPTION == JOptionPane.showOptionDialog(this, inputs, "Choose source file and destination dir", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, JOptionPane.DEFAULT_OPTION)) { try {//from w w w .java 2s . com new FirmwareDecoder().decode(sourceFile.getText(), destinationDir.getText(), false); JOptionPane.showMessageDialog(this, "Decoding complete", "Done", JOptionPane.INFORMATION_MESSAGE); } catch (FirmwareFormatException e) { JOptionPane.showMessageDialog(this, e.getMessage() + "\nPlease see console for full stack trace", "Error decoding files", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } }
From source file:com.nikonhacker.gui.EmulatorUI.java
private void openDecodeNkldDialog() { JTextField sourceFile = new JTextField(); JTextField destinationFile = new JTextField(); FileSelectionPanel sourceFileSelectionPanel = new FileSelectionPanel("Source file", sourceFile, false); sourceFileSelectionPanel.setFileFilter("nkld*.bin", "Lens correction data file (nkld*.bin)"); final JComponent[] inputs = new JComponent[] { sourceFileSelectionPanel, new FileSelectionPanel("Destination file", destinationFile, true) }; if (JOptionPane.OK_OPTION == JOptionPane.showOptionDialog(this, inputs, "Choose source file and destination dir", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, JOptionPane.DEFAULT_OPTION)) { try {//from ww w.ja va2 s .co m new NkldDecoder().decode(sourceFile.getText(), destinationFile.getText(), false); JOptionPane .showMessageDialog( this, "Decoding complete.\nFile '" + new File(destinationFile.getText()).getAbsolutePath() + "' was created.", "Done", JOptionPane.INFORMATION_MESSAGE); } catch (FirmwareFormatException e) { JOptionPane.showMessageDialog(this, e.getMessage() + "\nPlease see console for full stack trace", "Error decoding files", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } }
From source file:eu.crisis_economics.abm.dashboard.Page_Parameters.java
private void saveSubTree(@SuppressWarnings("rawtypes") final Enumeration children, final List<Parameter> parameterList, final List<SubmodelParameter> submodelParameterList, final Set<ParameterInfo> invalids) throws IOException { final ObjectFactory factory = new ObjectFactory(); while (children.hasMoreElements()) { final DefaultMutableTreeNode node = (DefaultMutableTreeNode) children.nextElement(); @SuppressWarnings("unchecked") final Pair<ParameterInfo, JComponent> userData = (Pair<ParameterInfo, JComponent>) node.getUserObject(); final ParameterInfo parameterInfo = userData.getFirst(); final JComponent valueContainer = userData.getSecond(); Parameter parameter = null; SubmodelParameter submodelParameter = null; if (parameterInfo instanceof ISubmodelGUIInfo) { final ISubmodelGUIInfo sgi = (ISubmodelGUIInfo) parameterInfo; if (sgi.getParent() != null) { final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) node.getParent(); @SuppressWarnings("unchecked") final Pair<ParameterInfo, JComponent> parentUserData = (Pair<ParameterInfo, JComponent>) parentNode .getUserObject(); final SubmodelInfo parentParameterInfo = (SubmodelInfo) parentUserData.getFirst(); if (invalids.contains(parentParameterInfo) || !classEquals(parentParameterInfo.getActualType(), sgi.getParentValue())) { invalids.add(parameterInfo); continue; }//from w w w. j a v a 2s. com } } if (parameterInfo instanceof SubmodelInfo) { submodelParameter = factory.createSubmodelParameter(); submodelParameter.setName(parameterInfo.getName()); } else { parameter = factory.createParameter(); parameter.setName(parameterInfo.getName()); } if (parameterInfo.isBoolean()) { final JCheckBox checkBox = (JCheckBox) valueContainer; parameter.getContent().add(String.valueOf(checkBox.isSelected())); } else if (parameterInfo.isEnum()) { final JComboBox comboBox = (JComboBox) valueContainer; parameter.getContent().add(String.valueOf(comboBox.getSelectedItem())); } else if (parameterInfo instanceof MasonChooserParameterInfo) { final JComboBox comboBox = (JComboBox) valueContainer; parameter.getContent().add(String.valueOf(comboBox.getSelectedIndex())); } else if (parameterInfo instanceof SubmodelInfo) { final JComboBox comboBox = (JComboBox) ((JPanel) valueContainer).getComponent(0); final ClassElement selectedElement = (ClassElement) comboBox.getSelectedItem(); if (selectedElement.clazz == null) throw new IOException("No type is selected for parameter " + parameterInfo.getName().replaceAll("([A-Z])", " $1") + "."); submodelParameter.setType(selectedElement.clazz.getName()); saveSubTree(node.children(), submodelParameter.getParameterList(), submodelParameter.getSubmodelParameterList(), invalids); } else if (parameterInfo.isFile()) { final JTextField textField = (JTextField) valueContainer.getComponent(0); parameter.getContent().add(textField.getToolTipText()); } else if (parameterInfo instanceof MasonIntervalParameterInfo) { final JTextField textField = (JTextField) valueContainer.getComponent(0); parameter.getContent().add(textField.getText().trim()); } else { final JTextField textField = (JTextField) valueContainer; String text = String.valueOf(ParameterInfo.getValue(textField.getText(), parameterInfo.getType())); if ("String".equals(parameterInfo.getType()) && parameterInfo.getValue() == null) text = textField.getText().trim(); parameter.getContent().add(text); } if (parameter != null) parameterList.add(parameter); else if (submodelParameter != null) submodelParameterList.add(submodelParameter); } }
From source file:eu.crisis_economics.abm.dashboard.Page_Parameters.java
@SuppressWarnings("unchecked") private List<ParameterInfo> createAndDisplayAParameterPanel( final List<ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?>> batchParameters, final String title, final SubmodelInfo parent, final boolean submodelSelectionWithoutNotify, final IModelHandler currentModelHandler) { final List<ParameterMetaData> metadata = new LinkedList<ParameterMetaData>(), unknownFields = new ArrayList<ParameterMetaData>(); for (final ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?> record : batchParameters) { final String parameterName = record.getName(), fieldName = StringUtils.uncapitalize(parameterName); Class<?> modelComponentType = parent == null ? currentModelHandler.getModelClass() : parent.getActualType(); while (true) { try { final Field field = modelComponentType.getDeclaredField(fieldName); final ParameterMetaData datum = new ParameterMetaData(); for (final Annotation element : field.getAnnotations()) { if (element.annotationType().getName() != Layout.class.getName()) // Proxies continue; final Class<? extends Annotation> type = element.annotationType(); datum.verboseDescription = (String) type.getMethod("VerboseDescription").invoke(element); datum.banner = (String) type.getMethod("Title").invoke(element); datum.fieldName = (String) " " + type.getMethod("FieldName").invoke(element); datum.imageFileName = (String) type.getMethod("Image").invoke(element); datum.layoutOrder = (Double) type.getMethod("Order").invoke(element); }/*from ww w . j ava 2 s . com*/ datum.parameter = record; if (datum.fieldName.trim().isEmpty()) datum.fieldName = parameterName.replaceAll("([A-Z])", " $1"); metadata.add(datum); break; } catch (final SecurityException e) { } catch (final NoSuchFieldException e) { } catch (final IllegalArgumentException e) { } catch (final IllegalAccessException e) { } catch (final InvocationTargetException e) { } catch (final NoSuchMethodException e) { } modelComponentType = modelComponentType.getSuperclass(); if (modelComponentType == null) { ParameterMetaData.createAndRegisterUnknown(fieldName, record, unknownFields); break; } } } Collections.sort(metadata); for (int i = unknownFields.size() - 1; i >= 0; --i) metadata.add(0, unknownFields.get(i)); // initialize single run form final DefaultFormBuilder formBuilder = FormsUtils.build("p ~ p:g", ""); appendMinimumWidthHintToPresentation(formBuilder, 550); if (parent == null) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { numberOfTurnsField.grabFocus(); } }); appendBannerToPresentation(formBuilder, "General Parameters"); appendTextToPresentation(formBuilder, "Global parameters affecting the entire simulation"); formBuilder.append(NUMBER_OF_TURNS_LABEL_TEXT, numberOfTurnsField); formBuilder.append(NUMBER_OF_TIMESTEPS_TO_IGNORE_LABEL_TEXT, numberTimestepsIgnored); appendCheckBoxFieldToPresentation(formBuilder, UPDATE_CHARTS_LABEL_TEXT, onLineChartsCheckBox); appendCheckBoxFieldToPresentation(formBuilder, DISPLAY_ADVANCED_CHARTS_LABEL_TEXT, advancedChartsCheckBox); } appendBannerToPresentation(formBuilder, title); final DefaultMutableTreeNode parentNode = (parent == null) ? parameterValueComponentTree : findParameterInfoNode(parent, false); final List<ParameterInfo> info = new ArrayList<ParameterInfo>(); // Search for a @ConfigurationComponent annotation { String headerText = "", imagePath = ""; final Class<?> parentType = parent == null ? currentModelHandler.getModelClass() : parent.getActualType(); for (final Annotation element : parentType.getAnnotations()) { // Proxies if (element.annotationType().getName() != ConfigurationComponent.class.getName()) continue; boolean doBreak = false; try { try { headerText = (String) element.annotationType().getMethod("Description").invoke(element); if (headerText.startsWith("#")) { headerText = (String) parent.getActualType().getMethod(headerText.substring(1)) .invoke(parent.getInstance()); } doBreak = true; } catch (IllegalArgumentException e) { } catch (SecurityException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } catch (NoSuchMethodException e) { } } catch (final Exception e) { } try { imagePath = (String) element.annotationType().getMethod("ImagePath").invoke(element); doBreak = true; } catch (IllegalArgumentException e) { } catch (SecurityException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } catch (NoSuchMethodException e) { } if (doBreak) break; } if (!headerText.isEmpty()) appendHeaderTextToPresentation(formBuilder, headerText); if (!imagePath.isEmpty()) appendImageToPresentation(formBuilder, imagePath); } if (metadata.isEmpty()) { // No fields to display. appendTextToPresentation(formBuilder, "No configuration is required for this module."); } else { for (final ParameterMetaData record : metadata) { final ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?> batchParameterInfo = record.parameter; if (!record.banner.isEmpty()) appendBannerToPresentation(formBuilder, record.banner); if (!record.imageFileName.isEmpty()) appendImageToPresentation(formBuilder, record.imageFileName); appendTextToPresentation(formBuilder, record.verboseDescription); final ParameterInfo parameterInfo = InfoConverter.parameterInfo2ParameterInfo(batchParameterInfo); if (parent != null && parameterInfo instanceof ISubmodelGUIInfo) { // sgi.setParentValue(parent.getActualType()); } final JComponent field; final DefaultMutableTreeNode oldNode = findParameterInfoNode(parameterInfo, true); Pair<ParameterInfo, JComponent> userData = null; JComponent oldField = null; if (oldNode != null) { userData = (Pair<ParameterInfo, JComponent>) oldNode.getUserObject(); oldField = userData.getSecond(); } if (parameterInfo.isBoolean()) { field = new JCheckBox(); boolean value = oldField != null ? ((JCheckBox) oldField).isSelected() : ((Boolean) batchParameterInfo.getDefaultValue()).booleanValue(); ((JCheckBox) field).setSelected(value); } else if (parameterInfo.isEnum() || parameterInfo instanceof MasonChooserParameterInfo) { Object[] elements = null; if (parameterInfo.isEnum()) { final Class<Enum<?>> type = (Class<Enum<?>>) parameterInfo.getJavaType(); elements = type.getEnumConstants(); } else { final MasonChooserParameterInfo chooserInfo = (MasonChooserParameterInfo) parameterInfo; elements = chooserInfo.getValidStrings(); } final JComboBox list = new JComboBox(elements); if (parameterInfo.isEnum()) { final Object value = oldField != null ? ((JComboBox) oldField).getSelectedItem() : parameterInfo.getValue(); list.setSelectedItem(value); } else { final int value = oldField != null ? ((JComboBox) oldField).getSelectedIndex() : (Integer) parameterInfo.getValue(); list.setSelectedIndex(value); } field = list; } else if (parameterInfo instanceof SubmodelInfo) { final SubmodelInfo submodelInfo = (SubmodelInfo) parameterInfo; final Object[] elements = new Object[] { "Loading class information..." }; final JComboBox list = new JComboBox(elements); // field = list; final Object value = oldField != null ? ((JComboBox) ((JPanel) oldField).getComponent(0)).getSelectedItem() : new ClassElement(submodelInfo.getActualType(), null); new ClassCollector(this, list, submodelInfo, value, submodelSelectionWithoutNotify).execute(); final JButton rightButton = new JButton(); rightButton.setOpaque(false); rightButton.setRolloverEnabled(true); rightButton.setIcon(SHOW_SUBMODEL_ICON); rightButton.setRolloverIcon(SHOW_SUBMODEL_ICON_RO); rightButton.setDisabledIcon(SHOW_SUBMODEL_ICON_DIS); rightButton.setBorder(null); rightButton.setToolTipText("Display submodel parameters"); rightButton.setActionCommand(ACTIONCOMMAND_SHOW_SUBMODEL); rightButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (parameterInfo instanceof SubmodelInfo) { SubmodelInfo submodelInfo = (SubmodelInfo) parameterInfo; int level = 0; showHideSubparameters(list, submodelInfo); List<String> components = new ArrayList<String>(); components.add(submodelInfo.getName()); while (submodelInfo.getParent() != null) { submodelInfo = submodelInfo.getParent(); components.add(submodelInfo.getName()); level++; } Collections.reverse(components); final String[] breadcrumbText = components.toArray(new String[components.size()]); for (int i = 0; i < breadcrumbText.length; ++i) breadcrumbText[i] = breadcrumbText[i].replaceAll("([A-Z])", " $1"); breadcrumb.setPath( currentModelHandler.getModelClassSimpleName().replaceAll("([A-Z])", " $1"), breadcrumbText); Style.apply(breadcrumb, dashboard.getCssStyle()); // reset all buttons that are nested deeper than this to default color for (int i = submodelButtons.size() - 1; i >= level; i--) { JButton button = submodelButtons.get(i); button.setIcon(SHOW_SUBMODEL_ICON); submodelButtons.remove(i); } rightButton.setIcon(SHOW_SUBMODEL_ICON_RO); submodelButtons.add(rightButton); } } }); field = new JPanel(new BorderLayout()); field.add(list, BorderLayout.CENTER); field.add(rightButton, BorderLayout.EAST); } else if (File.class.isAssignableFrom(parameterInfo.getJavaType())) { field = new JPanel(new BorderLayout()); String oldName = ""; String oldPath = ""; if (oldField != null) { final JTextField oldTextField = (JTextField) oldField.getComponent(0); oldName = oldTextField.getText(); oldPath = oldTextField.getToolTipText(); } else if (parameterInfo.getValue() != null) { final File file = (File) parameterInfo.getValue(); oldName = file.getName(); oldPath = file.getAbsolutePath(); } final JTextField textField = new JTextField(oldName); textField.setToolTipText(oldPath); textField.setInputVerifier(new InputVerifier() { @Override public boolean verify(final JComponent input) { final JTextField inputField = (JTextField) input; if (inputField.getText() == null || inputField.getText().isEmpty()) { final File file = new File(""); inputField.setToolTipText(file.getAbsolutePath()); hideError(); return true; } final File oldFile = new File(inputField.getToolTipText()); if (oldFile.exists() && oldFile.getName().equals(inputField.getText().trim())) { hideError(); return true; } inputField.setToolTipText(""); final File file = new File(inputField.getText().trim()); if (file.exists()) { inputField.setToolTipText(file.getAbsolutePath()); inputField.setText(file.getName()); hideError(); return true; } else { final PopupFactory popupFactory = PopupFactory.getSharedInstance(); final Point locationOnScreen = inputField.getLocationOnScreen(); final JLabel message = new JLabel("Please specify an existing file!"); message.setBorder(new LineBorder(Color.RED, 2, true)); if (errorPopup != null) errorPopup.hide(); errorPopup = popupFactory.getPopup(inputField, message, locationOnScreen.x - 10, locationOnScreen.y - 30); errorPopup.show(); return false; } } }); final JButton browseButton = new JButton(BROWSE_BUTTON_TEXT); browseButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final JFileChooser fileDialog = new JFileChooser( !"".equals(textField.getToolTipText()) ? textField.getToolTipText() : currentDirectory); if (!"".equals(textField.getToolTipText())) fileDialog.setSelectedFile(new File(textField.getToolTipText())); int dialogResult = fileDialog.showOpenDialog(dashboard); if (dialogResult == JFileChooser.APPROVE_OPTION) { final File selectedFile = fileDialog.getSelectedFile(); if (selectedFile != null) { currentDirectory = selectedFile.getAbsoluteFile().getParent(); textField.setText(selectedFile.getName()); textField.setToolTipText(selectedFile.getAbsolutePath()); } } } }); field.add(textField, BorderLayout.CENTER); field.add(browseButton, BorderLayout.EAST); } else if (parameterInfo instanceof MasonIntervalParameterInfo) { final MasonIntervalParameterInfo intervalInfo = (MasonIntervalParameterInfo) parameterInfo; field = new JPanel(new BorderLayout()); String oldValueStr = String.valueOf(parameterInfo.getValue()); if (oldField != null) { final JTextField oldTextField = (JTextField) oldField.getComponent(0); oldValueStr = oldTextField.getText(); } final JTextField textField = new JTextField(oldValueStr); PercentJSlider tempSlider = null; if (intervalInfo.isDoubleInterval()) tempSlider = new PercentJSlider(intervalInfo.getIntervalMin().doubleValue(), intervalInfo.getIntervalMax().doubleValue(), Double.parseDouble(oldValueStr)); else tempSlider = new PercentJSlider(intervalInfo.getIntervalMin().longValue(), intervalInfo.getIntervalMax().longValue(), Long.parseLong(oldValueStr)); final PercentJSlider slider = tempSlider; slider.setMajorTickSpacing(100); slider.setMinorTickSpacing(10); slider.setPaintTicks(true); slider.setPaintLabels(true); slider.addChangeListener(new ChangeListener() { public void stateChanged(final ChangeEvent _) { if (slider.hasFocus()) { final String value = intervalInfo.isDoubleInterval() ? String.valueOf(slider.getDoubleValue()) : String.valueOf(slider.getLongValue()); textField.setText(value); slider.setToolTipText(value); } } }); textField.setInputVerifier(new InputVerifier() { public boolean verify(JComponent input) { final JTextField inputField = (JTextField) input; try { hideError(); final String valueStr = inputField.getText().trim(); if (intervalInfo.isDoubleInterval()) { final double value = Double.parseDouble(valueStr); if (intervalInfo.isValidValue(valueStr)) { slider.setValue(value); return true; } else showError( "Please specify a value between " + intervalInfo.getIntervalMin() + " and " + intervalInfo.getIntervalMax() + ".", inputField); return false; } else { final long value = Long.parseLong(valueStr); if (intervalInfo.isValidValue(valueStr)) { slider.setValue(value); return true; } else { showError("Please specify an integer value between " + intervalInfo.getIntervalMin() + " and " + intervalInfo.getIntervalMax() + ".", inputField); return false; } } } catch (final NumberFormatException _) { final String message = "The specified value is not a" + (intervalInfo.isDoubleInterval() ? "" : "n integer") + " number."; showError(message, inputField); return false; } } }); textField.getDocument().addDocumentListener(new DocumentListener() { // private Popup errorPopup; public void removeUpdate(final DocumentEvent _) { textFieldChanged(); } public void insertUpdate(final DocumentEvent _) { textFieldChanged(); } public void changedUpdate(final DocumentEvent _) { textFieldChanged(); } private void textFieldChanged() { if (!textField.hasFocus()) { hideError(); return; } try { hideError(); final String valueStr = textField.getText().trim(); if (intervalInfo.isDoubleInterval()) { final double value = Double.parseDouble(valueStr); if (intervalInfo.isValidValue(valueStr)) slider.setValue(value); else showError("Please specify a value between " + intervalInfo.getIntervalMin() + " and " + intervalInfo.getIntervalMax() + ".", textField); } else { final long value = Long.parseLong(valueStr); if (intervalInfo.isValidValue(valueStr)) slider.setValue(value); else showError("Please specify an integer value between " + intervalInfo.getIntervalMin() + " and " + intervalInfo.getIntervalMax() + ".", textField); } } catch (final NumberFormatException _) { final String message = "The specified value is not a" + (intervalInfo.isDoubleInterval() ? "" : "n integer") + " number."; showError(message, textField); } } }); field.add(textField, BorderLayout.CENTER); field.add(slider, BorderLayout.SOUTH); } else { final Object value = oldField != null ? ((JTextField) oldField).getText() : parameterInfo.getValue(); field = new JTextField(value.toString()); ((JTextField) field).addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { wizard.clickDefaultButton(); } }); } final JLabel parameterLabel = new JLabel(record.fieldName); final String description = parameterInfo.getDescription(); if (description != null && !description.isEmpty()) { parameterLabel.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(final MouseEvent e) { final DescriptionPopupFactory popupFactory = DescriptionPopupFactory.getInstance(); final Popup parameterDescriptionPopup = popupFactory.getPopup(parameterLabel, description, dashboard.getCssStyle()); parameterDescriptionPopup.show(); } }); } if (oldNode != null) userData.setSecond(field); else { final Pair<ParameterInfo, JComponent> pair = new Pair<ParameterInfo, JComponent>(parameterInfo, field); final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(pair); parentNode.add(newNode); } if (field instanceof JCheckBox) { parameterLabel .setText("<html><div style=\"margin-bottom: 4pt; margin-top: 6pt; margin-left: 4pt\">" + parameterLabel.getText() + "</div></html>"); formBuilder.append(parameterLabel, field); // appendCheckBoxFieldToPresentation( // formBuilder, parameterLabel.getText(), (JCheckBox) field); } else { formBuilder.append(parameterLabel, field); final CellConstraints constraints = formBuilder.getLayout().getConstraints(parameterLabel); constraints.vAlign = CellConstraints.TOP; constraints.insets = new Insets(5, 0, 0, 0); formBuilder.getLayout().setConstraints(parameterLabel, constraints); } // prepare the parameterInfo for the param sweeps parameterInfo.setRuns(0); parameterInfo.setDefinitionType(ParameterInfo.CONST_DEF); parameterInfo.setValue(batchParameterInfo.getDefaultValue()); info.add(parameterInfo); } } appendVerticalSpaceToPresentation(formBuilder); final JPanel panel = formBuilder.getPanel(); singleRunParametersPanel.add(panel); if (singleRunParametersPanel.getComponentCount() > 1) { panel.setBorder( BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.GRAY), BorderFactory.createEmptyBorder(0, 5, 0, 5))); } else { panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); } Style.apply(panel, dashboard.getCssStyle()); return info; }
From source file:com.nikonhacker.gui.EmulatorUI.java
private void openUIOptionsDialog() { JPanel options = new JPanel(new GridLayout(0, 1)); options.setName("User Interface"); // Button size ActionListener buttonSizeRadioListener = new ActionListener() { @Override/*from w w w.j av a 2s. com*/ public void actionPerformed(ActionEvent e) { prefs.setButtonSize(e.getActionCommand()); } }; JRadioButton small = new JRadioButton("Small"); small.setActionCommand(BUTTON_SIZE_SMALL); small.addActionListener(buttonSizeRadioListener); if (BUTTON_SIZE_SMALL.equals(prefs.getButtonSize())) small.setSelected(true); JRadioButton medium = new JRadioButton("Medium"); medium.setActionCommand(BUTTON_SIZE_MEDIUM); medium.addActionListener(buttonSizeRadioListener); if (BUTTON_SIZE_MEDIUM.equals(prefs.getButtonSize())) medium.setSelected(true); JRadioButton large = new JRadioButton("Large"); large.setActionCommand(BUTTON_SIZE_LARGE); large.addActionListener(buttonSizeRadioListener); if (BUTTON_SIZE_LARGE.equals(prefs.getButtonSize())) large.setSelected(true); ButtonGroup group = new ButtonGroup(); group.add(small); group.add(medium); group.add(large); // Close windows on stop final JCheckBox closeAllWindowsOnStopCheckBox = new JCheckBox("Close all windows on Stop"); closeAllWindowsOnStopCheckBox.setSelected(prefs.isCloseAllWindowsOnStop()); // Refresh interval JPanel refreshIntervalPanel = new JPanel(); final JTextField refreshIntervalField = new JTextField(5); refreshIntervalPanel.add(new JLabel("Refresh interval for cpu, screen, etc. (ms):")); refreshIntervalField.setText("" + prefs.getRefreshIntervalMs()); refreshIntervalPanel.add(refreshIntervalField); // Setup panel options.add(new JLabel("Button size :")); options.add(small); options.add(medium); options.add(large); options.add(closeAllWindowsOnStopCheckBox); options.add(refreshIntervalPanel); options.add(new JLabel("Larger value greatly increases emulation speed")); if (JOptionPane.OK_OPTION == JOptionPane.showOptionDialog(this, options, "Preferences", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, JOptionPane.DEFAULT_OPTION)) { // save prefs.setButtonSize(group.getSelection().getActionCommand()); prefs.setCloseAllWindowsOnStop(closeAllWindowsOnStopCheckBox.isSelected()); int refreshIntervalMs = 0; try { refreshIntervalMs = Integer.parseInt(refreshIntervalField.getText()); } catch (NumberFormatException e) { // noop } refreshIntervalMs = Math.max(Math.min(refreshIntervalMs, 10000), 10); prefs.setRefreshIntervalMs(refreshIntervalMs); applyPrefsToUI(); } }