/** * Handle a refresh of the style panel after the fig has moved. * * <p><em>Warning</em>. There is a circular trap here. Editing the boundary box will also trigger * a refresh, and so we reset the boundary box, which causes funny behaviour (the cursor keeps * jumping to the end of the text). * * <p>The solution is to not reset the boundary box field if the boundaries have not changed. * * <p> */ public void refresh() { Fig target = getPanelTarget(); if (target instanceof FigEdgeModelElement) { hasEditableBoundingBox(false); } else { hasEditableBoundingBox(true); } if (target == null) return; // The boundary box as held in the target fig, and as listed in // the // boundary box style field (null if we don't have anything // valid) Rectangle figBounds = target.getBounds(); Rectangle styleBounds = parseBBox(); // Only reset the text if the two are not the same (i.e the fig // has // moved, rather than we've just edited the text, when // setTargetBBox() // will have made them the same). Note that styleBounds could // be null, // so we do the test this way round. if (!(figBounds.equals(styleBounds))) { bboxField.setText( figBounds.x + "," + figBounds.y + "," + figBounds.width + "," + figBounds.height); } // Change the fill colour if (target.getFilled()) { Color c = target.getFillColor(); fillField.setSelectedItem(c); if (c != null && !fillField.getSelectedItem().equals(c)) { fillField.insertItemAt(c, fillField.getItemCount() - 1); fillField.setSelectedItem(c); } } else { fillField.setSelectedIndex(0); } // Change the line colour if (target.getLineWidth() > 0) { Color c = target.getLineColor(); lineField.setSelectedItem(c); if (c != null && !lineField.getSelectedItem().equals(c)) { lineField.insertItemAt(c, lineField.getItemCount() - 1); lineField.setSelectedItem(c); } } else { lineField.setSelectedIndex(0); } }
/** Mthis method perform equals based on string rapresentation of objects */ public static void updateStringComboBox( javax.swing.JComboBox comboBox, Vector newItems, boolean addNullEntry) { Object itemSelected = null; if (comboBox.getSelectedIndex() >= 0) { itemSelected = comboBox.getSelectedItem() + ""; } comboBox.removeAllItems(); boolean selected = false; boolean foundNullItem = false; Enumeration e = newItems.elements(); while (e.hasMoreElements()) { String item = "" + e.nextElement(); comboBox.addItem(item); if (item.equals(itemSelected)) { selected = true; comboBox.setSelectedItem(itemSelected); } if (item.equals("")) { foundNullItem = true; } } if (addNullEntry) { if (!foundNullItem) comboBox.insertItemAt("", 0); if (!selected) comboBox.setSelectedItem(""); } }
public SwingThreadFrame() { setTitle("SwingThreadTest"); final JComboBox combo = new JComboBox(); combo.insertItemAt(new Integer(Integer.MAX_VALUE), 0); combo.setPrototypeDisplayValue(combo.getItemAt(0)); combo.setSelectedIndex(0); JPanel panel = new JPanel(); JButton goodButton = new JButton("Good"); goodButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { new Thread(new GoodWorkerRunnable(combo)).start(); } }); panel.add(goodButton); JButton badButton = new JButton("Bad"); badButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { new Thread(new BadWorkerRunnable(combo)).start(); } }); panel.add(badButton); panel.add(combo); add(panel); pack(); }
private void handleEntryAction(ActionEvent actionEvent) throws IOException, ParserConfigurationException, XPathExpressionException, SAXException, NoItemException { if (this.getGazetteer() == null) { Util.getLogger().severe("No gazeteer is registered"); return; } String lookupString; JComboBox cmb = ((JComboBox) actionEvent.getSource()); lookupString = cmb.getSelectedItem().toString(); if (lookupString == null || lookupString.length() < 1) return; java.util.List<PointOfInterest> results = this.gazetteer.findPlaces(lookupString); if (results == null || results.size() == 0) return; this.controller.moveToLocation(results.get(0)); // Add it to the list if not already there for (int i = 0; i < cmb.getItemCount(); i++) { Object oi = cmb.getItemAt(i); if (oi != null && oi.toString().trim().equals(lookupString)) return; // item exists } cmb.insertItemAt(lookupString, 0); }
// implemented for ActionListener event handling public void actionPerformed(ActionEvent e) { String actionCmd = e.getActionCommand(); Stack locStack = parentBrowserFrame.locationStack; Stack fwdStack = parentBrowserFrame.forwardStack; if (actionCmd.equals(homeCmd)) // event from home button { fwdStack.removeAllElements(); parentBrowserFrame.setBrowserLocation(mainBrowserURL); } else if (actionCmd.equals(backCmd)) // event from back button { if (!locStack.isEmpty()) { String myLocale = (String) (locStack.pop()); // push current location on forward stack fwdStack.push(location); getForwardButton().setEnabled(true); // do *not* cache the last location in the stack parentBrowserFrame.setBrowserLocation(myLocale, false); } } else if (actionCmd.equals(forwardCmd)) // event from forward button { if (!fwdStack.isEmpty()) { // remove location from forward stack String newLoc = (String) (fwdStack.pop()); // DO add the current location to the back stack parentBrowserFrame.setBrowserLocation(newLoc); } } else if (actionCmd.equals(comboCmd)) // event from URL combo box! { if (e.getSource() instanceof JComboBox) // just to be sure { JComboBox thisBox = (JComboBox) e.getSource(); String newLoc = thisBox.getSelectedItem().toString(); if (newLoc != null && !newLoc.equals("")) // ignore empty selections { if (thisBox.getSelectedIndex() == -1) { thisBox.insertItemAt(newLoc, 0); } fwdStack.removeAllElements(); parentBrowserFrame.setBrowserLocation(newLoc); } } } // disable the back button if we find the location stack is empty if (locStack.isEmpty()) { getBackButton().setEnabled(false); } // disable forward button if forward stack is empty if (fwdStack.isEmpty()) { getForwardButton().setEnabled(false); } }
public void setNativeFPS(int nfps) { nativeFPS = nfps; if (nfps == 60) nativeFPSCombo.setSelectedIndex(0); else if (nfps == 120) nativeFPSCombo.setSelectedIndex(1); else { nativeFPSCombo.insertItemAt(String.valueOf(nativeFPS), 2); nativeFPSCombo.setSelectedIndex(2); } }
/** * Prompts the user for a new custom color and adds that color to the combo box. * * @param field the combobox to enter a new color for * @param title the title for the dialog box * @param targetColor the initial Color set when the color-chooser is shown */ protected void handleCustomColor(JComboBox field, String title, Color targetColor) { Color newColor = JColorChooser.showDialog(ArgoFrame.getInstance(), title, targetColor); if (newColor != null) { field.insertItemAt(newColor, field.getItemCount() - 1); field.setSelectedItem(newColor); } else if (getPanelTarget() != null) { field.setSelectedItem(targetColor); } }
public void AtualizaComboData() { try { lstServicoData = mbServico.ServicoPorData(util.getCMBData(cmbDataInicio), util.getCMBData(cmbDataFinal)); if (lstServicoData != null) { List<Veiculo> lstVeiculo = new ArrayList<>(); cmbPlaca.removeAllItems(); for (int i = 0; i < lstServicoData.size(); i++) { if (!lstVeiculo.contains(lstServicoData.get(i).getVeiculo())) { lstVeiculo.add(lstServicoData.get(i).getVeiculo()); cmbPlaca.addItem(lstServicoData.get(i).getVeiculo().getPlaca()); } } cmbPlaca.insertItemAt("TODOS", 0); cmbPlaca.setSelectedIndex(0); List<Veiculo> listaVeiculo = mbVeiculo.VeiculoPorServico(lstServicoData); List<Unidade> listaUnidade = mbUnidade.UnidadesPorVeiculos(listaVeiculo); List<Modelo> listaModelo = mbModelo.ModeloPorVeiculo(listaVeiculo); List<Marca> listaMarca = mbMarca.MarcaModelo(listaModelo); List<Motorista> listaMotorista = mbMotorista.MotoristaServico(lstServicoData); List<TipoServico> listaTipoServico = mbTipoServico.TipoServicoPorServico(lstServicoData); List<Fornecedor> listaFornecedor = mbFornecedor.FornecedorServico(lstServicoData); // cmbUnidade.removeAllItems(); // AtualizaCombo(cmbUnidade, listaUnidade); cmbTipoServico.removeAllItems(); AtualizaCombo(cmbTipoServico, listaTipoServico); cmbFornecedor.removeAllItems(); AtualizaCombo(cmbFornecedor, listaFornecedor); cmbMarca.removeAllItems(); AtualizaCombo(cmbMarca, listaMarca); cmbModelo.removeAllItems(); AtualizaCombo(cmbModelo, listaModelo); cmbMotorista.removeAllItems(); AtualizaCombo(cmbMotorista, listaMotorista); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private void guiInit() { DefaultListModel listOfStuff = new DefaultListModel(); partsList.setModel(listOfStuff); listOfStuff.addElement(new ElementOrNullWrapper(null, "Build Model from skeleton file")); Sandbox[] possibilities = (Sandbox[]) AuthoringTool.getInstance().getWorld().sandboxes.getArrayValue(); for (int i = 0; i < possibilities.length; i++) { listOfStuff.addElement(new ElementOrNullWrapper(possibilities[i])); } partsList.setSelectedIndex(0); aliceFPSCombo.insertItemAt("15", 0); aliceFPSCombo.insertItemAt("30", 1); aliceFPSCombo.setSelectedIndex(1); nativeFPSCombo.insertItemAt("60", 0); nativeFPSCombo.insertItemAt("120", 1); nativeFPSCombo.setSelectedIndex(0); }
public void loadCombo2() { try { Connection con = DbConn.dbConnection(); Statement stmt = con.createStatement(); List plist = new ArrayList(); ResultSet rs = stmt.executeQuery("select distinct(brand_name) from brand order by brand_name"); while (rs.next()) { plist.add(rs.getString("brand_name")); } brandCompany.setModel(new DefaultComboBoxModel(plist.toArray())); brandCompany.insertItemAt("Select Brand", 0); brandCompany.setSelectedIndex(0); } catch (Exception e) { e.printStackTrace(); } }
protected void addMyControls() { // add browser-style control buttons JButton home = new JButton(new ImageIcon("data/Home24.gif")); JButton back = new JButton(new ImageIcon("data/Back24.gif")); JButton fwd = new JButton(new ImageIcon("data/Forward24.gif")); home.setToolTipText("Home"); home.addActionListener(this); home.setActionCommand(homeCmd); back.setToolTipText("Back"); back.addActionListener(this); back.setActionCommand(backCmd); back.setEnabled(false); // initially disabled fwd.setToolTipText("Forward"); fwd.addActionListener(this); fwd.setActionCommand(forwardCmd); fwd.setEnabled(false); // initially disabled add(home); add(back); add(fwd); add(new JToolBar.Separator()); // set built-in index variables homeIndex = getComponentIndex(home); backIndex = getComponentIndex(back); forwardIndex = getComponentIndex(fwd); JComboBox comboBox = new JComboBox(); comboBox.setEditable(true); comboBox.addActionListener(this); comboBox.setActionCommand(comboCmd); comboBox.setMaximumRowCount(3); // don't let it get too long comboBox.insertItemAt(mainBrowserURL, 0); // don't start it out empty add(comboBox); comboBoxIndex = getComponentIndex(comboBox); }
/** Do the search. */ private void doSearch() { numFinds++; String eName = ""; if (elementName.getSelectedItem() != null) { eName += elementName.getSelectedItem(); elementName.removeItem(eName); elementName.insertItemAt(eName, 0); elementName.setSelectedItem(eName); } String dName = ""; if (diagramName.getSelectedItem() != null) { dName += diagramName.getSelectedItem(); diagramName.removeItem(dName); diagramName.insertItemAt(dName, 0); diagramName.setSelectedItem(dName); } String name = eName; if (dName.length() > 0) { Object[] msgArgs = {name, dName}; name = Translator.messageFormat("dialog.find.comboboxitem.element-in-diagram", msgArgs); // name += " in " + dName; } String typeName = type.getSelectedItem().toString(); if (!typeName.equals("Any Type")) { name += " " + typeName; } if (name.length() == 0) { name = Translator.localize("dialog.find.tabname") + (nextResultNum++); } if (name.length() > 15) { // TODO: Localize name = name.substring(0, 12) + "..."; } String pName = ""; Predicate eNamePred = PredicateStringMatch.create(eName); Predicate pNamePred = PredicateStringMatch.create(pName); Predicate dNamePred = PredicateStringMatch.create(dName); Predicate typePred = (Predicate) type.getSelectedItem(); PredicateSearch pred = new PredicateSearch(eNamePred, pNamePred, dNamePred, typePred); ChildGenSearch gen = new ChildGenSearch(); Object root = ProjectManager.getManager().getCurrentProject(); TabResults newResults = new TabResults(); newResults.setTitle(name); newResults.setPredicate(pred); newResults.setRoot(root); newResults.setGenerator(gen); resultTabs.add(newResults); results.addTab(name, newResults); clearTabs.setEnabled(true); getOkButton().setEnabled(true); results.setSelectedComponent(newResults); Object[] msgArgs = {name}; location.addItem(Translator.messageFormat("dialog.find.comboboxitem.in-tab", msgArgs)); invalidate(); results.invalidate(); validate(); newResults.run(); newResults.requestFocus(); newResults.selectResult(0); }
private void initComponents() { caseListPane = new JPanel(); parameterPane = new JPanel(); helpPane = new JPanel(); helpLabel = new JLabel(); helpLabel.setText( "Dev key come from testlink---->Peronal---->API interface" + "Personal API access key = 2981988c9170b07fba98c6d8f0cba93x"); helpPane.add(helpLabel); GridBagLayout gb = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.EAST; // 该GridBagConstraints控制的GUI组件左对齐 gbc.anchor = GridBagConstraints.WEST; // 该GridBagConstraints控制的GUI组件纵向、横向扩大的权重是1 gbc.weighty = 1; gbc.weightx = 1; parameterPane.setLayout(gb); buildPane = new JPanel(); buildLabel = new JLabel(); buildField = new JTextField(20); gbc.gridwidth = 1; gbc.gridheight = 2; gbc.gridx = 0; gbc.gridy = 5; gb.setConstraints(buildPane, gbc); devPane = new JPanel(); devLabel = new JLabel(); devField = new JTextField(20); gbc.gridx = 0; gbc.gridy = 10; gb.setConstraints(devPane, gbc); testplanPane = new JPanel(); testplanLabel = new JLabel(); testplanNameField = new JTextField(20); gbc.gridx = 0; gbc.gridy = 0; gb.setConstraints(testplanPane, gbc); projectPane = new JPanel(); projectLabel = new JLabel(); projectField = new JTextField(20); gbc.gridx = 0; gbc.gridy = 15; gb.setConstraints(projectPane, gbc); executionTypePane = new JPanel(); executionTypeLabel = new JLabel(); executionTypeComboBox = new JComboBox<String>(); gbc.gridx = 0; gbc.gridy = 20; gb.setConstraints(executionTypePane, gbc); executionStatusPane = new JPanel(); executionStatusLabel = new JLabel(); executionStatusComboBox = new JComboBox<String>(); gbc.gridx = 0; gbc.gridy = 25; gb.setConstraints(executionStatusPane, gbc); startPane = new JPanel(); descriptionLable = new JLabel(); startButton = new JButton(); gbc.gridx = 0; gbc.gridy = 30; gb.setConstraints(startPane, gbc); jScrollPane = new JScrollPane(); jTextArea = new JTextArea(); helpPane.setBorder(BorderFactory.createTitledBorder("Help Information")); parameterPane.setBorder(BorderFactory.createTitledBorder("Parameter settings")); caseListPane.setBorder(BorderFactory.createTitledBorder(" Testcase List")); buildField.setText("53284"); buildLabel.setText("Build Number "); buildLabel.setBorder(BorderFactory.createRaisedBevelBorder()); devField.setText(ConstantPool.devKey); devLabel.setText("Dev key (Help) "); devLabel.setBorder(BorderFactory.createRaisedBevelBorder()); testplanNameField.setText("4.1.1.12 Test Plan"); testplanLabel.setText("Testplan Name "); testplanLabel.setBorder(BorderFactory.createRaisedBevelBorder()); executionTypeLabel.setText("Execution Type "); executionStatusLabel.setText("Execution Status"); projectField.setText("Instant"); projectField.setEditable(false); projectLabel.setBorder(BorderFactory.createRaisedBevelBorder()); projectLabel.setText("Project Name "); descriptionLable.setText("Testplan Execution Status:"); startButton.setText("Start"); startButton.setBorder(BorderFactory.createRaisedBevelBorder()); startButton.setPreferredSize(new Dimension(100, 20)); executionTypeComboBox.insertItemAt("Manual", 0); executionTypeComboBox.insertItemAt("Automated", 1); executionTypeComboBox.insertItemAt("All", 2); executionTypeComboBox.setSelectedIndex(2); executionTypeComboBox.setPreferredSize(new Dimension(100, 20)); executionStatusComboBox.insertItemAt("Pass", 0); executionStatusComboBox.insertItemAt("Fail", 1); executionStatusComboBox.setSelectedIndex(0); executionStatusComboBox.setPreferredSize(new Dimension(100, 20)); startButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { TestPlanExecutiongui.this.execute(event); } }); this.addWindowListener( new WindowAdapter() { /* @Override public void windowClosing(WindowEvent e) { try { Collection<TestlinkguiMessageThread> cols = Testlinkgui.this.map.values(); String messageXML = XMLUtil.constructCloseTestlinkguiWindowXML(); for(TestlinkguiMessageThread smt : cols) { smt.sendMessage(messageXML); } } catch(Exception ex) { ex.printStackTrace(); } finally { System.exit(0); } }*/ }); testplanPane.add(testplanLabel); testplanPane.add(testplanNameField); testplanPane.setBorder(BorderFactory.createEtchedBorder()); parameterPane.add(testplanPane); buildPane.add(buildLabel); buildPane.add(buildField); buildPane.setBorder(BorderFactory.createEtchedBorder()); parameterPane.add(buildPane); devPane.add(devLabel); devPane.add(devField); devPane.setBorder(BorderFactory.createEtchedBorder()); parameterPane.add(devPane); projectPane.add(projectLabel); projectPane.add(projectField); projectPane.setBorder(BorderFactory.createEtchedBorder()); parameterPane.add(projectPane); executionStatusPane.add(executionStatusLabel); executionStatusPane.add(executionStatusComboBox); executionStatusPane.setPreferredSize(new Dimension(328, 35)); executionStatusPane.setBorder(BorderFactory.createEtchedBorder()); parameterPane.add(executionStatusPane); executionTypePane.add(executionTypeLabel); executionTypePane.add(executionTypeComboBox); executionTypePane.setPreferredSize(new Dimension(328, 35)); executionTypePane.setAlignmentX(0); executionTypePane.setBorder(BorderFactory.createEtchedBorder()); parameterPane.add(executionTypePane); startPane.add(descriptionLable); startPane.add(startButton); startPane.setBorder(BorderFactory.createEtchedBorder()); startPane.setPreferredSize(new Dimension(328, 35)); parameterPane.add(startPane); jTextArea.setEditable(false); // 不允许用户手动修改在线用户列表 jTextArea.setRows(20); jTextArea.setColumns(60); jTextArea.setForeground(new Color(0, 51, 204)); jScrollPane.setViewportView(jTextArea); // 将JTextArea放置到JScrollPane中 caseListPane.add(jScrollPane); this.getContentPane().add(helpPane, BorderLayout.NORTH); this.getContentPane().add(parameterPane, BorderLayout.WEST); this.getContentPane().add(caseListPane, BorderLayout.EAST); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setAlwaysOnTop(true); this.setResizable(false); this.pack(); this.setVisible(true); }
/** * Customization of external program paths. * * @param prefs a <code>JabRefPreferences</code> value */ public TablePrefsTab(JabRefPreferences prefs) { this.prefs = prefs; setLayout(new BorderLayout()); /** * Added Bibtexkey to combobox. * * <p>[ 1540646 ] default sort order: bibtexkey * * <p>http://sourceforge.net/tracker/index.php?func=detail&aid=1540646&group_id=92314&atid=600306 */ Vector<String> fieldNames = new Vector<String>(Arrays.asList(BibtexFields.getAllFieldNames())); fieldNames.add(BibtexFields.KEY_FIELD); Collections.sort(fieldNames); String[] allPlusKey = fieldNames.toArray(new String[fieldNames.size()]); priSort = new JComboBox(allPlusKey); secSort = new JComboBox(allPlusKey); terSort = new JComboBox(allPlusKey); autoResizeMode = new JCheckBox(Localization.lang("Fit table horizontally on screen")); namesAsIs = new JRadioButton(Localization.lang("Show names unchanged")); namesFf = new JRadioButton(Localization.lang("Show 'Firstname Lastname'")); namesFl = new JRadioButton(Localization.lang("Show 'Lastname, Firstname'")); namesNatbib = new JRadioButton(Localization.lang("Natbib style")); noAbbrNames = new JRadioButton(Localization.lang("Do not abbreviate names")); abbrNames = new JRadioButton(Localization.lang("Abbreviate names")); lastNamesOnly = new JRadioButton(Localization.lang("Show last names only")); floatMarked = new JCheckBox(Localization.lang("Float marked entries")); priField = new JTextField(10); secField = new JTextField(10); terField = new JTextField(10); numericFields = new JTextField(30); priSort.insertItemAt(Localization.lang("<select>"), 0); secSort.insertItemAt(Localization.lang("<select>"), 0); terSort.insertItemAt(Localization.lang("<select>"), 0); priSort.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (priSort.getSelectedIndex() > 0) { priField.setText(priSort.getSelectedItem().toString()); priSort.setSelectedIndex(0); } } }); secSort.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (secSort.getSelectedIndex() > 0) { secField.setText(secSort.getSelectedItem().toString()); secSort.setSelectedIndex(0); } } }); terSort.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (terSort.getSelectedIndex() > 0) { terField.setText(terSort.getSelectedItem().toString()); terSort.setSelectedIndex(0); } } }); ButtonGroup nameStyle = new ButtonGroup(); nameStyle.add(namesAsIs); nameStyle.add(namesNatbib); nameStyle.add(namesFf); nameStyle.add(namesFl); ButtonGroup nameAbbrev = new ButtonGroup(); nameAbbrev.add(lastNamesOnly); nameAbbrev.add(abbrNames); nameAbbrev.add(noAbbrNames); priDesc = new JCheckBox(Localization.lang("Descending")); secDesc = new JCheckBox(Localization.lang("Descending")); terDesc = new JCheckBox(Localization.lang("Descending")); FormLayout layout = new FormLayout( "1dlu, 8dlu, left:pref, 4dlu, fill:pref, 4dlu, fill:60dlu, 4dlu, fill:pref", ""); DefaultFormBuilder builder = new DefaultFormBuilder(layout); JLabel lab; JPanel pan = new JPanel(); builder.appendSeparator(Localization.lang("Format of author and editor names")); DefaultFormBuilder nameBuilder = new DefaultFormBuilder(new FormLayout("left:pref, 8dlu, left:pref", "")); nameBuilder.append(namesAsIs); nameBuilder.append(noAbbrNames); nameBuilder.nextLine(); nameBuilder.append(namesFf); nameBuilder.append(abbrNames); nameBuilder.nextLine(); nameBuilder.append(namesFl); nameBuilder.append(lastNamesOnly); nameBuilder.nextLine(); nameBuilder.append(namesNatbib); builder.append(pan); builder.append(nameBuilder.getPanel()); builder.nextLine(); builder.appendSeparator(Localization.lang("Default sort criteria")); // Create a new panel with its own FormLayout for these items: FormLayout layout2 = new FormLayout("left:pref, 8dlu, fill:pref, 4dlu, fill:60dlu, 4dlu, left:pref", ""); DefaultFormBuilder builder2 = new DefaultFormBuilder(layout2); lab = new JLabel(Localization.lang("Primary sort criterion")); builder2.append(lab); builder2.append(priSort); builder2.append(priField); builder2.append(priDesc); builder2.nextLine(); lab = new JLabel(Localization.lang("Secondary sort criterion")); builder2.append(lab); builder2.append(secSort); builder2.append(secField); builder2.append(secDesc); builder2.nextLine(); lab = new JLabel(Localization.lang("Tertiary sort criterion")); builder2.append(lab); builder2.append(terSort); builder2.append(terField); builder2.append(terDesc); builder.nextLine(); builder.append(pan); builder.append(builder2.getPanel()); builder.nextLine(); builder.append(pan); builder.append(floatMarked); builder.nextLine(); builder.append(pan); builder2 = new DefaultFormBuilder(new FormLayout("left:pref, 8dlu, fill:pref", "")); builder2.append(Localization.lang("Sort the following fields as numeric fields") + ':'); builder2.append(numericFields); builder.append(builder2.getPanel(), 5); builder.nextLine(); builder.appendSeparator(Localization.lang("General")); builder.append(pan); builder.append(autoResizeMode); builder.nextLine(); pan = builder.getPanel(); pan.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); add(pan, BorderLayout.CENTER); namesNatbib.addChangeListener( new ChangeListener() { @Override public void stateChanged(ChangeEvent changeEvent) { abbrNames.setEnabled(!namesNatbib.isSelected()); lastNamesOnly.setEnabled(!namesNatbib.isSelected()); noAbbrNames.setEnabled(!namesNatbib.isSelected()); } }); }
public void AddSelectInCombo(JComboBox jc) { jc.insertItemAt("SELECT", 0); jc.setSelectedIndex(0); }
/** * Constructeur de recherche * * @param titre * @throws IOException */ public Recherche(String titre) throws IOException { setTitle(titre); // Container conteneur=this.getContentPane(); // conteneur.setLayout(new BorderLayout(2,1)); switchcherche = 0; setSize(1200, 800); InputStream input = img.class.getResourceAsStream("med.jpg"); JPanel panneau = new PanelImage(input); panneau.setLayout(null); // this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String[] typeRecherche = { "Docteur", "Malade", "Chambre", "Employe", "Infirmier", "Service", "Hospitalisation", "Soigne" }; rechercheDesire = new JLabel(); rechercheDesire.setText(" Selectionner une table :"); rechercheDesire.setBounds(400, 120, 400, 40); rechercheDesire.setBackground(Color.lightGray); rechercheDesire.setOpaque(true); panneau.add(rechercheDesire); rechercheDesireBox = new JComboBox(); for (int i = 0; i < typeRecherche.length; i++) { rechercheDesireBox.insertItemAt(typeRecherche[i], i); } rechercheDesireBox.setBounds(400, 160, 400, 80); panneau.add(rechercheDesireBox); explication = new JLabel(); explication.setBounds(200, 240, 800, 40); panneau.add(explication); explication.setBackground(Color.LIGHT_GRAY); explication.setOpaque(true); explication.setText( " Pour tout afficher : ne rien saisir dans les lignes de recherche"); rech1 = new JLabel(); rech1.setBounds(200, 300, 200, 50); rech1.setText(" Recherche 1"); rech1.setBackground(Color.LIGHT_GRAY); rech1.setOpaque(true); panneau.add(rech1); recherche1 = new JTextField(""); recherche1.setBounds(400, 300, 200, 50); // this.add("South",result1); panneau.add(recherche1); result1 = new JComboBox(); result1.setBounds(600, 300, 400, 50); panneau.add(result1); rech2 = new JLabel(); rech2.setBounds(200, 370, 200, 50); rech2.setText(" Recherche 2"); rech2.setBackground(Color.lightGray); rech2.setOpaque(true); panneau.add(rech2); recherche2 = new JTextField(""); recherche2.setBounds(400, 370, 200, 50); // this.add("South",result2); panneau.add(recherche2); result2 = new JComboBox(); result2.setBounds(600, 370, 400, 50); panneau.add(result2); rech3 = new JLabel(); rech3.setBounds(200, 440, 200, 50); rech3.setText(" Recherche 3"); rech3.setBackground(Color.lightGray); rech3.setOpaque(true); panneau.add(rech3); recherche3 = new JTextField(""); recherche3.setBounds(400, 440, 200, 50); panneau.add(recherche3); result3 = new JComboBox(); result3.setBounds(600, 440, 400, 50); panneau.add(result3); exit = new JButton("Retour"); exit.setForeground(Color.red); exit.setBounds(430, 700, 160, 40); valider = new JButton("Rechercher"); // valider.setForeground(Color.green); valider.setBounds(610, 700, 160, 40); panneau.add(valider); panneau.add(exit); rechercheDesireBox.addActionListener(this); recherche1.addActionListener(this); recherche2.addActionListener(this); recherche3.addActionListener(this); valider.addActionListener(this); exit.addActionListener(this); // conteneur.add(panneau); fentreCard.add("Recherche", panneau); setVisible(false); }
@Override public void actionPerformed(ActionEvent event) { if (event.getSource().getClass() == JButton.class) { if (event.getSource() == exit) { fentreCard.show("Menu"); } if (event.getSource() == valider) { try { try { String at1, re1, at2, re2, at3, re3; re1 = recherche1.getText(); re2 = recherche2.getText(); re3 = recherche3.getText(); try { at1 = result1.getSelectedItem().toString(); } catch (Exception e) { at1 = ""; } try { at2 = result2.getSelectedItem().toString(); } catch (Exception e) { at2 = ""; } try { at3 = result3.getSelectedItem().toString(); } catch (Exception e) { at3 = ""; } switch (switchcherche) { case 1: RechercheTab r1 = new RechercheTab(JobDocteur.FindResult(at1, re1, at2, re2, at3, re3), 1); break; case 2: RechercheTab r2 = new RechercheTab(JobMalade.FindResult(at1, re1, at2, re2, at3, re3), 2); break; case 3: RechercheTab r3 = new RechercheTab(JobInfirmier.FindResult(at1, re1, at2, re2, at3, re3), 3); break; case 4: RechercheTab r4 = new RechercheTab(JobEmploye.FindResult(at1, re1, at2, re2, at3, re3), 4); break; case 5: RechercheTab r5 = new RechercheTab( JobHospitalisation.FindResult(at1, re1, at2, re2, at3, re3), 5); break; case 6: RechercheTab r6 = new RechercheTab(JobChambre.FindResult(at1, re1, at2, re2, at3, re3), 6); break; case 7: RechercheTab r7 = new RechercheTab(JobService.FindResult(at1, re1, at2, re2, at3, re3), 7); break; case 8: RechercheTab r8 = new RechercheTab(JobSoigne.FindResult(at1, re1, at2, re2, at3, re3), 8); break; default: break; } } catch (SQLException ex) { Logger.getLogger(Recherche.class.getName()).log(Level.SEVERE, null, ex); } } catch (IOException ex) { Logger.getLogger(Recherche.class.getName()).log(Level.SEVERE, null, ex); } fentreCard.show("RechercheTab"); } } else if (event.getSource().getClass() == JComboBox.class) { if ("Docteur".equals((String) ((JComboBox) event.getSource()).getSelectedItem())) { String[] DocteurRecherche = { "Numero", "Nom", "Prenom", "Adresse", "Telephone", "Specialite" }; result1.removeAllItems(); result2.removeAllItems(); result3.removeAllItems(); switchcherche = 1; for (int i = 0; i < DocteurRecherche.length; i++) { result1.insertItemAt(DocteurRecherche[i], i); result2.insertItemAt(DocteurRecherche[i], i); result3.insertItemAt(DocteurRecherche[i], i); } } else if ("Malade".equals((String) ((JComboBox) event.getSource()).getSelectedItem())) { String[] MaladeRecherche = {"Numero", "Nom", "Prenom", "Telephone", "Adresse", "Mutuelle"}; result1.removeAllItems(); result2.removeAllItems(); result3.removeAllItems(); switchcherche = 2; for (int i = 0; i < MaladeRecherche.length; i++) { result1.insertItemAt(MaladeRecherche[i], i); result2.insertItemAt(MaladeRecherche[i], i); result3.insertItemAt(MaladeRecherche[i], i); } } else if ("Infirmier".equals((String) ((JComboBox) event.getSource()).getSelectedItem())) { String[] InfirmierRecherche = { "Numero", "Nom", "Prenom", "Nom Service", "Telephone", "Adresse", "Rotation" }; result1.removeAllItems(); result2.removeAllItems(); result3.removeAllItems(); switchcherche = 3; for (int i = 0; i < InfirmierRecherche.length; i++) { result1.insertItemAt(InfirmierRecherche[i], i); result2.insertItemAt(InfirmierRecherche[i], i); result3.insertItemAt(InfirmierRecherche[i], i); } } else if ("Employe".equals((String) ((JComboBox) event.getSource()).getSelectedItem())) { String[] EmployeRecherche = {"Numero", "Nom", "Prenom", "Telephone", "Adresse"}; result1.removeAllItems(); result2.removeAllItems(); result3.removeAllItems(); switchcherche = 4; for (int i = 0; i < EmployeRecherche.length; i++) { result1.insertItemAt(EmployeRecherche[i], i); result2.insertItemAt(EmployeRecherche[i], i); result3.insertItemAt(EmployeRecherche[i], i); } } else if ("Hospitalisation" .equals((String) ((JComboBox) event.getSource()).getSelectedItem())) { String[] HospitalisationRecherche = { "Numero du Malade", "Nom du Malade", "Numero du Service", "Nom du Service", "Chambre", "Numero du lit" }; result1.removeAllItems(); result2.removeAllItems(); result3.removeAllItems(); switchcherche = 5; for (int i = 0; i < HospitalisationRecherche.length; i++) { result1.insertItemAt(HospitalisationRecherche[i], i); result2.insertItemAt(HospitalisationRecherche[i], i); result3.insertItemAt(HospitalisationRecherche[i], i); } } else if ("Chambre".equals((String) ((JComboBox) event.getSource()).getSelectedItem())) { String[] ChambreRecherche = { "Numero Chambre", "Surveillant", "Nom Service", "Nombres de lits" }; result1.removeAllItems(); result2.removeAllItems(); result3.removeAllItems(); switchcherche = 6; for (int i = 0; i < ChambreRecherche.length; i++) { result1.insertItemAt(ChambreRecherche[i], i); result2.insertItemAt(ChambreRecherche[i], i); result3.insertItemAt(ChambreRecherche[i], i); } } else if ("Service".equals((String) ((JComboBox) event.getSource()).getSelectedItem())) { String[] ServiceRecherche = {"Code du Service", "Nom Service", "Batiment", "Directeur"}; result1.removeAllItems(); result2.removeAllItems(); result3.removeAllItems(); switchcherche = 7; for (int i = 0; i < ServiceRecherche.length; i++) { result1.insertItemAt(ServiceRecherche[i], i); result2.insertItemAt(ServiceRecherche[i], i); result3.insertItemAt(ServiceRecherche[i], i); } } else if ("Soigne".equals((String) ((JComboBox) event.getSource()).getSelectedItem())) { String[] SoigneRecherche = { "Numero du Docteur", "Nom Docteur", "Specialite du Docteur", "Numero du Malade", "Nom du Malade", "Mutuelle" }; result1.removeAllItems(); result2.removeAllItems(); result3.removeAllItems(); switchcherche = 8; for (int i = 0; i < SoigneRecherche.length; i++) { result1.insertItemAt(SoigneRecherche[i], i); result2.insertItemAt(SoigneRecherche[i], i); result3.insertItemAt(SoigneRecherche[i], i); } } } }
/** Initialize the contents of the frame. */ public void drawBoard() { // Set up the frame frmFloodFantasyLeague = new JFrame(); frmFloodFantasyLeague.setBackground(new Color(0, 0, 205)); frmFloodFantasyLeague.setTitle("FLOOD Fantasy League: " + theLeague.getName()); frmFloodFantasyLeague.setBounds(100, 100, 450, 300); frmFloodFantasyLeague.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmFloodFantasyLeague.setSize(new Dimension(700, 400)); frmFloodFantasyLeague.setVisible(true); // Initialize and add the tabbed pane final JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); frmFloodFantasyLeague.getContentPane().add(tabbedPane, BorderLayout.CENTER); // Initialize the home tab JSplitPane homeSplitPane = new JSplitPane(); homeSplitPane.setResizeWeight(0.99); homeSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); // Initialize the home tab toolbar JToolBar homeToolBar = new JToolBar(); homeToolBar.setFloatable(false); homeSplitPane.setRightComponent(homeToolBar); // Add the upload stats button to the toolbar JButton uploadStatsButton = new JButton("Upload Stat File"); uploadStatsButton.setMaximumSize(new Dimension(32767, 32767)); homeToolBar.add(uploadStatsButton); // Add the create dump button to the toolbar JButton createDumpButton = new JButton("Create Dump File"); createDumpButton.setMaximumSize(new Dimension(32767, 32767)); homeToolBar.add(createDumpButton); // Add the import dump button to the toolbar JButton importDumpButton = new JButton("Import Dump File"); importDumpButton.setMaximumSize(new Dimension(32767, 32767)); homeToolBar.add(importDumpButton); // Initialize the home tab scrollpane JScrollPane homePane = new JScrollPane(); homeSplitPane.setLeftComponent(homePane); // Add the home tab to the tabbed pane tabbedPane.addTab("Home", null, homeSplitPane, null); // Initialize, format and add the home table homeModel = new DefaultTableModel(homeHeader, 0); // Add the header but no rows homeTable = new MyTableModel(homeModel); homeTable.setEnabled(false); // Make the rows unselectable homeTable.setAutoCreateRowSorter(true); // Allow sorting homePane.setViewportView(homeTable); // Put the table into the scroll pane populateHome(); // Populate the home table JSplitPane draftSplitPane = new JSplitPane(); // Add the draft split pane draftSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); // Split vertically tabbedPane.addTab("Draft", null, draftSplitPane, null); // Add the split pane to the tabbed pane // Initialize and add the draft scroll pane JScrollPane draftScrollPane = new JScrollPane(); draftSplitPane.setRightComponent(draftScrollPane); // Initialize, format and add the draft table draftModel = new DefaultTableModel(playerInfoHeader, 0); // Add the header but no rows draftTable = new MyTableModel(draftModel); draftTable.setRowSelectionAllowed(true); // Allow row selection draftTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION); // Allow only one row selection at a time draftTable.setAutoCreateRowSorter(true); // Allow sorting draftScrollPane.setViewportView(draftTable); // Put the table into the scroll pane // Initialize, format and add the draft tool bar JToolBar draftToolBar = new JToolBar(); draftToolBar.setFloatable(false); draftSplitPane.setLeftComponent(draftToolBar); // Initialize, format and add the draft label draftLabel = new JLabel(); draftLabel.setMinimumSize(new Dimension(600, 15)); draftLabel.setMaximumSize(new Dimension(32767, 15)); draftToolBar.add(draftLabel); // Initialize,format and add the draft button JButton btnDraft = new JButton("Draft"); btnDraft.setPreferredSize(new Dimension(100, 25)); btnDraft.setMaximumSize(new Dimension(100, 25)); btnDraft.setMinimumSize(new Dimension(100, 25)); draftToolBar.add(btnDraft); // Initialize, format and add the trade split pane JSplitPane tradeSplitPane = new JSplitPane(); tradeSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); // Split vertically tabbedPane.addTab("Trade", null, tradeSplitPane, null); // Initialize, format and add the trade tool bar JToolBar tradeToolBar = new JToolBar(); tradeToolBar.setFloatable(false); tradeSplitPane.setLeftComponent(tradeToolBar); // Initialize, format and add the first trade combo box final JComboBox tradeComboBox_1 = new JComboBox(); tradeToolBar.add(tradeComboBox_1); // Initialize, format and add the second trade combo bos final JComboBox tradeComboBox_2 = new JComboBox(); tradeToolBar.add(tradeComboBox_2); // Initialize and add the trade button JButton btnTrade = new JButton("Trade"); tradeToolBar.add(btnTrade); // Initialize, format and add the second trade split pane JSplitPane tradeSplitPane_2 = new JSplitPane(); tradeSplitPane_2.setResizeWeight(0.5); tradeSplitPane.setRightComponent(tradeSplitPane_2); // Initialize and add the left trade scroll pane JScrollPane tradeScrollPane_1 = new JScrollPane(); tradeSplitPane_2.setLeftComponent(tradeScrollPane_1); // Initialize, format and add the left trade table tradeModel_1 = new DefaultTableModel(playerInfoHeader, 0); // Add the header but no rows tradeTable_1 = new MyTableModel(tradeModel_1); tradeTable_1.setRowSelectionAllowed(true); // Set selection of entire rows tradeTable_1.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); // Allow multiple row selection tradeTable_1.setAutoCreateRowSorter(true); // Allow sorting tradeScrollPane_1.setViewportView(tradeTable_1); // Add table to scroll pane // Initialize and add the right trade scroll pane JScrollPane tradeScrollPane_2 = new JScrollPane(); tradeSplitPane_2.setRightComponent(tradeScrollPane_2); // Initialize, format and add the right trade table tradeModel_2 = new DefaultTableModel(playerInfoHeader, 0); // Add the header but no rows tradeTable_2 = new MyTableModel(tradeModel_2); tradeTable_2.setRowSelectionAllowed(true); // Set selection of entire rows tradeTable_2.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); // Allow multiple row selection tradeTable_2.setAutoCreateRowSorter(true); // Allow sorting tradeScrollPane_2.setViewportView(tradeTable_2); // Add table to scroll pane // Initialize, format and add the drop split pane JSplitPane dropSplitPane = new JSplitPane(); dropSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); // Split vertically tabbedPane.addTab("Drop", null, dropSplitPane, null); // Initialize, format and add the drop toolbar JToolBar dropToolBar = new JToolBar(); dropToolBar.setFloatable(false); dropSplitPane.setLeftComponent(dropToolBar); // Initialize and add the drop combo box final JComboBox dropComboBox = new JComboBox(); dropToolBar.add(dropComboBox); // Initialize and add the drop button JButton btnDrop = new JButton("Drop"); dropToolBar.add(btnDrop); // Initialize and add the drop scroll pane JScrollPane dropScrollPane = new JScrollPane(); dropSplitPane.setRightComponent(dropScrollPane); // Initialize, format and add the drop table dropModel = new DefaultTableModel(playerInfoHeader, 0); // Add the header but no rows dropTable = new MyTableModel(dropModel); dropTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Alow single selection dropTable.setAutoCreateRowSorter(true); // Allow sorting dropScrollPane.setViewportView(dropTable); // Add the table to the scroll pane // Initialize the home tab scrollpane JScrollPane actionPane = new JScrollPane(); // Add the home tab to the tabbed pane tabbedPane.addTab("Actions", null, actionPane, null); // Initialize, format and add the home table actionModel = new DefaultTableModel(ruleHeader, 0); // Add the header but no rows actionTable = new MyTableModel(actionModel); actionTable.setEnabled(false); // Make the rows unselectable actionTable.setAutoCreateRowSorter(true); // Allow sorting actionPane.setViewportView(actionTable); // Put the table into the scroll pane populateActions(); // Populate the home table // Initialize the file chooser final JFileChooser chooser = new JFileChooser(); // Populate both trade and the drop combo boxes User[] rankedTeams = theLeague.getRankedUsers(); for (int i = 0; i < rankedTeams.length; i++) { tradeComboBox_1.insertItemAt(rankedTeams[i].getName(), i); tradeComboBox_2.insertItemAt(rankedTeams[i].getName(), i); dropComboBox.insertItemAt(rankedTeams[i].getName(), i); } // ************************************************************************ // ****************************Action Listeners**************************** // ************************************************************************ // Action listener for changing tabs tabbedPane.addChangeListener( new ChangeListener() { public void stateChanged(ChangeEvent e) { int selection = tabbedPane.getSelectedIndex(); // Get selected tab switch (selection) { case 0: // Populate home table populateHome(); break; case 1: // Populate draft table populateDraft(); break; case 4: populateActions(); break; } } }); // Stats upload action listener uploadStatsButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent arg0) { int result = chooser.showOpenDialog(null); // Determine what the user pressed switch (result) { case JFileChooser.APPROVE_OPTION: // Opened file File file = chooser.getSelectedFile(); // Get the chosen file IOManager.uploadStats( theLeague, file.getAbsolutePath()); // Pass the file path to the parser method populateHome(); break; case JFileChooser.CANCEL_OPTION: // Canceled break; case JFileChooser.ERROR_OPTION: // Generated an error GUI.error("Upload Error!", "Sorry, there was an error opening the stat file."); break; } } }); // Dump generator action listener createDumpButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { chooser.setSelectedFile(new File("flooddmp.txt")); int result = chooser.showSaveDialog(null); switch (result) { case JFileChooser.APPROVE_OPTION: // Opened file File file = chooser.getSelectedFile(); // Get the chosen file if (file.exists()) { int overwrite = JOptionPane.showConfirmDialog( frmFloodFantasyLeague, "Do you want to overwrite " + file.getName()); if (overwrite == JOptionPane.YES_OPTION) { IOManager.writeState( theLeague, file.getAbsolutePath(), currentTurn); // Pass the file path to the parser method tabbedPane.setSelectedIndex(0); } } else { IOManager.writeState( theLeague, file.getAbsolutePath(), currentTurn); // Pass the file path to the parser method tabbedPane.setSelectedIndex(0); } break; case JFileChooser.CANCEL_OPTION: // Canceled break; case JFileChooser.ERROR_OPTION: // Generated an error GUI.error("Upload Error!", "Sorry, error creating the dump file."); break; } } }); // Dump importer action listener importDumpButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent arg0) { int result = chooser.showOpenDialog(null); // Determine what the user pressed switch (result) { case JFileChooser.APPROVE_OPTION: // Opened file File file = chooser.getSelectedFile(); // Get the chosen file int temp = IOManager.importState( theLeague, file.getAbsolutePath()); // Pass the file path to the parser method if (temp != -1) { currentTurn = temp; populateDraft(); } populateHome(); break; case JFileChooser.CANCEL_OPTION: // Canceled break; case JFileChooser.ERROR_OPTION: // Generated an error GUI.error("Upload Error!", "Sorry, there was an error opening the stat file."); break; } } }); // Determine which user is picking first pick = FloodProgram.draftFunction(currentTurn); // Gets the number representing the user's turn draftLabel.setText( theLeague.getUser(pick).getName() + "'s turn!"); // Puts the user's name in the label // Draft action listener btnDraft.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent arg0) { for (int i = 0; i < draftModel.getRowCount(); i++) { // Iterate through table entries if (draftTable.isCellSelected(i, 0)) { // If it's selected int overwrite = JOptionPane.showConfirmDialog( frmFloodFantasyLeague, "Are you sure you want to draft: " + League.athletes.get(draftModel.getValueAt(i, 0)).getName()); if (overwrite == JOptionPane.YES_OPTION) { if (!FloodProgram.draftPlayer( theLeague.getUser(pick), League.athletes.get( draftModel.getValueAt(i, 0)))) { // If the draft isn't successful GUI.error("Invalid draft!", "Sorry, your draft violates rules of the league."); return; } currentTurn++; // Increment the turn draftModel.removeRow(i); // Remove that row from the draft table populateDraft(); // Make all the combo boxes not select anything tradeComboBox_1.setSelectedIndex(-1); tradeComboBox_2.setSelectedIndex(-1); dropComboBox.setSelectedIndex(-1); // Remove the current tables in all the other tabs so that they are up to date while (tradeModel_1.getRowCount() > 0) { tradeModel_1.removeRow(0); } while (tradeModel_2.getRowCount() > 0) { tradeModel_2.removeRow(0); } while (dropModel.getRowCount() > 0) { dropModel.removeRow(0); } return; } return; } } // If no selection is found GUI.error("Add error!", "Sorry, no player was selected!"); } }); // Action listener for left trade combo box tradeComboBox_1.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { if (tradeComboBox_1.getSelectedIndex() != -1) { // If a user is selected Player[] teamPlayers = League.teams .get(tradeComboBox_1.getSelectedItem()) .getPlayers(); // Get the players the user has while (tradeModel_1.getRowCount() > 0) { // Clear the current table tradeModel_1.removeRow(0); } for (int i = 0; i < teamPlayers.length; i++) { // Populate the table with the new data String[] temp = { teamPlayers[i].getName(), teamPlayers[i].getPosition(), Float.toString(teamPlayers[i].getPoints()) }; // Initialize the row tradeModel_1.addRow(temp); } } } }); // Action listener for the right trade combo box tradeComboBox_2.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { if (tradeComboBox_2.getSelectedIndex() != -1) { // If a user is selected Player[] teamPlayers = League.teams .get(tradeComboBox_2.getSelectedItem()) .getPlayers(); // Get the players the user has while (tradeModel_2.getRowCount() > 0) { // Clear the current table tradeModel_2.removeRow(0); } for (int i = 0; i < teamPlayers.length; i++) { // Populate the table with the new data String[] temp = { teamPlayers[i].getName(), teamPlayers[i].getPosition(), Float.toString(teamPlayers[i].getPoints()) }; // Initialize the row tradeModel_2.addRow(temp); } } } }); // Action listener for the trade button btnTrade.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (tradeComboBox_1.getSelectedIndex() == -1 || tradeComboBox_2.getSelectedIndex() == -1) { // If either combo box doesn't have a user selected GUI.error("Trade error!", "Must select two teams to trade between."); return; } else if (tradeComboBox_1.getSelectedIndex() == tradeComboBox_2 .getSelectedIndex()) { // If the same user is selected in each combo box GUI.error("Trade error!", "Must select two different teams to trade between."); return; } int rows1[] = tradeTable_1.getSelectedRows(); // Get selected rows in the left table int rows2[] = tradeTable_2.getSelectedRows(); // Get selected rows in the right table if (rows1.length == 0 && rows2.length == 0) { // If no players are selected GUI.error("Trade error!", "Must select at least one player to trade."); return; } int overwrite = JOptionPane.showConfirmDialog( frmFloodFantasyLeague, "Are you sure you want to trade?"); if (overwrite == JOptionPane.YES_OPTION) { Player[] p1 = new Player[rows1.length]; // Initialize player array for the left table selection Player[] p2 = new Player[rows2.length]; // Initialize player array for the right table selection // Populate the player arrays for (int i = 0; i < p1.length; i++) { p1[i] = League.athletes.get(tradeModel_1.getValueAt(rows1[i], 0)); } for (int i = 0; i < p2.length; i++) { p2[i] = League.athletes.get(tradeModel_2.getValueAt(rows2[i], 0)); } boolean success = FloodProgram.trade( League.teams.get( tradeComboBox_1 // Determine if it's a successful trade .getSelectedItem()), p1, League.teams.get(tradeComboBox_2.getSelectedItem()), p2); if (!success) { // If unsuccessful GUI.error("Invalid trade!", "Sorry, your trade violates rules of the league."); return; } // Repopulate the tables Player[] teamPlayers = League.teams.get(tradeComboBox_1.getSelectedItem()).getPlayers(); while (tradeModel_1.getRowCount() > 0) { // Clear the left trade table tradeModel_1.removeRow(0); } for (int i = 0; i < teamPlayers.length; i++) { // Repopulate the left trade table String[] temp = { teamPlayers[i].getName(), teamPlayers[i].getPosition(), Float.toString(teamPlayers[i].getPoints()) }; tradeModel_1.addRow(temp); // Add the row } teamPlayers = League.teams.get(tradeComboBox_2.getSelectedItem()).getPlayers(); while (tradeModel_2.getRowCount() > 0) { // Clear the left trade table tradeModel_2.removeRow(0); } for (int i = 0; i < teamPlayers.length; i++) { // Repopulate the left trade table String[] temp = { teamPlayers[i].getName(), teamPlayers[i].getPosition(), Float.toString(teamPlayers[i].getPoints()) }; tradeModel_2.addRow(temp); // Add the row } } } }); // Action listener for drop combo box dropComboBox.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { if (dropComboBox.getSelectedIndex() != -1) { // If a user is selected Player[] teamPlayers = League.teams .get(dropComboBox.getSelectedItem()) .getPlayers(); // Get the user's players while (dropModel.getRowCount() > 0) { // Clear the table dropModel.removeRow(0); } for (int i = 0; i < teamPlayers.length; i++) { // Repopulate the table String[] temp = { teamPlayers[i].getName(), teamPlayers[i].getPosition(), Float.toString(teamPlayers[i].getPoints()) }; dropModel.addRow(temp); // Add the row } } } }); // Action listener for drop button btnDrop.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent arg0) { int index = dropTable.getSelectedRow(); if (index == -1) { // If no player is selected to drop GUI.error("Drop error!", "Must select a team to drop a player from."); return; } int overwrite = JOptionPane.showConfirmDialog( frmFloodFantasyLeague, "Are you sure you want to drop: " + League.athletes.get(dropModel.getValueAt(index, 0)).getName()); if (overwrite == JOptionPane.YES_OPTION) { Player drop = League.athletes.get(dropModel.getValueAt(index, 0)); // Get player boolean success = FloodProgram.dropPlayer( League.teams.get(dropComboBox.getSelectedItem()), drop); // Determine if drop is successful if (!success) { GUI.error("Invalid drop!", "Sorry, your drop violates rules of the league."); return; } dropModel.removeRow(index); // Delete that row // Make all the combo boxes not select anything tradeComboBox_1.setSelectedIndex(-1); tradeComboBox_2.setSelectedIndex(-1); while (tradeModel_1.getRowCount() > 0) { tradeModel_1.removeRow(0); } while (tradeModel_2.getRowCount() > 0) { tradeModel_2.removeRow(0); } } } }); tabbedPane.setSelectedIndex(0); }
/** Creates new form PanelUsuarios */ public PanelUsuarios() { initComponents(); tabla.setDefaultEditor(GregorianCalendar.class, new DateCellEditor()); tabla.setDefaultRenderer( GregorianCalendar.class, new DefaultTableCellRenderer() { @Override public void setValue(Object val) { if (val instanceof GregorianCalendar) { setText(Fechas.format((GregorianCalendar) val)); } else { setText(""); } } }); TableColumnExt colRoles = tabla.getColumnExt("Roles"); colRoles.setCellEditor(new EditorRoles()); colRoles.setCellRenderer( new DefaultTableCellRenderer() { @Override public void setValue(Object val) { setText(Rol.getTextoRoles(Num.getInt(val))); } }); TableColumnExt colTutor = tabla.getColumnExt("Profesor"); TableColumnExt colClave = tabla.getColumnExt("Clave"); colClave.setCellRenderer( new DefaultTableCellRenderer() { @Override public void setValue(Object val) { setText("*********"); } }); colClave.setCellEditor(new DefaultCellEditor(new JPasswordField())); JComboBox comboTutores = new JComboBox(Profesor.getProfesores().toArray()); comboTutores.insertItemAt("Sin profesor asignado", 0); DefaultCellEditor dceTutor = new DefaultCellEditor(comboTutores) { @Override public Object getCellEditorValue() { Object obj = super.getCellEditorValue(); if (obj instanceof Profesor) { return ((Profesor) obj); } return null; } @Override public Component getTableCellEditorComponent( JTable table, Object value, boolean isSelected, int row, int column) { Component c = super.getTableCellEditorComponent(tabla, value, isSelected, row, column); try { int id = Num.getInt(value); if (id > 0) { Profesor p = Profesor.getProfesor(id); ((JComboBox) c).setSelectedItem(p); } else { ((JComboBox) c).setSelectedIndex(0); } } catch (Exception ex) { Logger.getLogger(PanelGrupos.class.getName()).log(Level.SEVERE, null, ex); } return c; } }; dceTutor.setClickCountToStart(2); colTutor.setCellEditor(dceTutor); }