List of usage examples for javax.swing.event ListSelectionListener ListSelectionListener
ListSelectionListener
From source file:com.mirth.connect.connectors.http.HttpListener.java
private void initComponentsManual() { staticResourcesTable.setModel(new RefreshTableModel(StaticResourcesColumn.getNames(), 0) { @Override/*w w w. java 2 s. c o m*/ public boolean isCellEditable(int rowIndex, int columnIndex) { return true; } }); staticResourcesTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); staticResourcesTable.setRowHeight(UIConstants.ROW_HEIGHT); staticResourcesTable.setFocusable(true); staticResourcesTable.setSortable(false); staticResourcesTable.setOpaque(true); staticResourcesTable.setDragEnabled(false); staticResourcesTable.getTableHeader().setReorderingAllowed(false); staticResourcesTable.setShowGrid(true, true); staticResourcesTable.setAutoCreateColumnsFromModel(false); staticResourcesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); staticResourcesTable.setRowSelectionAllowed(true); staticResourcesTable.setCustomEditorControls(true); if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) { staticResourcesTable.setHighlighters(HighlighterFactory .createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR, UIConstants.BACKGROUND_COLOR)); } class ContextPathCellEditor extends TextFieldCellEditor { public ContextPathCellEditor() { getTextField().setDocument(new MirthFieldConstraints("^\\S*$")); } @Override protected boolean valueChanged(String value) { if (StringUtils.isEmpty(value) || value.equals("/")) { return false; } if (value.equals(getOriginalValue())) { return false; } for (int i = 0; i < staticResourcesTable.getRowCount(); i++) { if (value.equals(fixContentPath((String) staticResourcesTable.getValueAt(i, StaticResourcesColumn.CONTEXT_PATH.getIndex())))) { return false; } } parent.setSaveEnabled(true); return true; } @Override public Object getCellEditorValue() { String value = fixContentPath((String) super.getCellEditorValue()); String baseContextPath = getBaseContextPath(); if (value.equals(baseContextPath)) { return null; } else { return fixContentPath(StringUtils.removeStartIgnoreCase(value, baseContextPath + "/")); } } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { String resourceContextPath = fixContentPath((String) value); setOriginalValue(resourceContextPath); getTextField().setText(getBaseContextPath() + resourceContextPath); return getTextField(); } } ; staticResourcesTable.getColumnExt(StaticResourcesColumn.CONTEXT_PATH.getIndex()) .setCellEditor(new ContextPathCellEditor()); staticResourcesTable.getColumnExt(StaticResourcesColumn.CONTEXT_PATH.getIndex()) .setCellRenderer(new DefaultTableCellRenderer() { @Override protected void setValue(Object value) { super.setValue(getBaseContextPath() + fixContentPath((String) value)); } }); class ResourceTypeCellEditor extends MirthComboBoxTableCellEditor implements ActionListener { private Object originalValue; public ResourceTypeCellEditor(JTable table, Object[] items, int clickCount, boolean focusable) { super(table, items, clickCount, focusable, null); for (ActionListener actionListener : comboBox.getActionListeners()) { comboBox.removeActionListener(actionListener); } comboBox.addActionListener(this); } @Override public boolean stopCellEditing() { if (ObjectUtils.equals(getCellEditorValue(), originalValue)) { cancelCellEditing(); } else { parent.setSaveEnabled(true); } return super.stopCellEditing(); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { originalValue = value; return super.getTableCellEditorComponent(table, value, isSelected, row, column); } @Override public void actionPerformed(ActionEvent evt) { ((AbstractTableModel) staticResourcesTable.getModel()).fireTableCellUpdated( staticResourcesTable.getSelectedRow(), StaticResourcesColumn.VALUE.getIndex()); stopCellEditing(); fireEditingStopped(); } } String[] resourceTypes = ResourceType.stringValues(); staticResourcesTable.getColumnExt(StaticResourcesColumn.RESOURCE_TYPE.getIndex()).setMinWidth(100); staticResourcesTable.getColumnExt(StaticResourcesColumn.RESOURCE_TYPE.getIndex()).setMaxWidth(100); staticResourcesTable.getColumnExt(StaticResourcesColumn.RESOURCE_TYPE.getIndex()) .setCellEditor(new ResourceTypeCellEditor(staticResourcesTable, resourceTypes, 1, false)); staticResourcesTable.getColumnExt(StaticResourcesColumn.RESOURCE_TYPE.getIndex()) .setCellRenderer(new MirthComboBoxTableCellRenderer(resourceTypes)); class ValueCellEditor extends AbstractCellEditor implements TableCellEditor { private JPanel panel; private JLabel label; private JTextField textField; private String text; private String originalValue; public ValueCellEditor() { panel = new JPanel(new MigLayout("insets 0 1 0 0, novisualpadding, hidemode 3")); panel.setBackground(UIConstants.BACKGROUND_COLOR); label = new JLabel(); label.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent evt) { new ValueDialog(); stopCellEditing(); } }); panel.add(label, "grow, pushx, h 19!"); textField = new JTextField(); panel.add(textField, "grow, pushx, h 19!"); } @Override public boolean isCellEditable(EventObject evt) { if (evt == null) { return false; } if (evt instanceof MouseEvent) { return ((MouseEvent) evt).getClickCount() >= 2; } return true; } @Override public Object getCellEditorValue() { if (label.isVisible()) { return text; } else { return textField.getText(); } } @Override public boolean stopCellEditing() { if (ObjectUtils.equals(getCellEditorValue(), originalValue)) { cancelCellEditing(); } else { parent.setSaveEnabled(true); } return super.stopCellEditing(); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { boolean custom = table.getValueAt(row, StaticResourcesColumn.RESOURCE_TYPE.getIndex()) .equals(ResourceType.CUSTOM.toString()); label.setVisible(custom); textField.setVisible(!custom); panel.setBackground(table.getSelectionBackground()); label.setBackground(panel.getBackground()); label.setMaximumSize(new Dimension(table.getColumnModel().getColumn(column).getWidth(), 19)); String text = (String) value; this.text = text; originalValue = text; label.setText(text); textField.setText(text); return panel; } class ValueDialog extends MirthDialog { public ValueDialog() { super(parent, true); setTitle("Custom Value"); setPreferredSize(new Dimension(600, 500)); setLayout(new MigLayout("insets 12, novisualpadding, hidemode 3, fill", "", "[grow]7[]")); setBackground(UIConstants.BACKGROUND_COLOR); getContentPane().setBackground(getBackground()); final MirthSyntaxTextArea textArea = new MirthSyntaxTextArea(); textArea.setSaveEnabled(false); textArea.setText(text); textArea.setBorder(BorderFactory.createEtchedBorder()); add(textArea, "grow"); add(new JSeparator(), "newline, grow"); JPanel buttonPanel = new JPanel(new MigLayout("insets 0, novisualpadding, hidemode 3")); buttonPanel.setBackground(getBackground()); JButton openFileButton = new JButton("Open File..."); openFileButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String content = parent.browseForFileString(null); if (content != null) { textArea.setText(content); } } }); buttonPanel.add(openFileButton); JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { text = textArea.getText(); label.setText(text); textField.setText(text); staticResourcesTable.getModel().setValueAt(text, staticResourcesTable.getSelectedRow(), StaticResourcesColumn.VALUE.getIndex()); parent.setSaveEnabled(true); dispose(); } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { dispose(); } }); buttonPanel.add(cancelButton); add(buttonPanel, "newline, right"); pack(); setLocationRelativeTo(parent); setVisible(true); } } } ; staticResourcesTable.getColumnExt(StaticResourcesColumn.VALUE.getIndex()) .setCellEditor(new ValueCellEditor()); staticResourcesTable.getColumnExt(StaticResourcesColumn.CONTENT_TYPE.getIndex()).setMinWidth(100); staticResourcesTable.getColumnExt(StaticResourcesColumn.CONTENT_TYPE.getIndex()).setMaxWidth(150); staticResourcesTable.getColumnExt(StaticResourcesColumn.CONTENT_TYPE.getIndex()) .setCellEditor(new TextFieldCellEditor() { @Override protected boolean valueChanged(String value) { if (value.equals(getOriginalValue())) { return false; } parent.setSaveEnabled(true); return true; } }); staticResourcesTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent evt) { if (getSelectedRow(staticResourcesTable) != -1) { staticResourcesLastIndex = getSelectedRow(staticResourcesTable); staticResourcesDeleteButton.setEnabled(true); } else { staticResourcesDeleteButton.setEnabled(false); } } }); contextPathField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent evt) { changedUpdate(evt); } @Override public void removeUpdate(DocumentEvent evt) { changedUpdate(evt); } @Override public void changedUpdate(DocumentEvent evt) { ((AbstractTableModel) staticResourcesTable.getModel()).fireTableDataChanged(); } }); staticResourcesDeleteButton.setEnabled(false); }
From source file:com.diversityarrays.kdxplore.specgroup.SpecimenGroupEditor.java
private JComponent createTopComponent(Action extraAction) { // refreshSpecimenList.setEnabled(false); loadAction.setEnabled(true);/*from w w w .j a va 2s . c om*/ Box specimenGroupControls = Box.createHorizontalBox(); specimenGroupControls.add(downloadGroupsButton); if (extraAction != null) { specimenGroupControls.add(new JButton(extraAction)); } specimenGroupControls.add(new JSeparator(JSeparator.VERTICAL)); // specimenGroupControls.add(new JButton(refreshSpecimenList)); specimenGroupControls.add(new JButton(loadAction)); specimenGroupTableModel = new SpecimenGroupTableModel(); specimenGroupTable = new JTable(specimenGroupTableModel); specimenGroupTable.setAutoCreateRowSorter(true); TableTransferHandler tth = TableTransferHandler.initialiseForCopySelectAll(specimenGroupTable, true); specimenGroupTable.setTransferHandler(tth); PromptScrollPane pane = new PromptScrollPane("No Specimen Groups Found"); pane.add(specimenGroupTable); specimenGroupTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); specimenGroupTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { List<Specimen> list = null; int vrow = specimenGroupTable.getSelectedRow(); if (vrow >= 0) { int mrow = specimenGroupTable.convertRowIndexToModel(vrow); if (mrow >= 0) { list = specimenGroupTableModel.getSpecimensAt(mrow); } } specimenTableModel.setData(list); } } }); JPanel containerPanel = new JPanel(new BorderLayout()); containerPanel.add(specimenGroupControls, BorderLayout.NORTH); containerPanel.add(new TitledTablePanel("Specimen Groups", specimenGroupTable, "No Specimen Groups Loaded"), BorderLayout.CENTER); return containerPanel; }
From source file:edu.ku.brc.af.ui.forms.TableViewObj.java
/** * Build the table now that we have all the information we need for the columns. *///from w w w . j a va 2 s . c o m protected void buildTable() { // Now Build the JTable model = new ColTableModel(); table = new JTable(model); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setRowSelectionAllowed(true); table.setColumnSelectionAllowed(false); table.setFocusable(false); //table.setPreferredScrollableViewportSize(new Dimension(200,table.getRowHeight()*6)); configColumns(); //table.setCellSelectionEnabled(false); table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { ListSelectionModel lsm = (ListSelectionModel) e.getSource(); updateUI(!lsm.isSelectionEmpty()); } } }); table.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent e) { if (e.getClickCount() == 2) { int index = table.getSelectedRow(); editRow(index, false); } } }); DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); renderer.setHorizontalAlignment(SwingConstants.CENTER); /* // This is BROKEN! table.setCellSelectionEnabled(true); for (int i=0;i<model.getColumnCount();i++) { TableColumn column = table.getColumn(model.getColumnName(i)); //log.info(model.getColumnName(i)); //column.setCellRenderer(renderer); ColumnInfo columnInfo = columnList.get(i); Component comp = columnInfo.getComp(); //column.setCellEditor(new DefaultCellEditor(new JTextField())); if (comp instanceof GetSetValueIFace) { column.setCellEditor(new MyTableCellEditor(columnInfo)); } else if (comp instanceof JTextField) { column.setCellEditor(new DefaultCellEditor((JTextField)comp)); } else { log.error("Couldn't figure out DefaultCellEditor for comp ["+comp.getClass().getSimpleName()+"]"); } } */ tableScroller = new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); orderablePanel = new JPanel(new BorderLayout()); orderablePanel.add(tableScroller, BorderLayout.CENTER); mainComp.add(orderablePanel, BorderLayout.CENTER); initColumnSizes(table); }
From source file:edu.ku.brc.specify.tasks.subpane.qb.QueryBldrPane.java
/** * create the query builder UI.// ww w . j av a 2 s . co m */ protected void createUI() { removeAll(); JMenuItem saveItem = new JMenuItem(UIRegistry.getResourceString("QB_SAVE")); Action saveActionListener = new AbstractAction() { public void actionPerformed(ActionEvent e) { if (saveQuery(false)) { try { String selId = null; if (selectedQFP != null && selectedQFP.getQueryField() != null) { selId = selectedQFP.getQueryField().getStringId(); } final String selectedFldId = selId; setupUI(true); SwingUtilities.invokeLater(new Runnable() { /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { if (selectedFldId != null) { for (QueryFieldPanel qfp : queryFieldItems) { if (qfp.getQueryField() != null && selectedFldId.equals(qfp.getQueryField().getStringId())) { selectQFP(qfp); return; } } selectQFP(queryFieldItems.get(0)); } } }); } catch (Exception ex) { } setSaveBtnEnabled(false); } } }; saveItem.addActionListener(saveActionListener); JMenuItem saveAsItem = new JMenuItem(UIRegistry.getResourceString("QB_SAVE_AS")); Action saveAsActionListener = new AbstractAction() { public void actionPerformed(ActionEvent e) { if (saveQuery(true)) { setSaveBtnEnabled(false); } } }; saveAsItem.addActionListener(saveAsActionListener); JComponent[] itemSample = { saveItem, saveAsItem }; saveBtn = new DropDownButton(UIRegistry.getResourceString("QB_SAVE"), null, 1, java.util.Arrays.asList(itemSample)); saveBtn.addActionListener(saveActionListener); String ACTION_KEY = "SAVE"; KeyStroke ctrlS = KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); InputMap inputMap = saveBtn.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(ctrlS, ACTION_KEY); ActionMap actionMap = saveBtn.getActionMap(); actionMap.put(ACTION_KEY, saveActionListener); ACTION_KEY = "SAVE_AS"; KeyStroke ctrlA = KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); inputMap.put(ctrlA, ACTION_KEY); actionMap.put(ACTION_KEY, saveAsActionListener); saveBtn.setActionMap(actionMap); UIHelper.setControlSize(saveBtn); //saveBtn.setOverrideBorder(true, BasicBorders.getButtonBorder()); listBoxPanel = new JPanel(new HorzLayoutManager(2, 2)); Vector<TableQRI> list = new Vector<TableQRI>(); for (int k = 0; k < tableTree.getKids(); k++) { list.add(tableTree.getKid(k).getTableQRI()); } Collections.sort(list); DefaultListModel model = new DefaultListModel(); for (TableQRI qri : list) { model.addElement(qri); } tableList = new JList(model); QryListRenderer qr = new QryListRenderer(IconManager.IconSize.Std16); qr.setDisplayKidIndicator(false); tableList.setCellRenderer(qr); JScrollPane spt = new JScrollPane(tableList, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); Dimension pSize = spt.getPreferredSize(); pSize.height = 200; spt.setPreferredSize(pSize); JPanel topPanel = new JPanel(new BorderLayout()); scrollPane = new JScrollPane(listBoxPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); tableList.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { int inx = tableList.getSelectedIndex(); if (inx > -1) { fillNextList(tableList); } else { listBoxPanel.removeAll(); } } } }); addBtn = new JButton(IconManager.getImage("PlusSign", IconManager.IconSize.Std16)); addBtn.setEnabled(false); addBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { BaseQRI qri = (BaseQRI) listBoxList.get(currentInx).getSelectedValue(); if (qri.isInUse) { return; } 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; } } }); contextPanel = new JPanel(new BorderLayout()); contextPanel.add(createLabel("Search Context", SwingConstants.CENTER), BorderLayout.NORTH); // I18N contextPanel.add(spt, BorderLayout.CENTER); contextPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10)); JPanel schemaPanel = new JPanel(new BorderLayout()); schemaPanel.add(scrollPane, BorderLayout.CENTER); topPanel.add(contextPanel, BorderLayout.WEST); topPanel.add(schemaPanel, BorderLayout.CENTER); add(topPanel, BorderLayout.NORTH); queryFieldsPanel = new JPanel(); queryFieldsPanel.setLayout(new NavBoxLayoutManager(0, 2)); queryFieldsScroll = new JScrollPane(queryFieldsPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); queryFieldsScroll.setBorder(null); add(queryFieldsScroll); //if (!isExportMapping) //{ final JPanel mover = buildMoverPanel(false); add(mover, BorderLayout.EAST); // } String searchLbl = schemaMapping == null ? getResourceString("QB_SEARCH") : getResourceString("QB_EXPORT_PREVIEW"); searchBtn = createButton(searchLbl); searchBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { // int m = ae.getModifiers(); // boolean ors = (m & ActionEvent.ALT_MASK) > 0 && (m & ActionEvent.CTRL_MASK) > 0 && (m & ActionEvent.SHIFT_MASK) > 0; // if (ors) // { // System.out.println("Disjunctional conjoinment desire gesture detected"); // } // doSearch(ors); doSearch(false); } }); distinctChk = createCheckBox(UIRegistry.getResourceString("QB_DISTINCT")); distinctChk.setVisible(schemaMapping == null); if (schemaMapping == null) { distinctChk.setSelected(false); distinctChk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { new SwingWorker() { /* (non-Javadoc) * @see edu.ku.brc.helpers.SwingWorker#construct() */ @Override public Object construct() { if (distinctChk.isSelected()) { UsageTracker.incrUsageCount("QB.DistinctOn"); } else { UsageTracker.incrUsageCount("QB.DistinctOff"); } if ((isTreeLevelSelected() || isAggFieldSelected()) && countOnly && distinctChk.isSelected()) { countOnlyChk.setSelected(false); countOnly = false; } query.setCountOnly(countOnly); query.setSelectDistinct(distinctChk.isSelected()); setSaveBtnEnabled(thereAreItems()); return null; } }.start(); } }); } countOnlyChk = createCheckBox(UIRegistry.getResourceString("QB_COUNT_ONLY")); countOnlyChk.setSelected(false); countOnlyChk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { new SwingWorker() { /* (non-Javadoc) * @see edu.ku.brc.helpers.SwingWorker#construct() */ @Override public Object construct() { //Don't allow change while query is running. if (runningResults.get() == null) { countOnly = !countOnly; if (countOnly) { UsageTracker.incrUsageCount("QB.CountOnlyOn"); } else { UsageTracker.incrUsageCount("QB.CountOnlyOff"); } if ((isTreeLevelSelected() || isAggFieldSelected()) && countOnly && (distinctChk.isSelected() || searchSynonymyChk.isSelected())) { distinctChk.setSelected(false); searchSynonymyChk.setSelected(false); } } else { //This might be awkward and/or klunky... countOnlyChk.setSelected(countOnly); } query.setCountOnly(countOnly); query.setSelectDistinct(distinctChk.isSelected()); setSaveBtnEnabled(thereAreItems()); return null; } }.start(); } }); searchSynonymyChk = createCheckBox(UIRegistry.getResourceString("QB_SRCH_SYNONYMS")); searchSynonymyChk.setSelected(searchSynonymy); searchSynonymyChk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { new SwingWorker() { /* (non-Javadoc) * @see edu.ku.brc.helpers.SwingWorker#construct() */ @Override public Object construct() { searchSynonymy = !searchSynonymy; if (!searchSynonymy) { UsageTracker.incrUsageCount("QB.SearchSynonymyOff"); } else { UsageTracker.incrUsageCount("QB.SearchSynonymyOn"); } if (isTreeLevelSelected() && countOnly && searchSynonymyChk.isSelected()) { countOnlyChk.setSelected(false); countOnly = false; } query.setSearchSynonymy(searchSynonymy); setSaveBtnEnabled(thereAreItems()); return null; } }.start(); } }); smushedChk = createCheckBox(UIRegistry.getResourceString("QB_SMUSH_RESULTS")); smushedChk.setVisible(isSmushableContext()); if (isSmushableContext()) { smushedChk.setSelected(smushed); smushedChk.setToolTipText( String.format(UIRegistry.getResourceString("QB_SMUSH_RESULTS_HINT"), getCatalogNumberTitle())); smushedChk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { new SwingWorker() { /* * (non-Javadoc) * * @see edu.ku.brc.helpers.SwingWorker#construct() */ @Override public Object construct() { smushed = !smushed; if (!smushed) { UsageTracker.incrUsageCount("QB.SmushedOff"); } else { UsageTracker.incrUsageCount("QB.SmushedOn"); } query.setSmushed(smushed); setSaveBtnEnabled(thereAreItems()); return null; } }.start(); } }); } PanelBuilder outer = new PanelBuilder( new FormLayout("p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 6dlu, p", "p")); CellConstraints cc = new CellConstraints(); outer.add(smushedChk, cc.xy(1, 1)); outer.add(searchSynonymyChk, cc.xy(3, 1)); outer.add(distinctChk, cc.xy(5, 1)); outer.add(countOnlyChk, cc.xy(7, 1)); outer.add(searchBtn, cc.xy(9, 1)); outer.add(saveBtn, cc.xy(11, 1)); JPanel bottom = new JPanel(new BorderLayout()); bottom.add(outer.getPanel(), BorderLayout.EAST); JButton helpBtn = UIHelper.createHelpIconButton(getHelpBtnContext()); bottom.add(helpBtn, BorderLayout.WEST); add(bottom, BorderLayout.SOUTH); setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); }
From source file:com.diversityarrays.kdxplore.specgroup.SpecimenGroupEditor.java
private JComponent createBottomComponent() { // =========/* ww w . j ava2 s .c o m*/ specimenTableModel = new SpecimenTableModel(null); specimenTableModel.addTableModelListener(new TableModelListener() { @Override public void tableChanged(TableModelEvent e) { exportSpecimenList.setEnabled(specimenTableModel.getRowCount() > 0); } }); specimenTable = new JTable(specimenTableModel); specimenTable.setAutoCreateRowSorter(true); specimenTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { deleteSpecimenFromList.setEnabled(specimenTable.getSelectedRowCount() > 0); } } }); // specimenTableModel.addTableModelListener(new TableModelListener() { // @Override // public void tableChanged(TableModelEvent e) { // fileDropTarget.setVisible(specimenTableModel.getRowCount() > 0); // } // }); CompoundBorder border = new CompoundBorder(new LineBorder(Color.DARK_GRAY), new EmptyBorder(4, 2, 4, 2)); fileDropTarget.setBorder(border); fileDropTarget.setBackground(Color.LIGHT_GRAY); // fileDropTarget.setVisible(false); deleteSpecimenFromList.setEnabled(false); TitledTablePanel specimenTablePanel = new TitledTablePanel("Specimen", specimenTable, "Download from database,\n Drag/drop Specimens or Drag/drop CSV File above"); // saveAction.setEnabled(false); // downloadSpecimenList.setEnabled(false); exportSpecimenList.setEnabled(false); Box otherBox = Box.createHorizontalBox(); otherBox.add(downloadSpecimensButton); otherBox.add(fileDropTarget); otherBox.add(Box.createHorizontalGlue()); otherBox.add(new JButton(exportSpecimenList)); otherBox.add(Box.createHorizontalGlue()); otherBox.add(new JLabel("(local)")); otherBox.add(new JButton(deleteSpecimenFromList)); JPanel containerPanel2 = new JPanel(new BorderLayout()); containerPanel2.add(otherBox, BorderLayout.NORTH); containerPanel2.add(specimenTablePanel, BorderLayout.CENTER); fileDropTarget.setTransferHandler(flth); // TableTransferHandler tth2 = TableTransferHandler.initialiseForCopySelectAll(specimenTable, true); // ChainingTransferHandler cth = new ChainingTransferHandler(flth, genotypeTransferHandler, tth2); TransferHandler cth = genotypeTransferHandler; // ChainingTH cth = new ChainingTH(genotypeTransferHandler, tth2); specimenTablePanel.scrollPane.setTransferHandler(cth); specimenTablePanel.setTransferHandler(cth); specimenTable.setTransferHandler(cth); specimenTable.setDragEnabled(true); return containerPanel2; }
From source file:com.pianobakery.complsa.MainGui.java
public MainGui() { $$$setupUI$$$();/* w ww . j a v a 2 s . c o m*/ runtimeParameters(); trainCorp = new HashMap<String, File>(); trainSentModels = new HashMap<String, File>(); indexFilesModel = new HashMap<String, File>(); searchCorpusModel = new HashMap<String, File>(); selDocdirContent = new ArrayList<File>(); langModelsText.setText("None"); posIndRadiusTextField.setEnabled(false); //Disable all Components as long as wDir is not set. enableUIElements(false); ButtonGroup selSearchGroup = new ButtonGroup(); selSearchGroup.add(searchSearchCorpRadioButton); selSearchGroup.add(searchTopCorpRadioButton); ButtonGroup searchSelGroup = new ButtonGroup(); searchSelGroup.add(selTextRadioButton); searchSelGroup.add(selDocRadioButton); //licenseKeyGUI = new LicenseKeyGUI(frame, true); //Added to get the docSearchTable the focus when opening the Reader without selecting something so up down button will work frame.addWindowFocusListener(new WindowAdapter() { public void windowGainedFocus(WindowEvent e) { docSearchResTable.requestFocusInWindow(); } }); frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke('S', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "CTRL + S"); frame.getRootPane().getActionMap().put("CTRL + S", runSearch()); frame.addWindowListener(new WindowAdapter() { public void windowOpened(WindowEvent evt) { formWindowOpened(evt); } }); //Needs to get a white background in the termtableview (only in windows) termTablePane.getViewport().setBackground(Color.WHITE); //Project Page //Project Folder newFolderButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { newFolderMethod(); } }); selectFolderButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { selectFolderMethod(); } }); //Download Language Models downloadModelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { downloadModelMethod(); } }); //Add-Remove Topic Corpus addTopicCorpusButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addTopicCorpusMethod(); } }); selectTrainCorp.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { frame.setTitle("Selected Training Corpus: " + selectTrainCorp.getSelectedItem() + " and " + "Sel. Search Corpus: " + searchCorpComboBox.getSelectedItem()); algTextField.setText("Knowledge Corpus: " + selectTrainCorp.getSelectedItem()); try { updateIndexFileFolder(); } catch (IOException e1) { e1.printStackTrace(); } } }); removeTopicCorpusButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) throws ArrayIndexOutOfBoundsException { removeTopicCorpusMethod(); } }); //Update and remove Index updateIndexButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateIndexMethod(); } }); removeIndexButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { removeIndexMethod(); } }); //Train Semantic trainCorpButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { trainCorpMethod(); } }); indexTypeComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (indexTypeComboBox.getSelectedIndex() == 2) { logger.debug("Enable indexType Combo with Index: " + indexTypeComboBox.getSelectedIndex()); posIndRadiusTextField.setEnabled(true); return; } logger.debug("Disable indexType Combo with Index: " + indexTypeComboBox.getSelectedIndex()); posIndRadiusTextField.setEnabled(false); } }); //Import and remove Search Corpora impSearchCorpButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { impSearchCorpMethod(); } }); searchCorpComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { frame.setTitle("Selected Training Corpus: " + selectTrainCorp.getSelectedItem() + " and " + "Sel. Search Corpus: " + searchCorpComboBox.getSelectedItem()); } }); removeSearchCorpButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) throws ArrayIndexOutOfBoundsException { removeSearchCorpMethod(); } }); //Search Page //Choose Index Type selectIndexTypeComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (searchModelList.isEmpty()) { return; } if (searchModelList.get(selectIndexTypeComboBox.getSelectedItem()) == null) { return; } List<String> theList = searchModelList.get(selectIndexTypeComboBox.getSelectedItem().toString()); selectTermweightComboBox.removeAllItems(); for (String aTFItem : theList) { selectTermweightComboBox.addItem(aTFItem); } getSelectedSearchModelFiles(); } }); selectTermweightComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (searchModelList.isEmpty()) { return; } if (searchModelList.get(selectIndexTypeComboBox.getSelectedItem()) == null) { return; } getSelectedSearchModelFiles(); } }); //Select Search Type selTextRadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { selectDocumentButton.setEnabled(false); searchTextArea.setEnabled(true); //searchDocValue.setText("nothing selected"); } }); selDocRadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { selectDocumentButton.setEnabled(true); searchTextArea.setText(null); searchTextArea.setEnabled(false); } }); selectDocumentButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { importSearchFile(); openSearchDocumentButton.setEnabled(true); } }); openSearchDocumentButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (searchDocReader == null) { searchDocReader = getReaderLater(null, maingui); searchDocReader.setSearchTerms(getSelectedTermTableWords()); } else if (!searchDocReader.getFrameVisible()) { searchDocReader.setFrameVisible(true); searchDocReader.setSearchTerms(getSelectedTermTableWords()); } searchDocReader.setDocumentText(searchFileString); searchDocReader.setSelFullDocLabel(searchDocValue.toString()); searchDocReader.setViewPane(2); searchDocReader.disableComponents(); searchDocReader.setSearchTerms(getSelectedTermTableWords()); } }); //Search Button searchButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { searchMethod(); } }); //Table Listeners docSearchResTable.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { JTable table = (JTable) me.getSource(); Point p = me.getPoint(); int row = docSearchResTable.rowAtPoint(p); if (docSearchResModel == null || docSearchResModel.getRowCount() == 0 || docSearchResModel.getDocFile(0).getFileName().equals(emptyTable)) { return; } switch (me.getClickCount()) { case 1: if (row == -1) { break; } if (docSearchResTable.getRowCount() > 0) { logger.debug("Single click Doc: " + ((DocSearchModel) docSearchResTable.getModel()) .getDocSearchFile(row).getFile().toString()); fillMetaDataField( ((DocSearchModel) docSearchResTable.getModel()).getDocSearchFile(row).getFile()); if (reader != null) { reader.setSearchTerms(getSelectedTermTableWords()); } if (searchDocReader != null) { searchDocReader.setSearchTerms(getSelectedTermTableWords()); } setSelReaderContent(); setDocReaderContent(0); if (reader != null) { reader.setSearchTerms(getSelectedTermTableWords()); } if (searchDocReader != null) { searchDocReader.setSearchTerms(getSelectedTermTableWords()); } } break; case 2: if (row == -1) { break; } if (docSearchResTable.getRowCount() > 0) { logger.debug("Double click Doc: " + ((DocSearchModel) docSearchResTable.getModel()) .getDocSearchFile(row).getFile().toString()); fillMetaDataField( ((DocSearchModel) docSearchResTable.getModel()).getDocSearchFile(row).getFile()); if (reader == null) { reader = getReaderLater((DocSearchModel) docSearchResTable.getModel(), maingui); reader.setSearchTerms(getSelectedTermTableWords()); } else if (!reader.getFrameVisible()) { reader.setFrameVisible(true); reader.setSearchTerms(getSelectedTermTableWords()); } setSelReaderContent(); setDocReaderContent(0); if (reader != null) { reader.setSearchTerms(getSelectedTermTableWords()); } if (searchDocReader != null) { searchDocReader.setSearchTerms(getSelectedTermTableWords()); } } break; } } }); termSearchResTable.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { JTable table = (JTable) me.getSource(); Point p = me.getPoint(); int row = docSearchResTable.rowAtPoint(p); if (termSearchResTable.getModel() == null || termSearchResTable.getRowCount() == 0 || termSearchResTable.getModel().getValueAt(row, 1).equals(emptyTable)) { return; } switch (me.getClickCount()) { case 1: logger.debug("Single click Term: " + termSearchResTable.getModel().getValueAt(row, 1)); logger.debug("Selected Terms: " + Arrays.toString(getSelectedTermTableWords())); if (reader != null) { reader.setSearchTerms(getSelectedTermTableWords()); } if (searchDocReader != null) { searchDocReader.setSearchTerms(getSelectedTermTableWords()); } break; case 2: logger.debug("Double click Term: " + termSearchResTable.getModel().getValueAt(row, 1)); if (reader != null) { reader.setSearchTerms(getSelectedTermTableWords()); } if (searchDocReader != null) { searchDocReader.setSearchTerms(getSelectedTermTableWords()); } break; } } }); docSearchResTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent event) { if (docSearchResModel == null || docSearchResModel.getRowCount() == 0 || docSearchResModel.getDocFile(0).getFileName().equals(emptyTable)) { return; } if (docSearchResTable.getSelectedRow() > -1) { // print first column value from selected row logger.debug("KeyboardSelection: " + ((DocSearchModel) docSearchResTable.getModel()) .getDocSearchFile( docSearchResTable.convertRowIndexToModel(docSearchResTable.getSelectedRow())) .getFile().toString()); fillMetaDataField(((DocSearchModel) docSearchResTable.getModel()) .getDocSearchFile( docSearchResTable.convertRowIndexToModel(docSearchResTable.getSelectedRow())) .getFile()); setSelReaderContent(); setDocReaderContent(0); if (reader != null) { reader.setSearchTerms(getSelectedTermTableWords()); } if (searchDocReader != null) { searchDocReader.setSearchTerms(getSelectedTermTableWords()); } } } }); termSearchResTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (termSearchResTable.getModel() == null || termSearchResTable.getRowCount() == 0 || termSearchResTable.getModel().getValueAt(0, 1).equals(emptyTable)) { return; } if (termSearchResTable.getSelectedRow() > -1) { // print first column value from selected row if (reader != null) { reader.setSearchTerms(getSelectedTermTableWords()); } if (searchDocReader != null) { searchDocReader.setSearchTerms(getSelectedTermTableWords()); } } } }); }
From source file:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java
/** * Constructs the pane for the spreadsheet. * /*from ww w . ja v a 2 s . c o m*/ * @param name the name of the pane * @param task the owning task * @param workbench the workbench to be edited * @param showImageView shows image window when first showing the window */ public WorkbenchPaneSS(final String name, final Taskable task, final Workbench workbenchArg, final boolean showImageView, final boolean isReadOnly) throws Exception { super(name, task); removeAll(); if (workbenchArg == null) { return; } this.workbench = workbenchArg; this.isReadOnly = isReadOnly; headers.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems()); Collections.sort(headers); boolean hasOneOrMoreImages = false; // pre load all the data for (WorkbenchRow wbRow : workbench.getWorkbenchRows()) { for (WorkbenchDataItem wbdi : wbRow.getWorkbenchDataItems()) { wbdi.getCellData(); } if (wbRow.getWorkbenchRowImages() != null && wbRow.getWorkbenchRowImages().size() > 0) { hasOneOrMoreImages = true; } } model = new GridTableModel(this); spreadSheet = new WorkbenchSpreadSheet(model, this); spreadSheet.setReadOnly(isReadOnly); model.setSpreadSheet(spreadSheet); Highlighter simpleStriping = HighlighterFactory.createSimpleStriping(); GridCellHighlighter hl = new GridCellHighlighter( new GridCellPredicate(GridCellPredicate.AnyPredicate, null)); Short[] errs = { WorkbenchDataItem.VAL_ERROR, WorkbenchDataItem.VAL_ERROR_EDIT }; ColorHighlighter errColorHighlighter = new ColorHighlighter( new GridCellPredicate(GridCellPredicate.ValidationPredicate, errs), CellRenderingAttributes.errorBackground, null); Short[] newdata = { WorkbenchDataItem.VAL_NEW_DATA }; ColorHighlighter noDataHighlighter = new ColorHighlighter( new GridCellPredicate(GridCellPredicate.MatchingPredicate, newdata), CellRenderingAttributes.newDataBackground, null); Short[] multimatch = { WorkbenchDataItem.VAL_MULTIPLE_MATCH }; ColorHighlighter multiMatchHighlighter = new ColorHighlighter( new GridCellPredicate(GridCellPredicate.MatchingPredicate, multimatch), CellRenderingAttributes.multipleMatchBackground, null); spreadSheet.setHighlighters(simpleStriping, hl, errColorHighlighter, noDataHighlighter, multiMatchHighlighter); //add key mappings for cut, copy, paste //XXX Note: these are shortcuts directly to the SpreadSheet cut,copy,paste methods, NOT to the Specify edit menu. addRecordKeyMappings(spreadSheet, KeyEvent.VK_C, "Copy", new AbstractAction() { public void actionPerformed(ActionEvent ae) { SwingUtilities.invokeLater(new Runnable() { /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { spreadSheet.cutOrCopy(false); } }); } }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); addRecordKeyMappings(spreadSheet, KeyEvent.VK_X, "Cut", new AbstractAction() { public void actionPerformed(ActionEvent ae) { SwingUtilities.invokeLater(new Runnable() { /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { spreadSheet.cutOrCopy(true); } }); } }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); addRecordKeyMappings(spreadSheet, KeyEvent.VK_V, "Paste", new AbstractAction() { public void actionPerformed(ActionEvent ae) { SwingUtilities.invokeLater(new Runnable() { /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { spreadSheet.paste(); } }); } }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); findPanel = spreadSheet.getFindReplacePanel(); UIRegistry.getLaunchFindReplaceAction().setSearchReplacePanel(findPanel); spreadSheet.setShowGrid(true); JTableHeader header = spreadSheet.getTableHeader(); header.addMouseListener(new ColumnHeaderListener()); header.setReorderingAllowed(false); // Turn Off column dragging // Put the model in image mode, and never change it. // Now we're showing/hiding the image column using JXTable's column hiding features. model.setInImageMode(true); int imageColIndex = model.getColumnCount() - 1; imageColExt = spreadSheet.getColumnExt(imageColIndex); imageColExt.setVisible(false); int sgrColIndex = model.getSgrHeading().getViewOrder(); sgrColExt = spreadSheet.getColumnExt(sgrColIndex); sgrColExt.setComparator(((WorkbenchSpreadSheet) spreadSheet).new NumericColumnComparator()); int cmpIdx = 0; for (Comparator<String> cmp : ((WorkbenchSpreadSheet) spreadSheet).getComparators()) { if (cmp != null) { spreadSheet.getColumnExt(cmpIdx++).setComparator(cmp); } } // Start off with the SGR score column hidden showHideSgrCol(false); model.addTableModelListener(new TableModelListener() { public void tableChanged(TableModelEvent e) { setChanged(true); } }); spreadSheet.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { UIRegistry.enableCutCopyPaste(true); UIRegistry.enableFind(findPanel, true); } @Override public void focusLost(FocusEvent e) { UIRegistry.enableCutCopyPaste(true); UIRegistry.enableFind(findPanel, true); } }); if (isReadOnly) { saveBtn = null; } else { saveBtn = createButton(getResourceString("SAVE")); saveBtn.setToolTipText( String.format(getResourceString("WB_SAVE_DATASET_TT"), new Object[] { workbench.getName() })); saveBtn.setEnabled(false); saveBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { UsageTracker.incrUsageCount("WB.SaveDataSet"); UIRegistry.writeSimpleGlassPaneMsg( String.format(getResourceString("WB_SAVING"), new Object[] { workbench.getName() }), WorkbenchTask.GLASSPANE_FONT_SIZE); UIRegistry.getStatusBar().setIndeterminate(workbench.getName(), true); final SwingWorker worker = new SwingWorker() { @SuppressWarnings("synthetic-access") @Override public Object construct() { try { saveObject(); } catch (Exception ex) { UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(WorkbenchPaneSS.class, ex); log.error(ex); return ex; } return null; } // Runs on the event-dispatching thread. @Override public void finished() { Object retVal = get(); if (retVal != null && retVal instanceof Exception) { Exception ex = (Exception) retVal; UIRegistry.getStatusBar().setErrorMessage(getResourceString("WB_ERROR_SAVING"), ex); } UIRegistry.clearSimpleGlassPaneMsg(); UIRegistry.getStatusBar().setProgressDone(workbench.getName()); } }; worker.start(); } }); } Action delAction = addRecordKeyMappings(spreadSheet, KeyEvent.VK_F3, "DelRow", new AbstractAction() { public void actionPerformed(ActionEvent ae) { if (validationWorkerQueue.peek() == null) { deleteRows(); } } }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); if (isReadOnly) { deleteRowsBtn = null; } else { deleteRowsBtn = createIconBtn("DelRec", "WB_DELETE_ROW", delAction); selectionSensitiveButtons.add(deleteRowsBtn); spreadSheet.setDeleteAction(delAction); } //XXX Using the wb ID in the prefname to do pref setting per wb, may result in a bloated prefs file?? doIncrementalValidation = AppPreferences.getLocalPrefs() .getBoolean(wbAutoValidatePrefName + "." + workbench.getId(), true); doIncrementalMatching = AppPreferences.getLocalPrefs() .getBoolean(wbAutoMatchPrefName + "." + workbench.getId(), false); if (isReadOnly) { clearCellsBtn = null; } else { clearCellsBtn = createIconBtn("Eraser", "WB_CLEAR_CELLS", new ActionListener() { public void actionPerformed(ActionEvent ae) { spreadSheet.clearSorter(); if (spreadSheet.getCellEditor() != null) { spreadSheet.getCellEditor().stopCellEditing(); } int[] rows = spreadSheet.getSelectedRowModelIndexes(); int[] cols = spreadSheet.getSelectedColumnModelIndexes(); model.clearCells(rows, cols); } }); selectionSensitiveButtons.add(clearCellsBtn); } Action addAction = addRecordKeyMappings(spreadSheet, KeyEvent.VK_N, "AddRow", new AbstractAction() { public void actionPerformed(ActionEvent ae) { if (workbench.getWorkbenchRows().size() < WorkbenchTask.MAX_ROWS) { if (validationWorkerQueue.peek() == null) { addRowAfter(); } } } }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); if (isReadOnly) { addRowsBtn = null; } else { addRowsBtn = createIconBtn("AddRec", "WB_ADD_ROW", addAction); addRowsBtn.setEnabled(true); addAction.setEnabled(true); } if (isReadOnly) { carryForwardBtn = null; } else { carryForwardBtn = createIconBtn("CarryForward20x20", IconManager.IconSize.NonStd, "WB_CARRYFORWARD", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { UsageTracker.getUsageCount("WBCarryForward"); configCarryFoward(); } }); carryForwardBtn.setEnabled(true); } toggleImageFrameBtn = createIconBtn("CardImage", IconManager.IconSize.NonStd, "WB_SHOW_IMG_WIN", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { toggleImageFrameVisible(); } }); toggleImageFrameBtn.setEnabled(true); importImagesBtn = createIconBtn("CardImage", IconManager.IconSize.NonStd, "WB_SHOW_IMG_WIN", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { toggleImportImageFrameVisible(); } }); importImagesBtn.setEnabled(true); /*showMapBtn = createIconBtn("ShowMap", IconManager.IconSize.NonStd, "WB_SHOW_MAP", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { showMapOfSelectedRecords(); } });*/ // enable or disable along with Google Earth and Geo Ref Convert buttons if (isReadOnly) { exportKmlBtn = null; } else { exportKmlBtn = createIconBtn("GoogleEarth", IconManager.IconSize.NonStd, "WB_SHOW_IN_GOOGLE_EARTH", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { SwingUtilities.invokeLater(new Runnable() { public void run() { showRecordsInGoogleEarth(); } }); } }); } // readRegisteries(); // enable or disable along with Show Map and Geo Ref Convert buttons if (isReadOnly) { geoRefToolBtn = null; } else { AppPreferences remotePrefs = AppPreferences.getRemote(); final String tool = remotePrefs.get("georef_tool", "geolocate"); String iconName = "GEOLocate20"; //tool.equalsIgnoreCase("geolocate") ? "GeoLocate" : "BioGeoMancer"; String toolTip = tool.equalsIgnoreCase("geolocate") ? "WB_DO_GEOLOCATE_LOOKUP" : "WB_DO_BIOGEOMANCER_LOOKUP"; geoRefToolBtn = createIconBtn(iconName, IconManager.IconSize.NonStd, toolTip, false, new ActionListener() { public void actionPerformed(ActionEvent ae) { spreadSheet.clearSorter(); if (tool.equalsIgnoreCase("geolocate")) { doGeoRef(new edu.ku.brc.services.geolocate.prototype.GeoCoordGeoLocateProvider(), "WB.GeoLocateRows"); } else { doGeoRef(new GeoCoordBGMProvider(), "WB.BioGeomancerRows"); } } }); // only enable it if the workbench has the proper columns in it String[] missingColumnsForBG = getMissingButRequiredColumnsForGeoRefTool(tool); if (missingColumnsForBG.length > 0) { geoRefToolBtn.setEnabled(false); String ttText = "<p>" + getResourceString("WB_ADDITIONAL_FIELDS_REQD") + ":<ul>"; for (String reqdField : missingColumnsForBG) { ttText += "<li>" + reqdField + "</li>"; } ttText += "</ul>"; String origTT = geoRefToolBtn.getToolTipText(); geoRefToolBtn.setToolTipText("<html>" + origTT + ttText); } else { geoRefToolBtn.setEnabled(true); } } if (isReadOnly) { convertGeoRefFormatBtn = null; } else { convertGeoRefFormatBtn = createIconBtn("ConvertGeoRef", IconManager.IconSize.NonStd, "WB_CONVERT_GEO_FORMAT", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { showGeoRefConvertDialog(); } }); // now enable/disable the geo ref related buttons String[] missingGeoRefFields = getMissingGeoRefLatLonFields(); if (missingGeoRefFields.length > 0) { convertGeoRefFormatBtn.setEnabled(false); exportKmlBtn.setEnabled(false); //showMapBtn.setEnabled(false); String ttText = "<p>" + getResourceString("WB_ADDITIONAL_FIELDS_REQD") + ":<ul>"; for (String reqdField : missingGeoRefFields) { ttText += "<li>" + reqdField + "</li>"; } ttText += "</ul>"; String origTT1 = convertGeoRefFormatBtn.getToolTipText(); convertGeoRefFormatBtn.setToolTipText("<html>" + origTT1 + ttText); String origTT2 = exportKmlBtn.getToolTipText(); exportKmlBtn.setToolTipText("<html>" + origTT2 + ttText); //String origTT3 = showMapBtn.getToolTipText(); //showMapBtn.setToolTipText("<html>" + origTT3 + ttText); } else { convertGeoRefFormatBtn.setEnabled(true); exportKmlBtn.setEnabled(true); //showMapBtn.setEnabled(true); } } if (AppContextMgr.isSecurityOn() && !task.getPermissions().canModify()) { exportExcelCsvBtn = null; } else { exportExcelCsvBtn = createIconBtn("Export", IconManager.IconSize.NonStd, "WB_EXPORT_DATA", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { doExcelCsvExport(); } }); exportExcelCsvBtn.setEnabled(true); } uploadDatasetBtn = createIconBtn("Upload", IconManager.IconSize.Std24, "WB_UPLOAD_DATA", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { doDatasetUpload(); } }); uploadDatasetBtn.setVisible(isUploadPermitted() && !UIRegistry.isMobile()); uploadDatasetBtn.setEnabled(canUpload()); if (!uploadDatasetBtn.isEnabled()) { uploadDatasetBtn.setToolTipText(getResourceString("WB_UPLOAD_IN_PROGRESS")); } // listen to selection changes to enable/disable certain buttons spreadSheet.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { JStatusBar statusBar = UIRegistry.getStatusBar(); statusBar.setText(""); currentRow = spreadSheet.getSelectedRow(); updateBtnUI(); } } }); for (int c = 0; c < spreadSheet.getTableHeader().getColumnModel().getColumnCount(); c++) { // TableColumn column = // spreadSheet.getTableHeader().getColumnModel().getColumn(spreadSheet.getTableHeader().getColumnModel().getColumnCount()-1); TableColumn column = spreadSheet.getTableHeader().getColumnModel().getColumn(c); column.setCellRenderer(new WbCellRenderer()); } // setup the JFrame to show images attached to WorkbenchRows imageFrame = new ImageFrame(mapSize, this, this.workbench, task, isReadOnly); // setup the JFrame to show images attached to WorkbenchRows imageImportFrame = new ImageImportFrame(this, this.workbench); setupWorkbenchRowChangeListener(); // setup window minimizing/maximizing listener JFrame topFrame = (JFrame) UIRegistry.getTopWindow(); minMaxWindowListener = new WindowAdapter() { @Override public void windowDeiconified(WindowEvent e) { if (imageFrame != null && imageFrame.isVisible()) { imageFrame.setExtendedState(Frame.NORMAL); } if (mapFrame != null && mapFrame.isVisible()) { mapFrame.setExtendedState(Frame.NORMAL); } } @Override public void windowIconified(WindowEvent e) { if (imageFrame != null && imageFrame.isVisible()) { imageFrame.setExtendedState(Frame.ICONIFIED); } if (mapFrame != null && mapFrame.isVisible()) { mapFrame.setExtendedState(Frame.ICONIFIED); } } }; topFrame.addWindowListener(minMaxWindowListener); if (!isReadOnly) { showHideUploadToolBtn = createIconBtn("ValidateWB", IconManager.IconSize.NonStd, "WB_HIDE_UPLOADTOOLPANEL", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { if (uploadToolPanel.isExpanded()) { hideUploadToolPanel(); showHideUploadToolBtn.setToolTipText(getResourceString("WB_SHOW_UPLOADTOOLPANEL")); } else { showUploadToolPanel(); showHideUploadToolBtn.setToolTipText(getResourceString("WB_HIDE_UPLOADTOOLPANEL")); } } }); showHideUploadToolBtn.setEnabled(true); } // setup the mapping features mapFrame = new JFrame(); mapFrame.setIconImage(IconManager.getImage("AppIcon").getImage()); mapFrame.setTitle(getResourceString("WB_GEO_REF_DATA_MAP")); mapImageLabel = createLabel(""); mapImageLabel.setSize(500, 500); mapFrame.add(mapImageLabel); mapFrame.setSize(500, 500); // start putting together the visible UI CellConstraints cc = new CellConstraints(); JComponent[] compsArray = { addRowsBtn, deleteRowsBtn, clearCellsBtn, /*showMapBtn,*/ exportKmlBtn, geoRefToolBtn, convertGeoRefFormatBtn, exportExcelCsvBtn, uploadDatasetBtn, showHideUploadToolBtn }; Vector<JComponent> availableComps = new Vector<JComponent>( compsArray.length + workBenchPluginSSBtns.size()); for (JComponent c : compsArray) { if (c != null) { availableComps.add(c); } } for (JComponent c : workBenchPluginSSBtns) { availableComps.add(c); } PanelBuilder spreadSheetControlBar = new PanelBuilder(new FormLayout( "f:p:g,4px," + createDuplicateJGoodiesDef("p", "4px", availableComps.size()) + ",4px,", "c:p:g")); int x = 3; for (JComponent c : availableComps) { spreadSheetControlBar.add(c, cc.xy(x, 1)); x += 2; } int h = 0; Vector<WorkbenchTemplateMappingItem> headers = new Vector<WorkbenchTemplateMappingItem>(); headers.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems()); Collections.sort(headers); for (WorkbenchTemplateMappingItem mi : headers) { //using the workbench data model table. Not the actual specify table the column is mapped to. //This MIGHT be less confusing //System.out.println("setting header renderer for " + mi.getTableName() + "." + mi.getFieldName()); spreadSheet.getColumnModel().getColumn(h++) .setHeaderRenderer(new WbTableHeaderRenderer(mi.getTableName())); } // NOTE: This needs to be done after the creation of the saveBtn. And after the creation of the header renderes. initColumnSizes(spreadSheet, saveBtn); // Create the Form Pane -- needs to be done after initColumnSizes - which also sets cell editors for collumns if (task instanceof SGRTask) { formPane = new SGRFormPane(this, workbench, isReadOnly); } else { formPane = new FormPane(this, workbench, isReadOnly); } // This panel contains just the ResultSetContoller, it's needed so the RSC gets centered PanelBuilder rsPanel = new PanelBuilder(new FormLayout("c:p:g", "c:p:g")); FormValidator dummy = new FormValidator(null); dummy.setEnabled(true); resultsetController = new ResultSetController(dummy, !isReadOnly, !isReadOnly, false, getResourceString("Record"), model.getRowCount(), true); resultsetController.addListener(formPane); if (!isReadOnly) { resultsetController.getDelRecBtn().addActionListener(delAction); } // else // { // resultsetController.getDelRecBtn().setVisible(false); // } rsPanel.add(resultsetController.getPanel(), cc.xy(1, 1)); // This panel is a single row containing the ResultSetContoller and the other controls for the Form Panel String colspec = "f:p:g, p, f:p:g, p"; for (int i = 0; i < workBenchPluginFormBtns.size(); i++) { colspec = colspec + ", f:p, p"; } PanelBuilder resultSetPanel = new PanelBuilder(new FormLayout(colspec, "c:p:g")); // Now put the two panel into the single row panel resultSetPanel.add(rsPanel.getPanel(), cc.xy(2, 1)); if (!isReadOnly) { resultSetPanel.add(formPane.getControlPropsBtn(), cc.xy(4, 1)); } int ccx = 6; for (JComponent c : workBenchPluginFormBtns) { resultSetPanel.add(c, cc.xy(ccx, 1)); ccx += 2; } // Create the main panel that uses card layout for the form and spreasheet mainPanel = new JPanel(cardLayout = new CardLayout()); // Add the Form and Spreadsheet to the CardLayout mainPanel.add(spreadSheet.getScrollPane(), PanelType.Spreadsheet.toString()); mainPanel.add(formPane.getPane(), PanelType.Form.toString()); // The controllerPane is a CardLayout that switches between the Spreadsheet control bar and the Form Control Bar controllerPane = new JPanel(cpCardLayout = new CardLayout()); controllerPane.add(spreadSheetControlBar.getPanel(), PanelType.Spreadsheet.toString()); controllerPane.add(resultSetPanel.getPanel(), PanelType.Form.toString()); JLabel sep1 = new JLabel(IconManager.getIcon("Separator")); JLabel sep2 = new JLabel(IconManager.getIcon("Separator")); ssFormSwitcher = createSwitcher(); // This works setLayout(new BorderLayout()); boolean doDnDImages = AppPreferences.getLocalPrefs().getBoolean("WB_DND_IMAGES", false); JComponent[] ctrlCompArray1 = { importImagesBtn, toggleImageFrameBtn, carryForwardBtn, sep1, saveBtn, sep2, ssFormSwitcher }; JComponent[] ctrlCompArray2 = { toggleImageFrameBtn, carryForwardBtn, sep1, saveBtn, sep2, ssFormSwitcher }; JComponent[] ctrlCompArray = doDnDImages ? ctrlCompArray1 : ctrlCompArray2; Vector<Pair<JComponent, Integer>> ctrlComps = new Vector<Pair<JComponent, Integer>>(); for (JComponent c : ctrlCompArray) { ctrlComps.add(new Pair<JComponent, Integer>(c, null)); } String layoutStr = ""; int compCount = 0; int col = 1; int pos = 0; for (Pair<JComponent, Integer> c : ctrlComps) { JComponent comp = c.getFirst(); if (comp != null) { boolean addComp = !(comp == sep1 || comp == sep2) || compCount > 0; if (!addComp) { c.setFirst(null); } else { if (!StringUtils.isEmpty(layoutStr)) { layoutStr += ","; col++; if (pos < ctrlComps.size() - 1) { //this works because we know ssFormSwitcher is last and always non-null. layoutStr += "6px,"; col++; } } c.setSecond(col); if (comp == sep1 || comp == sep2) { layoutStr += "6px"; compCount = 0; } else { layoutStr += "p"; compCount++; } } } pos++; } PanelBuilder ctrlBtns = new PanelBuilder(new FormLayout(layoutStr, "c:p:g")); for (Pair<JComponent, Integer> c : ctrlComps) { if (c.getFirst() != null) { ctrlBtns.add(c.getFirst(), cc.xy(c.getSecond(), 1)); } } add(mainPanel, BorderLayout.CENTER); FormLayout formLayout = new FormLayout("f:p:g,4px,p", "2px,f:p:g,p:g,p:g"); PanelBuilder builder = new PanelBuilder(formLayout); builder.add(controllerPane, cc.xy(1, 2)); builder.add(ctrlBtns.getPanel(), cc.xy(3, 2)); if (!isReadOnly) { uploadToolPanel = new UploadToolPanel(this, UploadToolPanel.EXPANDED); uploadToolPanel.createUI(); // showHideUploadToolBtn = createIconBtn("ValidateWB", IconManager.IconSize.NonStd, "WB_HIDE_UPLOADTOOLPANEL", false, new ActionListener() // { // public void actionPerformed(ActionEvent ae) // { // if (uploadToolPanel.isExpanded()) // { // hideUploadToolPanel(); // showHideUploadToolBtn.setToolTipText(getResourceString("WB_SHOW_UPLOADTOOLPANEL")); // } else // { // showUploadToolPanel(); // showHideUploadToolBtn.setToolTipText(getResourceString("WB_HIDE_UPLOADTOOLPANEL")); // } // } // }); // showHideUploadToolBtn.setEnabled(true); } builder.add(uploadToolPanel, cc.xywh(1, 3, 3, 1)); builder.add(findPanel, cc.xywh(1, 4, 3, 1)); add(builder.getPanel(), BorderLayout.SOUTH); resultsetController.addListener(new ResultSetControllerListener() { public boolean indexAboutToChange(int oldIndex, int newIndex) { return true; } public void indexChanged(int newIndex) { if (imageFrame != null) { if (newIndex > -1) { int index = spreadSheet.convertRowIndexToModel(newIndex); imageFrame.setRow(workbench.getRow(index)); } else { imageFrame.setRow(null); } } } public void newRecordAdded() { // do nothing } }); //compareSchemas(); if (getIncremental() && workbenchValidator == null) { buildValidator(); } // int c = 0; // Vector<WorkbenchTemplateMappingItem> headers = new Vector<WorkbenchTemplateMappingItem>(); // headers.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems()); // Collections.sort(headers); // for (WorkbenchTemplateMappingItem mi : headers) // { // //using the workbench data model table. Not the actual specify table the column is mapped to. // //This MIGHT be less confusing // //System.out.println("setting header renderer for " + mi.getTableName() + "." + mi.getFieldName()); // spreadSheet.getColumnModel().getColumn(c++).setHeaderRenderer(new WbTableHeaderRenderer(mi.getTableName())); // } // // // NOTE: This needs to be done after the creation of the saveBtn. And after the creation of the header renderes. // initColumnSizes(spreadSheet, saveBtn); // See if we need to make the Image Frame visible // Commenting this out for now because it is so annoying. if (showImageView || hasOneOrMoreImages) { SwingUtilities.invokeLater(new Runnable() { public void run() { toggleImageFrameVisible(); SwingUtilities.invokeLater(new Runnable() { public void run() { final Frame f = (Frame) UIRegistry.get(UIRegistry.FRAME); f.toFront(); f.requestFocus(); } }); } }); } ((WorkbenchTask) ContextMgr.getTaskByClass(WorkbenchTask.class)).opening(this); ((SGRTask) ContextMgr.getTaskByClass(SGRTask.class)).opening(this); }
From source file:edu.ku.brc.af.ui.db.TextFieldWithQuery.java
/** * * @param advanceFocus/* ww w.j av a 2 s. c o m*/ */ protected void showDialog(final int advanceFocus) { final Vector<Integer> idListLocal = (Vector<Integer>) idList.clone(); final Vector<String> listLocal = (Vector<String>) list.clone(); final String enteredText = StringUtils.isEmpty(prevEnteredText) ? cachedPrevText : prevEnteredText; DefaultListModel<String> model = new DefaultListModel<String>(); if (doAddAddItem) { model.addElement(UIRegistry.getResourceString("TFWQ_ADD_LABEL")); //$NON-NLS-1$ } for (String val : list) { model.addElement(val); } final JList<String> listBox = new JList<String>(model); JPanel panel = new JPanel(new BorderLayout()); panel.add(createLabel(UIRegistry.getResourceString("TFWQ_CHOOSE_LABEL"), SwingConstants.CENTER), //$NON-NLS-1$ BorderLayout.NORTH); panel.add(UIHelper.createScrollPane(listBox, true), BorderLayout.CENTER); panel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); // Had to do inner class in order to get it to select an item // before being shown class PopUpDialog extends CustomDialog { protected JList<String> pListBox; public PopUpDialog(final Frame frame, final boolean isModal, final Component contentPanel, JList<String> pListBoxArg) throws HeadlessException { super(frame, UIRegistry.getResourceString("TFWQ_CHOOSE_TITLE"), isModal, contentPanel); //$NON-NLS-1$ this.pListBox = pListBoxArg; initialize(); } public PopUpDialog(final Dialog dialog, final boolean isModal, final Component contentPanel, JList<String> pListBoxArg) throws HeadlessException { super(dialog, UIRegistry.getResourceString("TFWQ_CHOOSE_TITLE"), isModal, OK_BTN | CANCEL_BTN, //$NON-NLS-1$ contentPanel); this.pListBox = pListBoxArg; initialize(); } /** * */ protected void initialize() { pListBox.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (okBtn != null && pListBox != null) { okBtn.setEnabled(listBox.getSelectedIndex() != -1); } } } }); pListBox.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); if (e.getClickCount() == 2) { okBtn.setEnabled(true); okBtn.doClick(); } } }); } @Override public void setVisible(final boolean visible) { if (visible) { listBox.setSelectedIndex(doAddAddItem ? 1 : 0); } super.setVisible(visible); } } hasNewText = false; Window mostRecent = UIRegistry.getMostRecentWindow(); CustomDialog dlg; if (mostRecent instanceof Dialog) { dlg = new PopUpDialog((Dialog) UIRegistry.getMostRecentWindow(), true, panel, listBox); } else { dlg = new PopUpDialog((Frame) UIRegistry.getMostRecentWindow(), true, panel, listBox); } dlg.setVisible(true); if (!dlg.isCancelled()) { int inx = listBox.getSelectedIndex(); boolean isDoingAdd = inx == 0 && doAddAddItem; inx = doAddAddItem ? inx - 1 : inx; if (!isDoingAdd && inx < idListLocal.size()) { selectedId = idListLocal.get(inx); setText(listLocal.get(inx)); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { transferFocus(advanceFocus); notifyListenersOfChange(isDoingAdd ? new AddItemEvent(enteredText) : listBox); } }); } else { setText(""); //$NON-NLS-1$ } }
From source file:eu.apenet.dpt.standalone.gui.DataPreparationToolGUI.java
private void wireUp() { fileItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { if (actionEvent.getSource() == fileItem) { currentLocation = new File(retrieveFromDb.retrieveOpenLocation()); fileChooser.setCurrentDirectory(currentLocation); int returnedVal = fileChooser.showOpenDialog(getParent()); if (returnedVal == JFileChooser.APPROVE_OPTION) { currentLocation = fileChooser.getCurrentDirectory(); retrieveFromDb.saveOpenLocation(currentLocation.getAbsolutePath()); RootPaneContainer root = (RootPaneContainer) getRootPane().getTopLevelAncestor(); root.getGlassPane().setCursor(WAIT_CURSOR); root.getGlassPane().setVisible(true); File[] files = fileChooser.getSelectedFiles(); for (File file : files) { if (file.isDirectory()) { File[] fileArray = file.listFiles(); Arrays.sort(fileArray, new FileNameComparator()); for (File children : fileArray) { if (isCorrect(children)) { xmlEadListModel.addFile(children); }//from w w w.j av a2s .c om } } else { if (isCorrect(file)) { xmlEadListModel.addFile(file); } } } root.getGlassPane().setCursor(DEFAULT_CURSOR); root.getGlassPane().setVisible(false); } } } }); repositoryCodeItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createOptionPaneForRepositoryCode(); } }); countryCodeItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createOptionPaneForCountryCode(); } }); checksLoadingFilesItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { createOptionPaneForChecksLoadingFiles(); } }); createEag2012FromExistingEag2012.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser eagFileChooser = new JFileChooser(); eagFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); eagFileChooser.setMultiSelectionEnabled(false); eagFileChooser.setCurrentDirectory(new File(retrieveFromDb.retrieveOpenLocation())); if (eagFileChooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) { currentLocation = eagFileChooser.getCurrentDirectory(); retrieveFromDb.saveOpenLocation(currentLocation.getAbsolutePath()); File eagFile = eagFileChooser.getSelectedFile(); if (!Eag2012Frame.isUsed()) { try { if (ReadXml.isXmlFile(eagFile, "eag")) { new Eag2012Frame(eagFile, getContentPane().getSize(), (ProfileListModel) getXmlEadList().getModel(), labels); } else { JOptionPane.showMessageDialog(rootPane, labels.getString("eag2012.errors.notAnEagFile")); } } catch (SAXException ex) { if (ex instanceof SAXParseException) { JOptionPane.showMessageDialog(rootPane, labels.getString("eag2012.errors.notAnEagFile")); } java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (IOException ex) { java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (Exception ex) { try { JOptionPane.showMessageDialog(rootPane, labels.getString(ex.getMessage())); } catch (Exception ex1) { JOptionPane.showMessageDialog(rootPane, "Error..."); } } } } } }); createEag2012FromScratch.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!Eag2012Frame.isUsed()) { new Eag2012Frame(getContentPane().getSize(), (ProfileListModel) getXmlEadList().getModel(), labels, retrieveFromDb.retrieveCountryCode(), retrieveFromDb.retrieveRepositoryCode()); } } }); digitalObjectTypeItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!DigitalObjectAndRightsOptionFrame.isInUse()) { JFrame DigitalObjectAndRightsOptionFrame = new DigitalObjectAndRightsOptionFrame(labels, retrieveFromDb); DigitalObjectAndRightsOptionFrame.setPreferredSize(new Dimension( getContentPane().getWidth() * 3 / 8, getContentPane().getHeight() * 3 / 4)); DigitalObjectAndRightsOptionFrame.setLocation(getContentPane().getWidth() / 8, getContentPane().getHeight() / 8); DigitalObjectAndRightsOptionFrame.pack(); DigitalObjectAndRightsOptionFrame.setVisible(true); } } }); defaultSaveFolderItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { JFileChooser defaultSaveFolderChooser = new JFileChooser(); defaultSaveFolderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); defaultSaveFolderChooser.setMultiSelectionEnabled(false); defaultSaveFolderChooser.setCurrentDirectory(new File(retrieveFromDb.retrieveDefaultSaveFolder())); if (defaultSaveFolderChooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) { File directory = defaultSaveFolderChooser.getSelectedFile(); if (directory.canWrite() && DirectoryPermission.canWrite(directory)) { retrieveFromDb.saveDefaultSaveFolder(directory + "/"); } else { createErrorOrWarningPanel(new Exception(labels.getString("error.directory.nowrites")), false, labels.getString("error.directory.nowrites"), getContentPane()); } } } }); listDateConversionRulesItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { JDialog dateConversionRulesDialog = new DateConversionRulesDialog(labels, retrieveFromDb); dateConversionRulesDialog.setPreferredSize( new Dimension(getContentPane().getWidth() * 3 / 8, getContentPane().getHeight() * 7 / 8)); dateConversionRulesDialog.setLocation(getContentPane().getWidth() / 8, getContentPane().getHeight() / 8); dateConversionRulesDialog.pack(); dateConversionRulesDialog.setVisible(true); } }); edmGeneralOptionsItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!EdmGeneralOptionsFrame.isInUse()) { JFrame edmGeneralOptionsFrame = new EdmGeneralOptionsFrame(labels, retrieveFromDb); edmGeneralOptionsFrame.setPreferredSize(new Dimension(getContentPane().getWidth() * 3 / 8, getContentPane().getHeight() * 3 / 8)); edmGeneralOptionsFrame.setLocation(getContentPane().getWidth() / 8, getContentPane().getHeight() / 8); edmGeneralOptionsFrame.pack(); edmGeneralOptionsFrame.setVisible(true); } } }); closeSelectedItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { xmlEadListModel.removeFiles(xmlEadList.getSelectedValues()); } }); saveSelectedItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String defaultOutputDirectory = retrieveFromDb.retrieveDefaultSaveFolder(); boolean isMultipleFiles = xmlEadList.getSelectedIndices().length > 1; RootPaneContainer root = (RootPaneContainer) getRootPane().getTopLevelAncestor(); root.getGlassPane().setCursor(WAIT_CURSOR); root.getGlassPane().setVisible(true); for (Object selectedValue : xmlEadList.getSelectedValues()) { File selectedFile = (File) selectedValue; String filename = selectedFile.getName(); FileInstance fileInstance = fileInstances.get(filename); String filePrefix = fileInstance.getFileType().getFilePrefix(); //todo: do we really need this? filename = filename.startsWith("temp_") ? filename.replace("temp_", "") : filename; filename = !filename.endsWith(".xml") ? filename + ".xml" : filename; if (!fileInstance.isValid()) { filePrefix = "NOT_" + filePrefix; } if (fileInstance.getLastOperation().equals(FileInstance.Operation.EDIT_TREE)) { TreeTableModel treeTableModel = tree.getTreeTableModel(); Document document = (Document) treeTableModel.getRoot(); try { File file2 = new File(defaultOutputDirectory + filePrefix + "_" + filename); File filetemp = new File(Utilities.TEMP_DIR + "temp_" + filename); TransformerFactory tf = TransformerFactory.newInstance(); Transformer output = tf.newTransformer(); output.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes"); output.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource domSource = new DOMSource(document.getFirstChild()); output.transform(domSource, new StreamResult(filetemp)); output.transform(domSource, new StreamResult(file2)); fileInstance.setLastOperation(FileInstance.Operation.SAVE); fileInstance.setCurrentLocation(filetemp.getAbsolutePath()); } catch (Exception ex) { createErrorOrWarningPanel(ex, true, labels.getString("errorSavingTreeXML"), getContentPane()); } } else if (fileInstance.isConverted()) { try { File newFile = new File(defaultOutputDirectory + filePrefix + "_" + filename); FileUtils.copyFile(new File(fileInstance.getCurrentLocation()), newFile); fileInstance.setLastOperation(FileInstance.Operation.SAVE); // fileInstance.setCurrentLocation(newFile.getAbsolutePath()); } catch (IOException ioe) { LOG.error("Error when saving file", ioe); } } else { try { File newFile = new File(defaultOutputDirectory + filePrefix + "_" + filename); FileUtils.copyFile(selectedFile, newFile); fileInstance.setLastOperation(FileInstance.Operation.SAVE); // fileInstance.setCurrentLocation(newFile.getAbsolutePath()); } catch (IOException ioe) { LOG.error("Error when saving file", ioe); } } } root.getGlassPane().setCursor(DEFAULT_CURSOR); root.getGlassPane().setVisible(false); if (isMultipleFiles) { JOptionPane.showMessageDialog(getContentPane(), MessageFormat.format(labels.getString("filesInOutput"), defaultOutputDirectory) + ".", labels.getString("fileSaved"), JOptionPane.INFORMATION_MESSAGE, Utilities.icon); } else { JOptionPane.showMessageDialog(getContentPane(), MessageFormat.format(labels.getString("fileInOutput"), defaultOutputDirectory) + ".", labels.getString("fileSaved"), JOptionPane.INFORMATION_MESSAGE, Utilities.icon); } xmlEadList.updateUI(); } }); saveMessageReportItem.addActionListener( new MessageReportActionListener(retrieveFromDb, this, fileInstances, labels, this)); sendFilesWebDAV.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { throw new UnsupportedOperationException("Not supported yet."); } }); quitItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); xsltItem.addActionListener(new XsltAdderActionListener(this, labels)); xsdItem.addActionListener(new XsdAdderActionListener(this, labels, retrieveFromDb)); if (Utilities.isDev) { databaseItem.addActionListener(new DatabaseCheckerActionListener(retrieveFromDb, getContentPane())); } xmlEadList.addMouseListener(new ListMouseAdapter(xmlEadList, xmlEadListModel, deleteFileItem, this)); xmlEadList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (xmlEadList.getSelectedValues() != null && xmlEadList.getSelectedValues().length != 0) { if (xmlEadList.getSelectedValues().length > 1) { // convertAndValidateBtn.setEnabled(true); // validateSelectionBtn.setEnabled(true); // if (isValidated(xmlEadList)) { // convertEdmSelectionBtn.setEnabled(true); // } else { // convertEdmSelectionBtn.setEnabled(false); // } // disableAllBtnAndItems(); saveMessageReportItem.setEnabled(true); changeInfoInGUI(""); } else { // convertAndValidateBtn.setEnabled(false); // validateSelectionBtn.setEnabled(false); // convertEdmSelectionBtn.setEnabled(false); changeInfoInGUI(((File) xmlEadList.getSelectedValue()).getName()); if (apePanel.getApeTabbedPane().getSelectedIndex() == APETabbedPane.TAB_EDITION) { apePanel.getApeTabbedPane() .createEditionTree(((File) xmlEadList.getSelectedValue())); if (tree != null) { FileInstance fileInstance = fileInstances .get(((File) getXmlEadList().getSelectedValue()).getName()); tree.addMouseListener(new PopupMouseListener(tree, getDataPreparationToolGUI(), getContentPane(), fileInstance)); } } disableTabFlashing(); } checkHoldingsGuideButton(); } else { // convertAndValidateBtn.setEnabled(false); // validateSelectionBtn.setEnabled(false); // convertEdmSelectionBtn.setEnabled(false); createHGBtn.setEnabled(false); analyzeControlaccessBtn.setEnabled(false); changeInfoInGUI(""); } } } private boolean isValidated(JList xmlEadList) { for (Object selectedValue : xmlEadList.getSelectedValues()) { File selectedFile = (File) selectedValue; String filename = selectedFile.getName(); FileInstance fileInstance = fileInstances.get(filename); if (!fileInstance.isValid()) { return false; } } return true; } }); summaryWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_SUMMARY)); validationWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_VALIDATION)); conversionWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_CONVERSION)); edmConversionWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_EDM)); editionWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_EDITION)); internetApexItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { BareBonesBrowserLaunch.openURL("http://www.apex-project.eu/"); } }); /** * Option Edit apeEAC-CPF file in the menu */ this.editEacCpfFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser eacFileChooser = new JFileChooser(); eacFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); eacFileChooser.setMultiSelectionEnabled(false); eacFileChooser.setCurrentDirectory(new File(retrieveFromDb.retrieveOpenLocation())); if (eacFileChooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) { currentLocation = eacFileChooser.getCurrentDirectory(); retrieveFromDb.saveOpenLocation(currentLocation.getAbsolutePath()); File eacFile = eacFileChooser.getSelectedFile(); if (!EacCpfFrame.isUsed()) { try { if (ReadXml.isXmlFile(eacFile, "eac-cpf")) { new EacCpfFrame(eacFile, true, getContentPane().getSize(), (ProfileListModel) getXmlEadList().getModel(), labels); } else { JOptionPane.showMessageDialog(rootPane, labels.getString("eaccpf.error.notAnEacCpfFile")); } } catch (SAXException ex) { if (ex instanceof SAXParseException) { JOptionPane.showMessageDialog(rootPane, labels.getString("eaccpf.error.notAnEacCpfFile")); } java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (IOException ex) { java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (Exception ex) { try { JOptionPane.showMessageDialog(rootPane, labels.getString(ex.getMessage())); } catch (Exception ex1) { JOptionPane.showMessageDialog(rootPane, "Error..."); } } } } } }); /** * Option Create apeEAC-CPF in the menu */ this.createEacCpf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!EacCpfFrame.isUsed()) { EacCpfFrame eacCpfFrame = new EacCpfFrame(getContentPane().getSize(), (ProfileListModel) getXmlEadList().getModel(), labels, retrieveFromDb.retrieveCountryCode(), retrieveFromDb.retrieveRepositoryCode(), null, null, null); } } }); }
From source file:org.jas.gui.MainWindow.java
public JTable getDescriptionTable() { if (descriptionTable == null) { descriptionTable = new DescriptionTable(); descriptionTable.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { MetadataDialog metadataDialog = new MetadataDialog(MainWindow.this, controlEngineConfigurator, "Alter ALL rows"); metadataDialog.setVisible(true); }/* w ww. j av a2s . c o m*/ } }); descriptionTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (tableLoaded) { selectedRow = descriptionTable.getSelectedRow(); log.info("SETTING SELECTED ROW to : " + selectedRow); updateImage(selectedRow); } } }); descriptionTable.getModel().addTableModelListener(new TableModelListener() { public void tableChanged(TableModelEvent e) { if (e.getType() == TableModelEvent.UPDATE && tableLoaded && e.getColumn() != ApplicationState.STATUS_COLUMN) { int column = e.getColumn(); int row = e.getFirstRow(); String value = getDescriptionTable().getModel().getValueAt(row, column).toString(); log.info("value changed: " + value); List<Metadata> metadataList = viewEngineConfigurator.getViewEngine().get(Model.METADATA); Metadata metadata = metadataList.get(row); metadataAdapter.update(metadata, column, value); metadataWithAlbum.add(metadata); getDescriptionTable().getModel().setValueAt(ActionResult.New, row, ApplicationState.STATUS_COLUMN); controlEngineConfigurator.getControlEngine().set(Model.METADATA_ARTIST, metadataWithAlbum, null); getApplyButton().setEnabled(!working); log.info("setting applyButton to : " + !working); } } }); } return descriptionTable; }