List of usage examples for javax.swing JLabel setText
@BeanProperty(preferred = true, visualUpdate = true, description = "Defines the single line of text this component will display.") public void setText(String text)
From source file:in.gov.uidai.auth.sampleapp.SampleClientMainFrame.java
private void displayAuthResults(AuthRes authResult, boolean useProto) { javax.swing.JLabel status = (useProto ? this.jLabelAuthStatusTextProto : this.jLabelAuthStatusTextXML); javax.swing.JLabel statusLabel = (useProto ? this.jLabelAuthStatusProto : this.jLabelAuthStatus); statusLabel.setText(useProto ? "Proto " : "XML"); if (authResult.getRet().equals(AuthResult.Y)) { statusLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/success.png"))); status.setVisible(false);/*from w w w. ja va 2s. c om*/ status.setText(""); } else { statusLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/failure.png"))); status.setText((useProto ? "Proto " : "XML") + " Error code: " + authResult.getErr() + " (" + ErrorCodeDescriptions.getDescription(authResult.getErr()) + ")"); status.setVisible(true); } String origValue = StringUtils.isNotBlank(this.jLabelAuthRefCodeValue.getText()) ? this.jLabelAuthRefCodeValue.getText() + ", " : ""; this.jLabelAuthRefCodeValue.setText(origValue + authResult.getCode()); this.jLabelAuthRefCodeValue.setVisible(true); this.jLabelAuthRefCode.setVisible(true); }
From source file:DownloadDialog.java
/******************************************************************** * Constructor: DownloadDialog/* w ww. j a va 2 s .co m*/ * Purpose: constructor for download, with necessary references /*******************************************************************/ public DownloadDialog(final MainApplication context, Scheduler scheduler_Ref, JList courseListSelected_Ref, JList courseListAll_Ref) { // Basic setup for dialog setModalityType(Dialog.ModalityType.APPLICATION_MODAL); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); setTitle(TITLE); // Setup proper references this.scheduler = scheduler_Ref; this.courseListSelected = courseListSelected_Ref; this.courseListAll = courseListAll_Ref; // Store available terms storeTerms(); // Constraints GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.insets = new Insets(10, 10, 10, 10); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 0; c.gridwidth = 2; // Main panel panel = new JPanel(new GridBagLayout()); // Add term select box termCB = new JComboBox(termsName.toArray()); panel.add(termCB, c); // Setup username and password labels JLabel userL = new JLabel("Username:"); JLabel passL = new JLabel("Password:"); c.gridwidth = 1; c.gridx = 0; c.weightx = 0; // Add user label c.gridy = 1; c.insets = new Insets(5, 10, 0, 10); panel.add(userL, c); // Add password label c.gridy = 2; c.insets = new Insets(0, 10, 5, 10); panel.add(passL, c); // Setup user and pass text fields user = new JTextField(); pass = new JPasswordField(); c.weightx = 1; c.gridx = 1; // Add user field c.gridy = 1; c.insets = new Insets(5, 10, 2, 10); panel.add(user, c); // Add pass field c.gridy = 2; c.insets = new Insets(2, 10, 5, 10); panel.add(pass, c); // Setup login button JButton login = new JButton("Login"); login.addActionListener(this); c.insets = new Insets(10, 10, 10, 10); c.gridx = 0; c.gridy = 3; c.gridwidth = 2; c.weightx = 1; panel.add(login, c); // Add panel to main box add(panel); // Pack the components and give userbox focus pack(); user.requestFocus(); // Create worker to download courses worker = new SwingWorker<Void, Void>() { protected Void doInBackground() throws Exception { // Reset courses scheduler.resetCourses(); // Constraints GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.insets = new Insets(10, 10, 10, 10); c.gridx = 0; c.weightx = 1; c.weighty = 0; // Remove all elements panel.removeAll(); // Add status JLabel status = new JLabel("Connecting..."); c.gridy = 0; panel.add(status, c); // Add progress bar JProgressBar progressBar = new JProgressBar(0, SUBJECTS.length); c.gridy = 1; panel.add(progressBar, c); progressBar.setPreferredSize(new Dimension(275, 12)); // Revalidate, repaint, and pack //revalidate(); repaint(); pack(); try { // Create client DefaultHttpClient client = new DefaultHttpClient(); // Setup and execute initial login HttpGet initialLogin = new HttpGet("http://jweb.kettering.edu/cku1/twbkwbis.P_ValLogin"); HttpResponse response = client.execute(initialLogin); HTMLParser.parse(response); // Get current term String term = termsValue.get(termCB.getSelectedIndex()); // Consume entity (cookies) HttpEntity entity = response.getEntity(); if (entity != null) entity.consumeContent(); // Create post for login HttpPost login = new HttpPost("http://jweb.kettering.edu/cku1/twbkwbis.P_ValLogin"); // Parameters List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("sid", user.getText())); parameters.add(new BasicNameValuePair("PIN", pass.getText())); login.setEntity(new UrlEncodedFormEntity(parameters)); login.setHeader("Referer", "http://jweb.kettering.edu/cku1/twbkwbis.P_ValLogin"); // Login ! response = client.execute(login); // Store proper cookies List<Cookie> cookies = client.getCookieStore().getCookies(); // Start off assuming logging in failed boolean loggedIn = false; // Check cookies for successful login for (int i = 0; i < cookies.size(); i++) if (cookies.get(i).getName().equals("SESSID")) loggedIn = true; // Success? if (loggedIn) { // Consumption of feed HTMLParser.parse(response); // Execute GET class list page HttpGet classList = new HttpGet( "http://jweb.kettering.edu/cku1/bwskfcls.p_sel_crse_search"); classList.setHeader("Referer", "https://jweb.kettering.edu/cku1/twbkwbis.P_GenMenu"); response = client.execute(classList); HTMLParser.parse(response); // Execute GET for course page HttpGet coursePage = new HttpGet( "http://jweb.kettering.edu/cku1/bwckgens.p_proc_term_date?p_calling_proc=P_CrseSearch&p_term=" + term); coursePage.setHeader("Referer", "http://jweb.kettering.edu/cku1/bwskfcls.p_sel_crse_search"); response = client.execute(coursePage); HTMLParser.parse(response); // Download every subject's data for (int index = 0; index < SUBJECTS.length; index++) { // Don't download if cancel was pressed if (isCancelled()) break; // Update status, progress bar, then store course String subject = SUBJECTS[index]; status.setText("Downloading " + subject); progressBar.setValue(index); scheduler.storeDynamicCourse(subject, client, term); } // Update course list data courseListAll.setListData(scheduler.getCourseIDs().toArray()); // Clear course list data String[] empty = {}; courseListSelected.setListData(empty); context.updatePermutations(); context.updateSchedule(); // Dispose of dialog if cancelled if (!isCancelled()) { dispose(); } } // Invalid login? else { // Update status status.setText("Invalid login."); } } // Failed to download? catch (Exception exc) { // Show stack trace, and update status exc.printStackTrace(); status.setText("Failed downloading."); } return null; } }; // Setup window close event to be same as cancel this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // Cancel all downloads then dispose worker.cancel(true); dispose(); } }); // Make sure dialog is visible setLocationRelativeTo(context); setVisible(true); }
From source file:com.mirth.connect.client.ui.Frame.java
/** * Builds the content panel with a title bar and settings. *///from w w w . j av a 2s . com private void buildContentPanel(JXTitledPanel container, JScrollPane component, boolean opaque) { container.getContentContainer().setLayout(new BorderLayout()); container.setBorder(null); container.setTitleFont(new Font("Tahoma", Font.BOLD, 18)); container.setTitleForeground(UIConstants.HEADER_TITLE_TEXT_COLOR); JLabel mirthConnectImage = new JLabel(); mirthConnectImage.setIcon(UIConstants.MIRTHCONNECT_LOGO_GRAY); mirthConnectImage.setText(" "); mirthConnectImage.setToolTipText(UIConstants.MIRTHCONNECT_TOOLTIP); mirthConnectImage.setCursor(new Cursor(Cursor.HAND_CURSOR)); mirthConnectImage.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { BareBonesBrowserLaunch.openURL(UIConstants.MIRTHCONNECT_URL); } }); ((JPanel) container.getComponent(0)).add(mirthConnectImage); component.setBorder(new LineBorder(Color.GRAY, 1)); component.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); component.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); container.getContentContainer().add(component); }
From source file:com.osparking.osparking.Settings_System.java
private void initComPortIDLabel(JLabel comPortIDLabel) { short labelWidth = 115; comPortIDLabel.setFont(new java.awt.Font(font_Type, font_Style, font_Size)); comPortIDLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); comPortIDLabel.setText(COM_PORT_ID_LABEL.getContent()); comPortIDLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP); comPortIDLabel.setMaximumSize(new java.awt.Dimension(labelWidth, 25)); comPortIDLabel.setMinimumSize(new java.awt.Dimension(labelWidth, 25)); comPortIDLabel.setPreferredSize(new java.awt.Dimension(labelWidth, 25)); comPortIDLabel.setFont(new java.awt.Font(font_Type, font_Style, font_Size)); }
From source file:edu.ku.brc.specify.plugins.ipadexporter.ManageDataSetsDlg.java
/** * //from ww w . jav a2s . c om */ private void addUserToDS() { final Vector<String> wsList = new Vector<String>(); final Vector<String> instItems = new Vector<String>(); String addStr = getResourceString("ADD"); instItems.add(addStr); wsList.add(addStr); for (String fullName : cloudHelper.getInstList()) { String[] toks = StringUtils.split(fullName, '\t'); instItems.add(toks[0]); wsList.add(toks[1]); } final JTextField userNameTF = createTextField(20); final JTextField passwordTF = createTextField(20); final JLabel pwdLbl = createI18NFormLabel("Password"); final JLabel statusLbl = createLabel(""); final JCheckBox isNewUser = UIHelper.createCheckBox("Is New User"); final JLabel instLbl = createI18NFormLabel("Insitution"); final JComboBox instCmbx = UIHelper.createComboBox(instItems.toArray()); if (instItems.size() == 2) { instCmbx.setSelectedIndex(1); } CellConstraints cc = new CellConstraints(); PanelBuilder pb = new PanelBuilder(new FormLayout("p,2px,f:p:g", "p,4px,p,4px,p,4px,p,4px,p,8px,p")); pb.add(createI18NLabel("Add New or Existing User to DataSet"), cc.xyw(1, 1, 3)); pb.add(createI18NFormLabel("Username"), cc.xy(1, 3)); pb.add(userNameTF, cc.xy(3, 3)); pb.add(pwdLbl, cc.xy(1, 5)); pb.add(passwordTF, cc.xy(3, 5)); pb.add(instLbl, cc.xy(1, 7)); pb.add(instCmbx, cc.xy(3, 7)); pb.add(isNewUser, cc.xy(3, 9)); pb.add(statusLbl, cc.xyw(1, 11, 3)); pb.setDefaultDialogBorder(); pwdLbl.setVisible(false); passwordTF.setVisible(false); instLbl.setVisible(false); instCmbx.setVisible(false); final CustomDialog dlg = new CustomDialog(this, "Add User", true, OKCANCEL, pb.getPanel()) { @Override protected void okButtonPressed() { String usrName = userNameTF.getText(); if (cloudHelper.isUserNameOK(usrName)) { String collGuid = datasetGUIDList.get(dataSetList.getSelectedIndex()); if (cloudHelper.addUserAccessToDataSet(usrName, collGuid)) { super.okButtonPressed(); } else { iPadDBExporterPlugin.setErrorMsg(statusLbl, String.format("Unable to add usr: %s to the DataSet guid: %s", usrName, collGuid)); } } else if (isNewUser.isSelected()) { String pwdStr = passwordTF.getText(); String guid = null; if (instCmbx.getSelectedIndex() == 0) { // InstDlg instDlg = new InstDlg(cloudHelper); // if (!instDlg.isInstOK()) // { // instDlg.createUI(); // instDlg.pack(); // centerAndShow(instDlg, 600, null); // if (instDlg.isCancelled()) // { // return; // } // //guid = instDlg.getGuid()(); // } } else { //webSite = wsList.get(instCmbx.getSelectedIndex()); } if (guid != null) { String collGuid = datasetGUIDList.get(dataSetList.getSelectedIndex()); if (cloudHelper.addNewUser(usrName, pwdStr, guid)) { if (cloudHelper.addUserAccessToDataSet(usrName, collGuid)) { ManageDataSetsDlg.this.loadUsersForDataSetsIntoJList(); super.okButtonPressed(); } else { iPadDBExporterPlugin.setErrorMsg(statusLbl, String.format("Unable to add%s to the DataSet %s", usrName, collGuid)); } } else { iPadDBExporterPlugin.setErrorMsg(statusLbl, String.format("Unable to add%s to the DataSet %s", usrName, collGuid)); } } else { // error } } else { iPadDBExporterPlugin.setErrorMsg(statusLbl, String.format("'%s' doesn't exist.", usrName)); } } }; KeyAdapter ka = new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { statusLbl.setText(""); String usrNmStr = userNameTF.getText(); boolean hasData = StringUtils.isNotEmpty(usrNmStr) && (!isNewUser.isSelected() || StringUtils.isNotEmpty(passwordTF.getText())) && UIHelper.isValidEmailAddress(usrNmStr); dlg.getOkBtn().setEnabled(hasData); } }; userNameTF.addKeyListener(ka); passwordTF.addKeyListener(ka); final Color textColor = userNameTF.getForeground(); FocusAdapter fa = new FocusAdapter() { @Override public void focusGained(FocusEvent e) { JTextField tf = (JTextField) e.getSource(); if (!tf.getForeground().equals(textColor)) { tf.setText(""); tf.setForeground(textColor); } } @Override public void focusLost(FocusEvent e) { JTextField tf = (JTextField) e.getSource(); if (tf.getText().length() == 0) { tf.setText("Enter email address"); tf.setForeground(Color.LIGHT_GRAY); } } }; userNameTF.addFocusListener(fa); userNameTF.setText("Enter email address"); userNameTF.setForeground(Color.LIGHT_GRAY); isNewUser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean isSel = isNewUser.isSelected(); pwdLbl.setVisible(isSel); passwordTF.setVisible(isSel); instLbl.setVisible(isSel); instCmbx.setVisible(isSel); Dimension s = dlg.getSize(); int hgt = isNewUser.getSize().height + 4 + instCmbx.getSize().height; s.height += isSel ? hgt : -hgt; dlg.setSize(s); } }); dlg.createUI(); dlg.getOkBtn().setEnabled(false); centerAndShow(dlg); if (!dlg.isCancelled()) { loadUsersForDataSetsIntoJList(); } }
From source file:com.smanempat.controller.ControllerEvaluation.java
private double[][] evaluationModel(JTable tableResult, JTable tableConfMatrix, JLabel totalAccuracy, JTable tableTahunTesting, JTable tableDataSetTesting, String[] knnValue, int i, int[] tempK, JPanel panelChart) throws SQLException { int actIPA = 0; int actIPS = 0; int trueIPA = 0; int falseIPA = 0; int trueIPS = 0; int falseIPS = 0; double recIPA; double recIPS; double preIPA; double preIPS; double accuracy; DefaultTableModel tableModelRes = new DefaultTableModel(); tableModelRes = (DefaultTableModel) tableResult.getModel(); String[] tempJurusan = getJurusanTest(tableTahunTesting, tableDataSetTesting); for (int j = 0; j < tableDataSetTesting.getRowCount(); j++) { String nis = tableDataSetTesting.getValueAt(j, 0).toString(); String jurusan = tempJurusan[j]; String classified = knnValue[j]; Object[] tableContent = { nis, jurusan, classified }; tableModelRes.addRow(tableContent); tableResult.setModel(tableModelRes); }//from w w w .j a v a2 s . com /*Hitung Jumlah Data Actual IPA dan IPS*/ for (int j = 0; j < tempJurusan.length; j++) { if (tempJurusan[j].equals("IPA")) { actIPA = actIPA + 1; } else if (tempJurusan[j].equals("IPS")) { actIPS = actIPS + 1; } } /*Hitung Jumlah Data Classified IPA dan IPS*/ for (int j = 0; j < knnValue.length; j++) { if (tableResult.getValueAt(j, 1).equals("IPA")) { if (tableResult.getValueAt(j, 1).equals(tableResult.getValueAt(j, 2))) { trueIPA = trueIPA + 1; } else { falseIPS = falseIPS + 1; } } else if (tableResult.getValueAt(j, 1).equals("IPS")) { if (tableResult.getValueAt(j, 1).equals(tableResult.getValueAt(j, 2))) { trueIPS = trueIPS + 1; } else { falseIPA = falseIPA + 1; } } } /*Hitung Nilai Recall, Precision, dan Accuracy*/ preIPA = (double) trueIPA / (trueIPA + falseIPA); preIPS = (double) trueIPS / (trueIPS + falseIPS); recIPA = (double) trueIPA / (trueIPA + falseIPS); recIPS = (double) trueIPS / (trueIPS + falseIPA); accuracy = (double) (trueIPA + trueIPS) / (trueIPA + trueIPS + falseIPA + falseIPS); /*Tampung Nilai Recall, Precision, dan Accuracy*/ double[][] tempEval = new double[3][tempK.length]; tempEval[0][i] = accuracy; tempEval[1][i] = recIPA; tempEval[2][i] = preIPA; /*Set Nilai TF, TN, FP, FN ke Tabel Confusion Matrix*/ tableConfMatrix.setValueAt("Actual IPA", 0, 0); tableConfMatrix.setValueAt("Actual IPS", 1, 0); tableConfMatrix.setValueAt("Class Precision", 2, 0); tableConfMatrix.setValueAt(trueIPA, 0, 1); tableConfMatrix.setValueAt(falseIPS, 0, 2); tableConfMatrix.setValueAt(falseIPA, 1, 1); tableConfMatrix.setValueAt(trueIPS, 1, 2); /*Set Nilai Recall, Precision, dan Accuracy ke Tabel Confusion Matrix*/ if (Double.isNaN(preIPA)) { tableConfMatrix.setValueAt("NaN" + " %", 2, 1); } else { tableConfMatrix.setValueAt(df.format(preIPA * 100) + " %", 2, 1); } if (Double.isNaN(preIPS)) { tableConfMatrix.setValueAt("NaN" + " %", 2, 2); } else { tableConfMatrix.setValueAt(df.format(preIPS * 100) + " %", 2, 2); } if (Double.isNaN(recIPA)) { tableConfMatrix.setValueAt("NaN" + " %", 0, 3); } else { tableConfMatrix.setValueAt(df.format(recIPA * 100) + " %", 0, 3); } if (Double.isNaN(recIPS)) { tableConfMatrix.setValueAt("NaN" + " %", 1, 3); } else { tableConfMatrix.setValueAt(df.format(recIPS * 100) + " %", 1, 3); } if (Double.isNaN(accuracy)) { totalAccuracy.setText("Overall Accuracy is " + "NaN" + " %"); } else { totalAccuracy.setText("Overall Accuracy is " + df.format(accuracy * 100) + " %"); } tableModelRes.setRowCount(0); return tempEval; }
From source file:edu.ku.brc.specify.tasks.subpane.qb.QueryBldrPane.java
/** * @param parentList/*ww w.j av a 2 s .c om*/ */ protected void fillNextList(final JList parentList) { if (processingLists) { return; } processingLists = true; final int curInx = listBoxList.indexOf(parentList); if (curInx > -1) { int startSize = listBoxPanel.getComponentCount(); for (int i = curInx + 1; i < listBoxList.size(); i++) { listBoxPanel.remove(spList.get(i)); } int removed = startSize - listBoxPanel.getComponentCount(); for (int i = 0; i < removed; i++) { tableTreeList.remove(tableTreeList.size() - 1); } } else { listBoxPanel.removeAll(); tableTreeList.clear(); } QryListRendererIFace item = (QryListRendererIFace) parentList.getSelectedValue(); if (item instanceof ExpandableQRI) { JList newList; DefaultListModel model; JScrollPane sp; if (curInx == listBoxList.size() - 1) { newList = new JList(model = new DefaultListModel()); newList.addMouseListener(new MouseAdapter() { /* (non-Javadoc) * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent) */ @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { if (currentInx != -1) { JList list = (JList) e.getSource(); QryListRendererIFace qriFace = (QryListRendererIFace) list.getSelectedValue(); if (BaseQRI.class.isAssignableFrom(qriFace.getClass())) { BaseQRI qri = (BaseQRI) qriFace; if (qri.isInUse()) { //remove the field for (QueryFieldPanel qfp : QueryBldrPane.this.queryFieldItems) { FieldQRI fqri = qfp.getFieldQRI(); if (fqri == qri || (fqri instanceof RelQRI && fqri.getTable() == qri)) { boolean clearIt = qfp.getSchemaItem() != null; QueryBldrPane.this.removeQueryFieldItem(qfp); if (clearIt) { qfp.setField(null, null); } break; } } } else { // add the field try { FieldQRI fieldQRI = buildFieldQRI(qri); if (fieldQRI == null) { throw new Exception("null FieldQRI"); } SpQueryField qf = new SpQueryField(); qf.initialize(); qf.setFieldName(fieldQRI.getFieldName()); qf.setStringId(fieldQRI.getStringId()); query.addReference(qf, "fields"); if (!isExportMapping) { addQueryFieldItem(fieldQRI, qf, false); } else { addNewMapping(fieldQRI, qf, null, false); } } catch (Exception ex) { log.error(ex); UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance() .capture(QueryBldrPane.class, ex); return; } } } } } } }); newList.setCellRenderer(qryRenderer); listBoxList.add(newList); sp = new JScrollPane(newList, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); JLabel colHeader = UIHelper.createLabel(item.getTitle()); colHeader.setHorizontalAlignment(SwingConstants.CENTER); colHeader.setBackground(listBoxPanel.getBackground()); colHeader.setOpaque(true); sp.setColumnHeaderView(colHeader); spList.add(sp); newList.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { fillNextList(listBoxList.get(curInx + 1)); } } }); } else { newList = listBoxList.get(curInx + 1); model = (DefaultListModel) newList.getModel(); sp = spList.get(curInx + 1); JLabel colHeaderLbl = (JLabel) sp.getColumnHeader().getComponent(0); if (item instanceof TableQRI) { colHeaderLbl.setText(((TableQRI) item).getTitle()); } else { colHeaderLbl.setText(getResourceString("QueryBldrPane.QueryFields")); } } createNewList((TableQRI) item, model); listBoxPanel.remove(addBtn); listBoxPanel.add(sp); tableTreeList.add(((ExpandableQRI) item).getTableTree()); listBoxPanel.add(addBtn); currentInx = -1; } else { listBoxPanel.add(addBtn); } SwingUtilities.invokeLater(new Runnable() { public void run() { updateAddBtnState(); // Is all this really necessary listBoxPanel.validate(); listBoxPanel.repaint(); scrollPane.validate(); scrollPane.invalidate(); scrollPane.doLayout(); scrollPane.repaint(); validate(); invalidate(); doLayout(); repaint(); UIRegistry.forceTopFrameRepaint(); } }); processingLists = false; currentInx = curInx; }
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); }// w w w . j a va 2 s.c o m 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.smanempat.controller.ControllerEvaluation.java
private double[][] evaluationModel(JTable tableResult, JTable tableConfMatrix, JLabel totalAccuracy, JTable tableTahunTesting, JTable tableDataSetTesting, String[] knnValue, int nilaiK, JPanel panelChart) throws SQLException { int actIPA = 0; int actIPS = 0; int trueIPA = 0; int falseIPA = 0; int trueIPS = 0; int falseIPS = 0; int classIPA = 0; int classIPS = 0; double recIPA; double recIPS; double preIPA; double preIPS; double accuracy; DefaultTableModel tableModelConf = (DefaultTableModel) tableConfMatrix.getModel(); DefaultTableModel tableModelRes = (DefaultTableModel) tableResult.getModel(); String[] tempJurusan = getJurusanTest(tableTahunTesting, tableDataSetTesting); if (tableModelRes.getRowCount() != 0) { tableModelRes.setRowCount(0);//from www.ja v a 2 s . c o m } for (int j = 0; j < tableDataSetTesting.getRowCount(); j++) { String nis = tableDataSetTesting.getValueAt(j, 0).toString(); String jurusan = tempJurusan[j]; String classified = knnValue[j]; Object[] tableContent = { nis, jurusan, classified }; tableModelRes.addRow(tableContent); tableResult.setModel(tableModelRes); } /*Hitung Jumlah Data Actual IPA dan IPS*/ for (int j = 0; j < tempJurusan.length; j++) { if (tempJurusan[j].equals("IPA")) { actIPA = actIPA + 1; } else if (tempJurusan[j].equals("IPS")) { actIPS = actIPS + 1; } } /*Hitung Jumlah Data Classified IPA dan IPS*/ for (int j = 0; j < knnValue.length; j++) { if (tableResult.getValueAt(j, 1).equals("IPA")) { if (tableResult.getValueAt(j, 1).equals(tableResult.getValueAt(j, 2))) { trueIPA = trueIPA + 1; } else { falseIPS = falseIPS + 1; } } else if (tableResult.getValueAt(j, 1).equals("IPS")) { if (tableResult.getValueAt(j, 1).equals(tableResult.getValueAt(j, 2))) { trueIPS = trueIPS + 1; } else { falseIPA = falseIPA + 1; } } } // System.out.println("trueIPA =" + trueIPA); // System.out.println("falseIPA =" + falseIPA); // System.out.println("falseIPS =" + falseIPS); // System.out.println("trueIPS =" + trueIPS); /*Hitung Nilai Recall, Precision, dan Accuracy*/ preIPA = (double) trueIPA / (trueIPA + falseIPA); preIPS = (double) trueIPS / (trueIPS + falseIPS); recIPA = (double) trueIPA / (trueIPA + falseIPS); recIPS = (double) trueIPS / (trueIPS + falseIPA); accuracy = (double) (trueIPA + trueIPS) / (trueIPA + trueIPS + falseIPA + falseIPS); /*Tampung Nilai Recall, Precision, dan Accuracy*/ double[][] tempEval = new double[3][1]; tempEval[0][0] = accuracy; tempEval[1][0] = recIPA; tempEval[2][0] = preIPA; /*Set Nilai TF, TN, FP, FN ke Tabel Confusion Matrix*/ tableModelConf.setValueAt("Actual IPA", 0, 0); tableModelConf.setValueAt("Actual IPS", 1, 0); tableModelConf.setValueAt("Class Precision", 2, 0); tableModelConf.setValueAt(trueIPA, 0, 1); tableModelConf.setValueAt(falseIPS, 0, 2); tableModelConf.setValueAt(falseIPA, 1, 1); tableModelConf.setValueAt(trueIPS, 1, 2); /*Set Nilai Recall, Precision, dan Accuracy ke Tabel Confusion Matrix*/ if (Double.isNaN(preIPA)) { tableModelConf.setValueAt("NaN" + " %", 2, 1); } else { tableModelConf.setValueAt(df.format(preIPA * 100) + " %", 2, 1); } if (Double.isNaN(preIPS)) { tableModelConf.setValueAt("NaN" + " %", 2, 2); } else { tableModelConf.setValueAt(df.format(preIPS * 100) + " %", 2, 2); } if (Double.isNaN(recIPA)) { tableModelConf.setValueAt("NaN" + " %", 0, 3); } else { tableModelConf.setValueAt(df.format(recIPA * 100) + " %", 0, 3); } if (Double.isNaN(recIPS)) { tableModelConf.setValueAt("NaN" + " %", 1, 3); } else { tableModelConf.setValueAt(df.format(recIPS * 100) + " %", 1, 3); } if (Double.isNaN(accuracy)) { totalAccuracy.setText("Overall Accuracy is " + "NaN" + " %"); } else { totalAccuracy.setText("Overall Accuracy is " + df.format(accuracy * 100) + " %"); } // System.out.println("Recall IPA = " + recIPA); // System.out.println("Recall IPA =" + recIPS); // System.out.println("Precision IPA = " + preIPA); // System.out.println("Precision IPS = " + preIPS); // System.out.println("Overall Accuracy = " + accuracy); return tempEval; }
From source file:lcmc.gui.resources.ServiceInfo.java
/** Revert locations to saved values. */ protected final void revertLocations() { for (Host host : getBrowser().getClusterHosts()) { final HostInfo hi = host.getBrowser().getHostInfo(); final HostLocation savedLocation = savedHostLocations.get(hi); final Widget wi = scoreComboBoxHash.get(hi); if (wi == null) { continue; }/*from w ww . java 2s.co m*/ String score = null; String op = null; if (savedLocation != null) { score = savedLocation.getScore(); op = savedLocation.getOperation(); } wi.setValue(score); final JLabel label = wi.getLabel(); final String text = getHostLocationLabel(hi.getName(), op); label.setText(text); } /* pingd */ final Widget pwi = pingComboBox; if (pwi != null) { final String spo = savedPingOperation; if (spo == null) { pwi.setValue(Widget.NOTHING_SELECTED); } else { pwi.setValue(PING_ATTRIBUTES.get(spo)); } } }