List of usage examples for javax.swing.event TableModelListener TableModelListener
TableModelListener
From source file:blue.soundObject.tracker.TrackList.java
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject();/*from w w w . j av a 2 s.c om*/ columnChangeListener = new TableModelListener() { public void tableChanged(TableModelEvent e) { TableModelEvent tme = new TableModelEvent(TrackList.this, TableModelEvent.HEADER_ROW); fireTableModelEvent(tme); } }; for (Iterator it = tracks.iterator(); it.hasNext();) { Track t = (Track) it.next(); t.addTableModelListener(columnChangeListener); } }
From source file:com.diversityarrays.kdxplore.curate.SampleEntryPanel.java
SampleEntryPanel(CurationData cd, IntFunction<Trait> traitProvider, TypedSampleMeasurementTableModel tsm, JTable table, TsmCellRenderer tsmCellRenderer, JToggleButton showPpiOption, Closure<Void> refreshFieldLayoutView, BiConsumer<Comparable<?>, List<CurationCellValue>> showChangedValue, SampleType[] sampleTypes) { this.curationData = cd; this.traitProvider = traitProvider; this.typedSampleTableModel = tsm; this.typedSampleTable = table; this.showPpiOption = showPpiOption; this.initialTableRowHeight = typedSampleTable.getRowHeight(); this.tsmCellRenderer = tsmCellRenderer; this.refreshFieldLayoutView = refreshFieldLayoutView; this.showChangedValue = showChangedValue; List<SampleType> list = new ArrayList<>(); list.add(NO_SAMPLE_TYPE);//from w w w.j a va 2s. com for (SampleType st : sampleTypes) { list.add(st); sampleTypeById.put(st.getTypeId(), st); } sampleTypeCombo = new JComboBox<SampleType>(list.toArray(new SampleType[list.size()])); typedSampleTableModel.addTableModelListener(new TableModelListener() { @Override public void tableChanged(TableModelEvent e) { if (TableModelEvent.HEADER_ROW == e.getFirstRow()) { typedSampleTable.setAutoCreateColumnsFromModel(true); everSetData = false; } } }); showStatsAction.putValue(Action.SHORT_DESCRIPTION, Vocab.TOOLTIP_STATS_FOR_KDSMART_SAMPLES()); showStatsOption.setFont(showStatsOption.getFont().deriveFont(Font.BOLD)); showStatsOption.setPreferredSize(new Dimension(30, 30)); JLabel helpPanel = new JLabel(); helpPanel.setHorizontalAlignment(JLabel.CENTER); String html = "<HTML>Either enter a value or select<br>a <i>Source</i> for <b>Value From:</b>"; if (shouldShowSampleType(sampleTypes)) { html += "<BR>You may also select a <i>Sample Type</i> if it is relevant."; } helpPanel.setText(html); singleOrMultiCardPanel.add(helpPanel, CARD_SINGLE); singleOrMultiCardPanel.add(applyToPanel, CARD_MULTI); // singleOrMultiCardPanel.add(multiCellControlsPanel, CARD_MULTI); validationMessage.setBorder(new LineBorder(Color.LIGHT_GRAY)); validationMessage.setForeground(Color.RED); validationMessage.setBackground(new JLabel().getBackground()); validationMessage.setHorizontalAlignment(SwingConstants.CENTER); // validationMessage.setEditable(false); Box setButtons = Box.createHorizontalBox(); setButtons.add(new JButton(deleteAction)); setButtons.add(new JButton(notApplicableAction)); setButtons.add(new JButton(missingAction)); setButtons.add(new JButton(setValueAction)); deleteAction.putValue(Action.SHORT_DESCRIPTION, Vocab.TOOLTIP_SET_UNSET()); notApplicableAction.putValue(Action.SHORT_DESCRIPTION, Vocab.TOOLTIP_SET_NA()); missingAction.putValue(Action.SHORT_DESCRIPTION, Vocab.TOOLTIP_SET_MISSING()); setValueAction.putValue(Action.SHORT_DESCRIPTION, Vocab.TOOLTIP_SET_VALUE()); Box sampleType = Box.createHorizontalBox(); sampleType.add(new JLabel(Vocab.LABEL_SAMPLE_TYPE())); sampleType.add(sampleTypeCombo); statisticsControls = generateStatControls(); setBorder(new TitledBorder(new LineBorder(Color.GREEN.darker().darker()), "Sample Entry Panel")); GBH gbh = new GBH(this); int y = 0; gbh.add(0, y, 2, 1, GBH.HORZ, 1, 1, GBH.CENTER, statisticsControls); ++y; if (shouldShowSampleType(sampleTypes)) { sampleType.setBorder(new LineBorder(Color.RED)); sampleType.setToolTipText("DEVELOPER MODE: sampleType is possible hack for accept/suppress"); gbh.add(0, y, 2, 1, GBH.HORZ, 1, 1, GBH.CENTER, sampleType); ++y; } sampleSourceControls = Box.createHorizontalBox(); sampleSourceControls.add(new JLabel(Vocab.PROMPT_VALUES_FROM())); // sampleSourceControls.add(new JSeparator(JSeparator.VERTICAL)); sampleSourceControls.add(sampleSourceComboBox); sampleSourceControls.add(Box.createHorizontalGlue()); sampleSourceComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateSetValueAction(); } }); gbh.add(0, y, 2, 1, GBH.HORZ, 1, 1, GBH.CENTER, sampleSourceControls); ++y; gbh.add(0, y, 2, 1, GBH.HORZ, 1, 1, GBH.CENTER, valueDescription); ++y; gbh.add(0, y, 1, 1, GBH.NONE, 1, 1, GBH.WEST, showStatsOption); gbh.add(1, y, 1, 1, GBH.HORZ, 2, 1, GBH.CENTER, sampleValueTextField); ++y; gbh.add(0, y, 2, 1, GBH.NONE, 1, 1, GBH.CENTER, setButtons); ++y; gbh.add(0, y, 2, 1, GBH.HORZ, 2, 1, GBH.CENTER, validationMessage); ++y; gbh.add(0, y, 2, 1, GBH.HORZ, 2, 0, GBH.CENTER, singleOrMultiCardPanel); ++y; deleteAction.setEnabled(false); sampleSourceControls.setVisible(false); sampleValueTextField.setGrayWhenDisabled(true); sampleValueTextField.addActionListener(enterKeyListener); sampleValueTextField.getDocument().addDocumentListener(new DocumentListener() { @Override public void removeUpdate(DocumentEvent e) { updateSetValueAction(); } @Override public void insertUpdate(DocumentEvent e) { updateSetValueAction(); } @Override public void changedUpdate(DocumentEvent e) { updateSetValueAction(); } }); setValueAction.setEnabled(false); }
From source file:com.diversityarrays.kdxplore.trials.TrialSelectionDialog.java
public TrialSelectionDialog(Window owner, String title, DALClient c, List<Trial> kdxTrials, Transformer<BackgroundRunner, TrialSearchOptionsPanel> searchOptionsPanelFactory) { super(owner, title, USE_TRIALS); setGlassPane(backgroundRunner.getBlockingPane()); searchOptionsPanel = searchOptionsPanelFactory.transform(backgroundRunner); helpInstructions = new JLabel(searchOptionsPanel.getHtmlHelp(GET_TRIALS)); kdxTrialByIdDownloaded = kdxTrials.stream().filter(t -> t.getIdDownloaded() != null) .collect(Collectors.toMap(Trial::getIdDownloaded, java.util.function.Function.identity())); trialRecordTable.setName(this.getClass().getName() + ".trialRecordTable"); //$NON-NLS-1$ TableColumnModel tcm = trialRecordTable.getColumnModel(); TableCellRenderer cellRenderer = new OptionalCheckboxRenderer("Already downloaded"); tcm.getColumn(trialRecordTableModel.getChosenColumnIndex()).setCellRenderer(cellRenderer); for (int col = tcm.getColumnCount(); --col >= 0;) { if ("TrialName".equals(trialRecordTable.getColumnName(col))) { TableColumn tc = tcm.getColumn(col); tc.setCellRenderer(new TrialNameCellRenderer()); break; }//from w ww . j a va 2 s. co m } findTrialRecords.setEnabled(false); searchOptionsPanel.addSearchOptionsChangeListener(searchOptionsListener); wantTrialUnits.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { filteringClauseUsed = null; handleSearchOptionsChoiceChanged(); } }); setDALClient(c); initialiseGui(); if (owner != null) { Dimension ownerSize = owner.getSize(); Dimension mySize = getSize(); int w = (ownerSize.width * 3) / 4; int h = (ownerSize.height * 3) / 4; if (w > mySize.width || h > mySize.height) { if (w > mySize.width) { mySize.width = w; } if (h > mySize.height) { mySize.height = h; } setSize(mySize); } } // TODO consider using setSize to increase to parent's width getOkAction().setEnabled(false); trialRecordTableModel.addTableModelListener(new TableModelListener() { @Override public void tableChanged(TableModelEvent e) { getOkAction().setEnabled(trialRecordTableModel.getAnyChosen()); } }); }
From source file:com.qspin.qtaste.ui.xmleditor.TestRequirementEditor.java
private void genUI() { getActionMap().put("Save", new SaveAction()); getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK), "Save"); m_TestRequirementTable = new JTable() { @Override/* w w w. j a va 2 s . c om*/ public String getToolTipText(MouseEvent e) { Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); if (colIndex < 0) { return null; } return convertObjectToToolTip(getValueAt(rowIndex, colIndex)); } // overwrite cell content when typing on a selected cell @Override public Component prepareEditor(TableCellEditor editor, int row, int column) { Component c = super.prepareEditor(editor, row, column); if (c instanceof JTextComponent) { ((JTextField) c).selectAll(); } return c; } // select entire rows when selecting first column (row id) @Override public void columnSelectionChanged(ListSelectionEvent e) { if (e.getFirstIndex() == 0 && e.getValueIsAdjusting()) { setColumnSelectionInterval(1, getColumnCount() - 1); } else { super.columnSelectionChanged(e); } } }; m_TestRequirementTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); m_TestRequirementModel = new TestRequirementTableModel(); m_TestRequirementTable.setModel(m_TestRequirementModel); m_TableColumnModelListener = new MyTableColumnModelListener(); m_TestRequirementTable.setSurrendersFocusOnKeystroke(true); m_TestRequirementTable.setColumnSelectionAllowed(true); m_TestRequirementTable.addMouseListener(new TableMouseListener(m_TestRequirementTable)); m_TestRequirementTable.getTableHeader().addMouseListener(new TableMouseListener(m_TestRequirementTable)); m_TestRequirementTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); m_TestRequirementTable.getActionMap().put("Save", new SaveAction()); m_TestRequirementTable.setDefaultEditor(String.class, new TestDataTableCellEditor()); m_TestRequirementTable.setDefaultEditor(Integer.class, new TestDataTableCellEditor()); m_TestRequirementTable.getTableHeader().getInputMap() .put(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK), "Save"); m_TestRequirementTable.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK), "Save"); m_TestRequirementTable.setRowHeight(ROW_HEIGHT); m_TestRequirementTable.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { // if (e.getKeyCode() == KeyEvent.VK_UP) { // check if previous line is empty } if (e.getKeyCode() == KeyEvent.VK_DOWN) { // if current row is the last one if (m_TestRequirementTable.getSelectedRow() == m_TestRequirementTable.getRowCount() - 1) { addNewRow(); } } if ((e.getKeyCode() == KeyEvent.VK_S) && (e.isControlDown())) { save(); } if ((e.getKeyCode() == KeyEvent.VK_C) && (e.isControlDown())) { copySelectionToClipboard(); } if ((e.getKeyCode() == KeyEvent.VK_V) && (e.isControlDown())) { if (m_TestRequirementTable.getSelectedColumn() != 0) { pasteSelectionFromClipboard(); } } } }); tableListener = new TableModelListener() { public void tableChanged(TableModelEvent e) { // build the test data if (e.getType() == TableModelEvent.UPDATE) { if (e.getFirstRow() >= 0) { setModified(true); } } } }; m_TestRequirementModel.addTableModelListener(tableListener); JScrollPane sp = new JScrollPane(m_TestRequirementTable); sp.addMouseListener(new TableMouseListener(null)); add(sp); }
From source file:com.vgi.mafscaling.MafCompare.java
/** * Initialize the contents of the frame. *///ww w . j a v a 2s . c om private void initialize() { try { ImageIcon tableImage = new ImageIcon(getClass().getResource("/table.jpg")); setTitle(Title); setIconImage(tableImage.getImage()); setBounds(100, 100, 621, 372); setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); setSize(Config.getCompWindowSize()); setLocation(Config.getCompWindowLocation()); setLocationRelativeTo(null); setVisible(false); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Utils.clearTable(origMafTable); Utils.clearTable(newMafTable); Utils.clearTable(compMafTable); Config.setCompWindowSize(getSize()); Config.setCompWindowLocation(getLocation()); origMafData.clear(); newMafData.clear(); } }); JPanel dataPanel = new JPanel(); GridBagLayout gbl_dataPanel = new GridBagLayout(); gbl_dataPanel.columnWidths = new int[] { 0, 0, 0 }; gbl_dataPanel.rowHeights = new int[] { RowHeight, RowHeight, RowHeight, RowHeight, RowHeight, 0 }; gbl_dataPanel.columnWeights = new double[] { 0.0, 0.0, 0.0 }; gbl_dataPanel.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }; dataPanel.setLayout(gbl_dataPanel); getContentPane().add(dataPanel); JLabel origLabel = new JLabel(origMaf); GridBagConstraints gbc_origLabel = new GridBagConstraints(); gbc_origLabel.anchor = GridBagConstraints.PAGE_START; gbc_origLabel.insets = new Insets(1, 1, 1, 5); gbc_origLabel.weightx = 0; gbc_origLabel.weighty = 0; gbc_origLabel.gridx = 0; gbc_origLabel.gridy = 0; gbc_origLabel.gridheight = 2; dataPanel.add(origLabel, gbc_origLabel); JLabel newLabel = new JLabel(newMaf); GridBagConstraints gbc_newLabel = new GridBagConstraints(); gbc_newLabel.anchor = GridBagConstraints.PAGE_START; gbc_newLabel.insets = new Insets(1, 1, 1, 5); gbc_newLabel.weightx = 0; gbc_newLabel.weighty = 0; gbc_newLabel.gridx = 0; gbc_newLabel.gridy = 2; gbc_newLabel.gridheight = 2; dataPanel.add(newLabel, gbc_newLabel); JLabel compLabel = new JLabel("Change"); GridBagConstraints gbc_compLabel = new GridBagConstraints(); gbc_compLabel.anchor = GridBagConstraints.PAGE_START; gbc_compLabel.insets = new Insets(1, 1, 1, 5); gbc_compLabel.weightx = 0; gbc_compLabel.weighty = 0; gbc_compLabel.gridx = 0; gbc_compLabel.gridy = 4; dataPanel.add(compLabel, gbc_compLabel); JLabel origVoltLabel = new JLabel("volt"); GridBagConstraints gbc_origVoltLabel = new GridBagConstraints(); gbc_origVoltLabel.anchor = GridBagConstraints.PAGE_START; gbc_origVoltLabel.insets = new Insets(1, 1, 1, 5); gbc_origVoltLabel.weightx = 0; gbc_origVoltLabel.weighty = 0; gbc_origVoltLabel.gridx = 1; gbc_origVoltLabel.gridy = 0; dataPanel.add(origVoltLabel, gbc_origVoltLabel); JLabel origGsLabel = new JLabel(" g/s"); GridBagConstraints gbc_origGsLabel = new GridBagConstraints(); gbc_origGsLabel.anchor = GridBagConstraints.PAGE_START; gbc_origGsLabel.insets = new Insets(1, 1, 1, 5); gbc_origGsLabel.weightx = 0; gbc_origGsLabel.weighty = 0; gbc_origGsLabel.gridx = 1; gbc_origGsLabel.gridy = 1; dataPanel.add(origGsLabel, gbc_origGsLabel); JLabel newVoltLabel = new JLabel("volt"); GridBagConstraints gbc_newVoltLabel = new GridBagConstraints(); gbc_newVoltLabel.anchor = GridBagConstraints.PAGE_START; gbc_newVoltLabel.insets = new Insets(1, 1, 1, 5); gbc_newVoltLabel.weightx = 0; gbc_newVoltLabel.weighty = 0; gbc_newVoltLabel.gridx = 1; gbc_newVoltLabel.gridy = 2; dataPanel.add(newVoltLabel, gbc_newVoltLabel); JLabel newGsLabel = new JLabel(" g/s"); GridBagConstraints gbc_newGsLabel = new GridBagConstraints(); gbc_newGsLabel.anchor = GridBagConstraints.PAGE_START; gbc_newGsLabel.insets = new Insets(1, 1, 1, 5); gbc_newGsLabel.weightx = 0; gbc_newGsLabel.weighty = 0; gbc_newGsLabel.gridx = 1; gbc_newGsLabel.gridy = 3; dataPanel.add(newGsLabel, gbc_newGsLabel); JLabel compPctLabel = new JLabel(" % "); GridBagConstraints gbc_compPctLabel = new GridBagConstraints(); gbc_compPctLabel.anchor = GridBagConstraints.PAGE_START; gbc_compPctLabel.insets = new Insets(1, 1, 1, 5); gbc_compPctLabel.weightx = 0; gbc_compPctLabel.weighty = 0; gbc_compPctLabel.gridx = 1; gbc_compPctLabel.gridy = 4; dataPanel.add(compPctLabel, gbc_compPctLabel); JPanel tablesPanel = new JPanel(); GridBagLayout gbl_tablesPanel = new GridBagLayout(); gbl_tablesPanel.columnWidths = new int[] { 0 }; gbl_tablesPanel.rowHeights = new int[] { 0, 0, 0 }; gbl_tablesPanel.columnWeights = new double[] { 0.0 }; gbl_tablesPanel.rowWeights = new double[] { 0.0, 0.0, 1.0 }; tablesPanel.setLayout(gbl_tablesPanel); JScrollPane mafScrollPane = new JScrollPane(tablesPanel); mafScrollPane.setMinimumSize(new Dimension(1600, 107)); mafScrollPane.getHorizontalScrollBar().setMaximumSize(new Dimension(20, 20)); mafScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); mafScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); GridBagConstraints gbc_mafScrollPane = new GridBagConstraints(); gbc_mafScrollPane.weightx = 1.0; gbc_mafScrollPane.anchor = GridBagConstraints.PAGE_START; gbc_mafScrollPane.fill = GridBagConstraints.HORIZONTAL; gbc_mafScrollPane.gridx = 2; gbc_mafScrollPane.gridy = 0; gbc_mafScrollPane.gridheight = 5; dataPanel.add(mafScrollPane, gbc_mafScrollPane); origMafTable = new JTable(); origMafTable.setColumnSelectionAllowed(true); origMafTable.setCellSelectionEnabled(true); origMafTable.setBorder(new LineBorder(new Color(0, 0, 0))); origMafTable.setRowHeight(RowHeight); origMafTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); origMafTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); origMafTable.setModel(new DefaultTableModel(2, MafTableColumnCount)); origMafTable.setTableHeader(null); Utils.initializeTable(origMafTable, ColumnWidth); GridBagConstraints gbc_origMafTable = new GridBagConstraints(); gbc_origMafTable.anchor = GridBagConstraints.PAGE_START; gbc_origMafTable.insets = new Insets(0, 0, 0, 0); gbc_origMafTable.fill = GridBagConstraints.HORIZONTAL; gbc_origMafTable.weightx = 1.0; gbc_origMafTable.weighty = 0; gbc_origMafTable.gridx = 0; gbc_origMafTable.gridy = 0; tablesPanel.add(origMafTable, gbc_origMafTable); excelAdapter.addTable(origMafTable, false, false, false, false, true, false, true, false, true); newMafTable = new JTable(); newMafTable.setColumnSelectionAllowed(true); newMafTable.setCellSelectionEnabled(true); newMafTable.setBorder(new LineBorder(new Color(0, 0, 0))); newMafTable.setRowHeight(RowHeight); newMafTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); newMafTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); newMafTable.setModel(new DefaultTableModel(2, MafTableColumnCount)); newMafTable.setTableHeader(null); Utils.initializeTable(newMafTable, ColumnWidth); GridBagConstraints gbc_newMafTable = new GridBagConstraints(); gbc_newMafTable.anchor = GridBagConstraints.PAGE_START; gbc_newMafTable.insets = new Insets(0, 0, 0, 0); gbc_newMafTable.fill = GridBagConstraints.HORIZONTAL; gbc_newMafTable.weightx = 1.0; gbc_newMafTable.weighty = 0; gbc_newMafTable.gridx = 0; gbc_newMafTable.gridy = 1; tablesPanel.add(newMafTable, gbc_newMafTable); excelAdapter.addTable(newMafTable, false, false, false, false, false, false, false, false, true); compMafTable = new JTable(); compMafTable.setColumnSelectionAllowed(true); compMafTable.setCellSelectionEnabled(true); compMafTable.setBorder(new LineBorder(new Color(0, 0, 0))); compMafTable.setRowHeight(RowHeight); compMafTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); compMafTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); compMafTable.setModel(new DefaultTableModel(1, MafTableColumnCount)); compMafTable.setTableHeader(null); Utils.initializeTable(compMafTable, ColumnWidth); NumberFormatRenderer numericRenderer = new NumberFormatRenderer(); numericRenderer.setFormatter(new DecimalFormat("0.000")); compMafTable.setDefaultRenderer(Object.class, numericRenderer); GridBagConstraints gbc_compMafTable = new GridBagConstraints(); gbc_compMafTable.anchor = GridBagConstraints.PAGE_START; gbc_compMafTable.insets = new Insets(0, 0, 0, 0); gbc_compMafTable.fill = GridBagConstraints.HORIZONTAL; gbc_compMafTable.weightx = 1.0; gbc_compMafTable.weighty = 0; gbc_compMafTable.gridx = 0; gbc_compMafTable.gridy = 2; tablesPanel.add(compMafTable, gbc_compMafTable); compExcelAdapter.addTable(compMafTable, false, true, false, false, false, true, true, false, true); TableModelListener origTableListener = new TableModelListener() { public void tableChanged(TableModelEvent tme) { if (tme.getType() == TableModelEvent.UPDATE) { int colCount = origMafTable.getColumnCount(); Utils.ensureColumnCount(colCount, newMafTable); Utils.ensureColumnCount(colCount, compMafTable); origMafData.clear(); String origY, origX, newY; for (int i = 0; i < colCount; ++i) { origY = origMafTable.getValueAt(1, i).toString(); if (Pattern.matches(Utils.fpRegex, origY)) { origX = origMafTable.getValueAt(0, i).toString(); if (Pattern.matches(Utils.fpRegex, origX)) origMafData.add(Double.valueOf(origX), Double.valueOf(origY), false); newY = newMafTable.getValueAt(1, i).toString(); if (Pattern.matches(Utils.fpRegex, newY)) compMafTable.setValueAt( ((Double.valueOf(newY) / Double.valueOf(origY)) - 1.0) * 100.0, 0, i); } else break; } origMafData.fireSeriesChanged(); } } }; TableModelListener newTableListener = new TableModelListener() { public void tableChanged(TableModelEvent tme) { if (tme.getType() == TableModelEvent.UPDATE) { int colCount = newMafTable.getColumnCount(); Utils.ensureColumnCount(colCount, origMafTable); Utils.ensureColumnCount(colCount, compMafTable); newMafData.clear(); String newY, newX, origY; for (int i = 0; i < colCount; ++i) { newY = newMafTable.getValueAt(1, i).toString(); if (Pattern.matches(Utils.fpRegex, newY)) { newX = newMafTable.getValueAt(0, i).toString(); if (Pattern.matches(Utils.fpRegex, newX)) newMafData.add(Double.valueOf(newX), Double.valueOf(newY), false); origY = origMafTable.getValueAt(1, i).toString(); if (Pattern.matches(Utils.fpRegex, origY)) compMafTable.setValueAt( ((Double.valueOf(newY) / Double.valueOf(origY)) - 1.0) * 100.0, 0, i); } else break; } newMafData.fireSeriesChanged(); } } }; origMafTable.getModel().addTableModelListener(origTableListener); newMafTable.getModel().addTableModelListener(newTableListener); Action action = new AbstractAction() { private static final long serialVersionUID = 8148393537657380215L; public void actionPerformed(ActionEvent e) { TableCellListener tcl = (TableCellListener) e.getSource(); if (Pattern.matches(Utils.fpRegex, compMafTable.getValueAt(0, tcl.getColumn()).toString())) { if (Pattern.matches(Utils.fpRegex, origMafTable.getValueAt(1, tcl.getColumn()).toString())) { double corr = Double.valueOf(compMafTable.getValueAt(0, tcl.getColumn()).toString()) / 100.0 + 1.0; newMafTable.setValueAt( Double.valueOf(origMafTable.getValueAt(1, tcl.getColumn()).toString()) * corr, 1, tcl.getColumn()); } } else compMafTable.setValueAt(tcl.getOldValue(), 0, tcl.getColumn()); } }; setCompMafCellListener(new TableCellListener(compMafTable, action)); // CHART JFreeChart chart = ChartFactory.createXYLineChart(null, null, null, null, PlotOrientation.VERTICAL, false, true, false); chart.setBorderVisible(true); chartPanel = new ChartPanel(chart, true, true, true, true, true); chartPanel.setAutoscrolls(true); GridBagConstraints gbl_chartPanel = new GridBagConstraints(); gbl_chartPanel.anchor = GridBagConstraints.PAGE_START; gbl_chartPanel.fill = GridBagConstraints.BOTH; gbl_chartPanel.insets = new Insets(1, 1, 1, 1); gbl_chartPanel.weightx = 1.0; gbl_chartPanel.weighty = 1.0; gbl_chartPanel.gridx = 0; gbl_chartPanel.gridy = 5; gbl_chartPanel.gridheight = 1; gbl_chartPanel.gridwidth = 3; dataPanel.add(chartPanel, gbl_chartPanel); XYSplineRenderer lineRenderer = new XYSplineRenderer(3); lineRenderer.setUseFillPaint(true); lineRenderer.setBaseToolTipGenerator( new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT, new DecimalFormat("0.00"), new DecimalFormat("0.00"))); Stroke stroke = new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, null, 0.0f); lineRenderer.setSeriesStroke(0, stroke); lineRenderer.setSeriesStroke(1, stroke); lineRenderer.setSeriesPaint(0, new Color(201, 0, 0)); lineRenderer.setSeriesPaint(1, new Color(0, 0, 255)); lineRenderer.setSeriesShape(0, ShapeUtilities.createDiamond((float) 2.5)); lineRenderer.setSeriesShape(1, ShapeUtilities.createDownTriangle((float) 2.5)); lineRenderer.setLegendItemLabelGenerator(new StandardXYSeriesLabelGenerator() { private static final long serialVersionUID = -4045338273187150888L; public String generateLabel(XYDataset dataset, int series) { XYSeries xys = ((XYSeriesCollection) dataset).getSeries(series); return xys.getDescription(); } }); NumberAxis mafvDomain = new NumberAxis(XAxisName); mafvDomain.setAutoRangeIncludesZero(false); mafvDomain.setAutoRange(true); mafvDomain.setAutoRangeStickyZero(false); NumberAxis mafgsRange = new NumberAxis(YAxisName); mafgsRange.setAutoRangeIncludesZero(false); mafgsRange.setAutoRange(true); mafgsRange.setAutoRangeStickyZero(false); XYSeriesCollection lineDataset = new XYSeriesCollection(); origMafData.setDescription(origMaf); newMafData.setDescription(newMaf); lineDataset.addSeries(origMafData); lineDataset.addSeries(newMafData); XYPlot plot = chart.getXYPlot(); plot.setRangePannable(true); plot.setDomainPannable(true); plot.setDomainGridlinePaint(Color.DARK_GRAY); plot.setRangeGridlinePaint(Color.DARK_GRAY); plot.setBackgroundPaint(new Color(224, 224, 224)); plot.setDataset(0, lineDataset); plot.setRenderer(0, lineRenderer); plot.setDomainAxis(0, mafvDomain); plot.setRangeAxis(0, mafgsRange); plot.mapDatasetToDomainAxis(0, 0); plot.mapDatasetToRangeAxis(0, 0); LegendTitle legend = new LegendTitle(plot.getRenderer()); legend.setItemFont(new Font("Arial", 0, 10)); legend.setPosition(RectangleEdge.TOP); chart.addLegend(legend); } catch (Exception e) { logger.error(e); } }
From source file:com.mirth.connect.client.ui.codetemplate.CodeTemplateImportDialog.java
private void initComponents() { setBackground(UIConstants.BACKGROUND_COLOR); getContentPane().setBackground(getBackground()); topPanel = new JPanel(); topPanel.setBackground(getBackground()); linkPanel = new JPanel(); linkPanel.setBackground(topPanel.getBackground()); linkLeftPanel = new JPanel(); linkLeftPanel.setBackground(linkPanel.getBackground()); linkLeftSelectAllLabel = new JLabel("<html><u>All</u></html>"); linkLeftSelectAllLabel.setForeground(Color.BLUE); linkLeftSelectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR)); linkLeftSelectAllLabel.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent evt) { for (int row = 0; row < importTreeTable.getRowCount(); row++) { importTreeTable.getModel().setValueAt(true, row, IMPORT_SELECTED_COLUMN); }//from ww w . jav a 2s . c o m } }); linkLeftDeselectAllLabel = new JLabel("<html><u>None</u></html>"); linkLeftDeselectAllLabel.setForeground(Color.BLUE); linkLeftDeselectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR)); linkLeftDeselectAllLabel.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent evt) { for (int row = 0; row < importTreeTable.getRowCount(); row++) { importTreeTable.getModel().setValueAt(false, row, IMPORT_SELECTED_COLUMN); } } }); linkRightPanel = new JPanel(); linkRightPanel.setBackground(linkPanel.getBackground()); linkRightOverwriteAllLabel = new JLabel("<html><u>All</u></html>"); linkRightOverwriteAllLabel.setForeground(Color.BLUE); linkRightOverwriteAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR)); linkRightOverwriteAllLabel.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent evt) { for (int row = 0; row < importTreeTable.getRowCount(); row++) { TreePath path = importTreeTable.getPathForRow(row); if (path != null) { ImportTreeTableNode node = (ImportTreeTableNode) path.getLastPathComponent(); if (node instanceof ImportLibraryTreeTableNode) { ImportLibraryTreeTableNode libraryNode = (ImportLibraryTreeTableNode) node; if (libraryNode.getConflicts().getMatchingLibrary() != null) { importTreeTable.getModel().setValueAt(true, row, IMPORT_OVERWRITE_COLUMN); } } else if (node instanceof ImportCodeTemplateTreeTableNode) { ImportCodeTemplateTreeTableNode codeTemplateNode = (ImportCodeTemplateTreeTableNode) node; if (codeTemplateNode.getConflicts().getMatchingCodeTemplate() != null) { importTreeTable.getModel().setValueAt(true, row, IMPORT_OVERWRITE_COLUMN); } } } } } }); linkRightOverwriteNoneLabel = new JLabel("<html><u>None</u></html>"); linkRightOverwriteNoneLabel.setForeground(Color.BLUE); linkRightOverwriteNoneLabel.setCursor(new Cursor(Cursor.HAND_CURSOR)); linkRightOverwriteNoneLabel.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent evt) { for (int row = 0; row < importTreeTable.getRowCount(); row++) { TreePath path = importTreeTable.getPathForRow(row); if (path != null) { ImportTreeTableNode node = (ImportTreeTableNode) path.getLastPathComponent(); if (node instanceof ImportLibraryTreeTableNode) { ImportLibraryTreeTableNode libraryNode = (ImportLibraryTreeTableNode) node; if (libraryNode.getConflicts().getMatchingLibrary() != null) { importTreeTable.getModel().setValueAt(false, row, IMPORT_OVERWRITE_COLUMN); } } else if (node instanceof ImportCodeTemplateTreeTableNode) { ImportCodeTemplateTreeTableNode codeTemplateNode = (ImportCodeTemplateTreeTableNode) node; if (codeTemplateNode.getConflicts().getMatchingCodeTemplate() != null) { importTreeTable.getModel().setValueAt(false, row, IMPORT_OVERWRITE_COLUMN); } } } } } }); final TableCellEditor templateCellEditor = new NameCellEditor(); importTreeTable = new JXTreeTable() { @Override public boolean isCellEditable(int row, int column) { return (column == IMPORT_OVERWRITE_COLUMN || column == IMPORT_SELECTED_COLUMN || column == IMPORT_NAME_COLUMN); } @Override public TableCellEditor getCellEditor(int row, int column) { if (isHierarchical(column)) { return templateCellEditor; } else { return super.getCellEditor(row, column); } } }; importTreeTable.setLargeModel(true); DefaultTreeTableModel model = new ImportTreeTableModel(); model.setColumnIdentifiers(Arrays.asList(new String[] { "", "Name", "Overwrite", "Conflicts", "Id" })); DefaultMutableTreeTableNode rootNode = new DefaultMutableTreeTableNode(); model.setRoot(rootNode); importTreeTable.setTreeTableModel(model); Set<String> addedCodeTemplateIds = new HashSet<String>(); if (unassignedCodeTemplates) { ImportTreeTableNode libraryNode = new ImportUnassignedLibraryTreeTableNode("Select a library", ""); CodeTemplateLibrary library = importLibraries.get(0); for (CodeTemplate codeTemplate : library.getCodeTemplates()) { if (!addedCodeTemplateIds.contains(codeTemplate.getId())) { libraryNode .add(new ImportCodeTemplateTreeTableNode(codeTemplate.getName(), codeTemplate.getId())); addedCodeTemplateIds.add(codeTemplate.getId()); importCodeTemplateMap.put(codeTemplate.getId(), codeTemplate); } } rootNode.add(libraryNode); } else { Set<String> addedLibraryIds = new HashSet<String>(); for (CodeTemplateLibrary library : importLibraries) { if (!addedLibraryIds.contains(library.getId())) { ImportTreeTableNode libraryNode = new ImportLibraryTreeTableNode(library.getName(), library.getId()); importLibraryMap.put(library.getId(), library); for (CodeTemplate codeTemplate : library.getCodeTemplates()) { if (!addedCodeTemplateIds.contains(codeTemplate.getId())) { libraryNode.add(new ImportCodeTemplateTreeTableNode(codeTemplate.getName(), codeTemplate.getId())); addedCodeTemplateIds.add(codeTemplate.getId()); importCodeTemplateMap.put(codeTemplate.getId(), codeTemplate); } } rootNode.add(libraryNode); addedLibraryIds.add(library.getId()); } } } importTreeTable.setOpenIcon(null); importTreeTable.setClosedIcon(null); importTreeTable.setLeafIcon(null); importTreeTable.setRootVisible(false); importTreeTable.setDoubleBuffered(true); importTreeTable.setDragEnabled(false); importTreeTable.setRowSelectionAllowed(true); importTreeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); importTreeTable.setRowHeight(UIConstants.ROW_HEIGHT); importTreeTable.setFocusable(true); importTreeTable.setOpaque(true); importTreeTable.getTableHeader().setReorderingAllowed(false); importTreeTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); importTreeTable.setEditable(true); importTreeTable.setSortable(false); importTreeTable.setAutoCreateColumnsFromModel(false); importTreeTable.setShowGrid(true, true); if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) { importTreeTable.setHighlighters(HighlighterFactory .createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR, UIConstants.BACKGROUND_COLOR)); } importTreeTable.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent evt) { checkSelection(evt); } @Override public void mouseReleased(MouseEvent evt) { checkSelection(evt); } private void checkSelection(MouseEvent evt) { int row = importTreeTable.rowAtPoint(new Point(evt.getX(), evt.getY())); if (row < 0) { importTreeTable.clearSelection(); } } }); importTreeTable.addTreeWillExpandListener(new TreeWillExpandListener() { @Override public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException { } @Override public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException { throw new ExpandVetoException(event); } }); importTreeTable.setTreeCellRenderer(new NameCellRenderer()); importTreeTable.getModel().addTableModelListener(new TableModelListener() { @Override public void tableChanged(TableModelEvent evt) { if (evt.getColumn() != IMPORT_CONFLICTS_COLUMN) { for (int row = evt.getFirstRow(); row <= evt.getLastRow() && row < importTreeTable.getRowCount(); row++) { TreePath path = importTreeTable.getPathForRow(row); if (path != null) { ImportTreeTableNode node = (ImportTreeTableNode) path.getLastPathComponent(); if (path.getPathCount() == 2) { if (node instanceof ImportUnassignedLibraryTreeTableNode) { String libraryName = (String) node.getValueAt(IMPORT_NAME_COLUMN); String libraryId = null; for (CodeTemplateLibrary library : PlatformUI.MIRTH_FRAME.codeTemplatePanel .getCachedCodeTemplateLibraries().values()) { if (library.getName().equals(libraryName)) { libraryId = library.getId(); break; } } node.setValueAt(libraryId, IMPORT_ID_COLUMN); } else if (node instanceof ImportLibraryTreeTableNode) { ImportLibraryTreeTableNode libraryNode = (ImportLibraryTreeTableNode) node; libraryNode.setConflicts(getLibraryConflicts(node)); } for (Enumeration<? extends TreeTableNode> codeTemplateNodes = node .children(); codeTemplateNodes.hasMoreElements();) { ImportCodeTemplateTreeTableNode codeTemplateNode = (ImportCodeTemplateTreeTableNode) codeTemplateNodes .nextElement(); codeTemplateNode.setConflicts(getCodeTemplateConflicts(codeTemplateNode)); } importTreeTable.updateUI(); } else if (path.getPathCount() == 3) { ImportCodeTemplateTreeTableNode codeTemplateNode = (ImportCodeTemplateTreeTableNode) node; codeTemplateNode.setConflicts(getCodeTemplateConflicts(node)); } } } } updateImportButton(); updateErrorsAndWarnings(); } }); importTreeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent evt) { if (!evt.getValueIsAdjusting()) { updateImportButton(); updateErrorsAndWarnings(); } } }); importTreeTable.expandAll(); importTreeTable.getColumnModel().getColumn(IMPORT_SELECTED_COLUMN).setMinWidth(20); importTreeTable.getColumnModel().getColumn(IMPORT_SELECTED_COLUMN).setMaxWidth(20); importTreeTable.getColumnModel().getColumn(IMPORT_SELECTED_COLUMN) .setCellRenderer(new ImportSelectedCellRenderer()); importTreeTable.getColumnModel().getColumn(IMPORT_SELECTED_COLUMN) .setCellEditor(new ImportSelectedCellEditor()); importTreeTable.getColumnModel().getColumn(IMPORT_OVERWRITE_COLUMN).setMinWidth(60); importTreeTable.getColumnModel().getColumn(IMPORT_OVERWRITE_COLUMN).setMaxWidth(60); importTreeTable.getColumnModel().getColumn(IMPORT_OVERWRITE_COLUMN) .setCellRenderer(new OverwriteCellRenderer()); importTreeTable.getColumnModel().getColumn(IMPORT_OVERWRITE_COLUMN) .setCellEditor(new OverwriteCellEditor()); importTreeTable.getColumnModel().getColumn(IMPORT_CONFLICTS_COLUMN).setMinWidth(60); importTreeTable.getColumnModel().getColumn(IMPORT_CONFLICTS_COLUMN).setMaxWidth(60); importTreeTable.getColumnModel().getColumn(IMPORT_CONFLICTS_COLUMN).setCellRenderer(new IconCellRenderer()); importTreeTable.getColumnModel().removeColumn(importTreeTable.getColumnModel().getColumn(IMPORT_ID_COLUMN)); importTreeTableScrollPane = new JScrollPane(importTreeTable); importTreeTableScrollPane.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, new Color(0x6E6E6E))); warningsPanel = new JPanel(); warningsPanel.setBackground(getBackground()); warningsPanel.setVisible(false); warningsLabel = new JLabel(UIConstants.ICON_WARNING); warningsTextArea = new JTextArea(); warningsTextArea.setLineWrap(true); warningsTextArea.setWrapStyleWord(true); errorsPanel = new JPanel(); errorsPanel.setBackground(getBackground()); errorsPanel.setVisible(false); errorsLabel = new JLabel(UIConstants.ICON_ERROR); errorsTextArea = new JTextArea(); errorsTextArea.setLineWrap(true); errorsTextArea.setWrapStyleWord(true); separator = new JSeparator(); buttonPanel = new JPanel(); buttonPanel.setBackground(getBackground()); importButton = new JButton("Import"); importButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { try { boolean warnings = false; for (Enumeration<? extends TreeTableNode> libraryNodes = ((TreeTableNode) importTreeTable .getTreeTableModel().getRoot()).children(); libraryNodes.hasMoreElements();) { for (Enumeration<? extends TreeTableNode> codeTemplateNodes = libraryNodes.nextElement() .children(); codeTemplateNodes.hasMoreElements();) { ImportCodeTemplateTreeTableNode codeTemplateNode = (ImportCodeTemplateTreeTableNode) codeTemplateNodes .nextElement(); if ((boolean) codeTemplateNode.getValueAt(IMPORT_SELECTED_COLUMN)) { CodeTemplateConflicts conflicts = codeTemplateNode.getConflicts(); if (conflicts.getMatchingCodeTemplate() != null) { warnings = true; break; } } } if (warnings) { break; } } if (!warnings || PlatformUI.MIRTH_FRAME.alertOption(CodeTemplateImportDialog.this, "Some selected rows have warnings. Are you sure you wish to continue?")) { save(); dispose(); } } catch (Exception e) { PlatformUI.MIRTH_FRAME.alertThrowable(CodeTemplateImportDialog.this, e, "Unable to import: " + e.getMessage()); } } }); cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { if (confirmClose()) { dispose(); } } }); updateImportButton(); }
From source file:com.diversityarrays.kdxplore.curate.fieldview.FieldLayoutViewPanel.java
@SuppressWarnings("unchecked") public FieldLayoutViewPanel(@SuppressWarnings("rawtypes") MutableComboBoxModel comboBoxModel, JCheckBox alwaysOnTopOption, CurationData cd, CurationTableModel ctm, SelectedValueStore svs, PlotCellChoicesPanel pccp, JPopupMenu popuMenu, Font fontForResizeControls, Action curationHelpAction, MessagePrinter mp, Closure<String> selectionClosure, CurationContext curationContext, CurationMenuProvider curationMenuProvider, FieldLayoutTableModel fieldLayoutTableModel, CellSelectableTable fieldLayoutTable, FieldViewSelectionModel fvsm,/*from w ww . jav a 2 s .c o m*/ JButton undockButton) { super(new BorderLayout()); this.traitInstanceCombo.setModel(comboBoxModel); this.curationData = cd; this.messagePrinter = mp; this.selectionClosure = selectionClosure; this.curationTableModel = ctm; this.fieldLayoutTableModel = fieldLayoutTableModel; this.fieldLayoutTable = fieldLayoutTable; this.fieldViewSelectionModel = fvsm; traitInstanceCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object item = comboBoxModel.getSelectedItem(); if (item instanceof TraitInstance) { TraitInstance ti = (TraitInstance) item; plotCellRenderer.setActiveInstance(ti); } } }); rhtm = new RowHeaderTableModel(true, fieldLayoutTable, rowRemovable) { public String getRowLabel(int rowIndex) { int yCoord = FieldLayoutUtil.convertRowIndexToYCoord(rowIndex, trial, fieldLayoutTableModel.getFieldLayout()); return String.valueOf(yCoord); } }; rowHeaderTable = new RowHeaderTable(SwingConstants.CENTER, false, fieldLayoutTable, rowRemovable, rhtm, RowHeaderTable.createDefaultColumnModel("X/Y")) { public String getMarkerIndexName(int viewRow) { return "MIN-" + viewRow; //$NON-NLS-1$ } }; rhtTableRowResizer = new TableRowResizer(rowHeaderTable, true); curationData.addCurationDataChangeListener(plotActivationListener); curationTableModel.addTableModelListener(new TableModelListener() { @Override public void tableChanged(TableModelEvent e) { fieldLayoutTable.repaint(); } }); plotCellRenderer = new PlotCellRenderer(plotAttributeProvider, curationTableModel); TraitInstanceCellRenderer tiCellRenderer = new TraitInstanceCellRenderer( curationData.getTraitColorProvider(), instanceNameProvider); traitInstanceCombo.setRenderer(tiCellRenderer); traitInstanceCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateActiveTraitInstance(); } }); traitInstanceCombo.getModel().addListDataListener(new ListDataListener() { @Override public void intervalRemoved(ListDataEvent e) { updateActiveTraitInstance(); } @Override public void intervalAdded(ListDataEvent e) { updateActiveTraitInstance(); } @Override public void contentsChanged(ListDataEvent e) { updateActiveTraitInstance(); } }); this.trial = curationData.getTrial(); this.plotCellChoicesPanel = pccp; for (TraitInstance t : curationData.getTraitInstances()) { String id = InstanceIdentifierUtil.getInstanceIdentifier(t); traitById.put(id, t); } // fieldViewSelectionModel = new FieldViewSelectionModel( // fieldLayoutTable, // fieldLayoutTableModel, // svs); fieldLayoutTable.setSelectionModel(fieldViewSelectionModel); plotCellRenderer.setCurationData(curationData); plotCellRenderer.setSelectionModel(fieldViewSelectionModel); plotCellChoicesPanel.addPlotCellChoicesListener(plotCellChoicesListener); fieldLayoutTableModel.setTrial(trial); // IMPORTANT: DO NOT SORT THE FIELD LAYOUT TABLE fieldLayoutTable.setAutoCreateRowSorter(false); JScrollPane fieldTableScrollPane = new JScrollPane(fieldLayoutTable); if (undockButton != null) { fieldTableScrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER, undockButton); } fieldTableScrollPane.setRowHeaderView(rowHeaderTable); ChangeListener scrollBarChangeListener = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { fireRefreshRequired(); } }; fieldTableScrollPane.getVerticalScrollBar().getModel().addChangeListener(scrollBarChangeListener); fieldTableScrollPane.getHorizontalScrollBar().getModel().addChangeListener(scrollBarChangeListener); fieldLayoutTable.setRowHeaderTable(rowHeaderTable); // fieldLayoutTable.setComponentPopupMenu(popuMenu); initFieldLayoutTable(); Map<Integer, Plot> plotById = new HashMap<>(); FieldLayout<Integer> plotIdLayout = FieldLayoutUtil.createPlotIdLayout(trial.getTrialLayout(), trial.getPlotIdentSummary(), curationData.getPlots(), plotById); KdxploreFieldLayout<Plot> kdxFieldLayout = new KdxploreFieldLayout<Plot>(Plot.class, plotIdLayout.imageId, plotIdLayout.xsize, plotIdLayout.ysize); kdxFieldLayout.warning = plotIdLayout.warning; for (int y = 0; y < plotIdLayout.ysize; ++y) { for (int x = 0; x < plotIdLayout.xsize; ++x) { Integer id = plotIdLayout.cells[y][x]; if (id != null) { Plot plot = plotById.get(id); kdxFieldLayout.store_xy(plot, x, y); } } } fieldLayoutTableModel.setFieldLayout(kdxFieldLayout); if (kdxFieldLayout.warning != null && !kdxFieldLayout.warning.isEmpty()) { warningMessage.setText(kdxFieldLayout.warning); } else { warningMessage.setText(""); //$NON-NLS-1$ } changeVisitOrderAction.putValue(Action.SMALL_ICON, KDClientUtils.getIcon(kdxFieldLayout.imageId)); List<Component> components = new ArrayList<>(); components.add(alwaysOnTopOption); Collections.addAll(components, new JButton(changeVisitOrderAction), new JButton(curationHelpAction), traitInstanceCombo); Box resizeControls = KDClientUtils.createResizeControls(fieldLayoutTable, fontForResizeControls, components.toArray(new Component[components.size()])); resizeCombo = KDClientUtils.findResizeCombo(resizeControls); if (RunMode.getRunMode().isDeveloper()) { new FieldLayoutViewPanel.DebugSettings(resizeControls, messagePrinter); } JPanel fieldPanel = new JPanel(new BorderLayout()); // if (useSeparator) { // SeparatorPanel separator = GuiUtil.createLabelSeparator("Field Layout:", resizeControls); // fieldPanel.add(separator, BorderLayout.NORTH); // fieldPanel.add(fieldTableScrollPane, BorderLayout.CENTER); // } // else { fieldPanel.add(resizeControls, BorderLayout.NORTH); fieldPanel.add(fieldTableScrollPane, BorderLayout.CENTER); // } // splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, // plotCellChoicesPanel, // fieldPanel); // splitPane.setResizeWeight(0.0); // splitPane.setOneTouchExpandable(true); add(warningMessage, BorderLayout.NORTH); add(fieldPanel, BorderLayout.CENTER); // splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, // plotCellChoicesPanel, // fieldPanel); // splitPane.setResizeWeight(0.0); // splitPane.setOneTouchExpandable(true); // // add(warningMessage, BorderLayout.NORTH); // add(splitPane, BorderLayout.CENTER); fieldLayoutTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { if (SwingUtilities.isRightMouseButton(me) && 1 == me.getClickCount()) { me.consume(); List<Plot> plots = getSelectedPlots(); List<TraitInstance> checkedInstances = new ArrayList<>(); for (int index = traitInstanceCombo.getItemCount(); --index >= 1;) { Object item = traitInstanceCombo.getItemAt(index); if (item instanceof TraitInstance) { checkedInstances.add((TraitInstance) item); } } TraitInstance ti = fieldViewSelectionModel.getActiveTraitInstance(true); List<PlotOrSpecimen> plotSpecimens = new ArrayList<>(); plotSpecimens.addAll(plots); curationMenuProvider.showFieldViewToolMenu(me, plotSpecimens, ti, checkedInstances); } } }); }
From source file:com.diversityarrays.kdxplore.trials.TrialOverviewPanel.java
public TrialOverviewPanel(String title, OfflineData offdata, TrialExplorerManager manager, FileListTransferHandler flth, MessagePrinter mp, final Closure<List<Trial>> onTrialSelected) { super(new BorderLayout()); offlineData = offdata;//from w w w . j a va 2s . com KdxploreDatabase kdxdb = offlineData.getKdxploreDatabase(); if (kdxdb != null) { kdxdb.addEntityChangeListener(trialChangeListener); kdxdb.addEntityChangeListener(traitChangeListener); } this.messagePrinter = mp; TableTransferHandler tth = TableTransferHandler.initialiseForCopySelectAll(trialsTable, true); trialsTable.setTransferHandler(new ChainingTransferHandler(flth, tth)); trialsTable.setAutoCreateRowSorter(true); trialsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { List<Trial> selectedTrials = getSelectedTrials(); if (selectedTrials.size() == 1) { trialTraitsTableModel.setSelectedTrial(selectedTrials.get(0)); } else { trialTraitsTableModel.setSelectedTrial(null); } onTrialSelected.execute(selectedTrials); } } }); trialsTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) { fireEditCommand(e); } } }); GuiUtil.setVisibleRowCount(trialsTable, MAX_INITIAL_VISIBLE_TRIAL_ROWS); offlineData.addOfflineDataChangeListener(offlineDataChangeListener); trialTableModel.addTableModelListener(new TableModelListener() { @Override public void tableChanged(TableModelEvent e) { updateRefreshAction(); } }); trialTraitsTableModel.addTableModelListener(new TableModelListener() { @Override public void tableChanged(TableModelEvent e) { updateAddTraitAction(); updateRemoveTraitAction(); updateScoringOrderAction(); } }); trialTraitsTable.addMouseListener(new MouseAdapter() { List<Trait> selectedTraits; JPopupMenu popupMenu; Action showTraitsAction = new AbstractAction("Select in Trait Explorer") { @Override public void actionPerformed(ActionEvent e) { manager.showTraitsInTraitExplorer(selectedTraits); } }; @Override public void mouseClicked(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e) && 2 == e.getClickCount()) { // Start editing the Trait e.consume(); int vrow = trialTraitsTable.rowAtPoint(e.getPoint()); if (vrow >= 0) { int mrow = trialTraitsTable.convertRowIndexToModel(vrow); if (mrow >= 0) { Trait trait = trialTraitsTableModel.getTraitAt(mrow); if (trait != null) { traitExplorer.startEditing(trait); ; } } } } else if (SwingUtilities.isRightMouseButton(e) && 1 == e.getClickCount()) { // Select the traits in the traitExplorer e.consume(); List<Integer> modelRows = GuiUtil.getSelectedModelRows(trialTraitsTable); if (!modelRows.isEmpty()) { selectedTraits = modelRows.stream().map(trialTraitsTableModel::getTraitAt) .collect(Collectors.toList()); if (popupMenu == null) { popupMenu = new JPopupMenu(); popupMenu.add(showTraitsAction); } Point pt = e.getPoint(); popupMenu.show(trialTraitsTable, pt.x, pt.y); } } } }); trialTraitsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { updateRemoveTraitAction(); } } }); updateAddTraitAction(); updateRemoveTraitAction(); updateScoringOrderAction(); updateRefreshAction(); KDClientUtils.initAction(ImageId.REFRESH_24, refreshTrialTraitsAction, "Refresh"); KDClientUtils.initAction(ImageId.MINUS_GOLD_24, removeTraitAction, "Remove selected Traits"); KDClientUtils.initAction(ImageId.PLUS_BLUE_24, addTraitAction, "Add Traits to Trial"); KDClientUtils.initAction(ImageId.TRAIT_ORDER_24, setScoringOrderAction, "Define Trait Scoring Order"); Box buttons = Box.createHorizontalBox(); buttons.add(new JButton(setScoringOrderAction)); buttons.add(Box.createHorizontalGlue()); buttons.add(new JButton(addTraitAction)); buttons.add(new JButton(removeTraitAction)); buttons.add(Box.createHorizontalStrut(10)); buttons.add(refreshTrialTraitsButton); JPanel traitsPanel = new JPanel(new BorderLayout()); traitsPanel.add(GuiUtil.createLabelSeparator("Uses Traits", buttons), BorderLayout.NORTH); traitsPanel.add(new PromptScrollPane(trialTraitsTable, "If the (single) selected Trial has Traits they will appear here"), BorderLayout.CENTER); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JScrollPane(trialsTable), traitsPanel); splitPane.setResizeWeight(0.5); add(splitPane, BorderLayout.CENTER); }
From source file:com.diversityarrays.kdxplore.trials.TrialViewPanel.java
public TrialViewPanel(WindowOpener<JFrame> windowOpener, OfflineData od, Transformer<Trial, Boolean> checkIfEditorActive, Consumer<Trial> onTraitInstancesRemoved, MessagePrinter mp) {/*from w w w .ja v a 2s .c om*/ super(new BorderLayout()); this.windowOpener = windowOpener; this.checkIfEditorActive = checkIfEditorActive; this.onTraitInstancesRemoved = onTraitInstancesRemoved; this.messagePrinter = mp; this.offlineData = od; this.offlineData.addOfflineDataChangeListener(offlineDataChangeListener); KdxploreDatabase db = offlineData.getKdxploreDatabase(); if (db != null) { db.addEntityChangeListener(trialChangeListener); } trialDataTable.setTransferHandler(TableTransferHandler.initialiseForCopySelectAll(trialDataTable, true)); trialPropertiesTable .setTransferHandler(TableTransferHandler.initialiseForCopySelectAll(trialPropertiesTable, true)); // Note: Can't use renderers because the TM always returns String.class // for getColumnClass() // trialPropertiesTable.setDefaultRenderer(TrialLayout.class, new // TrialLayoutRenderer(trialPropertiesTableModel)); // trialPropertiesTable.setDefaultRenderer(PlotIdentOption.class, new // PlotIdentOptionRenderer(trialPropertiesTableModel)); trialPropertiesTableModel.addTableModelListener(new TableModelListener() { @Override public void tableChanged(TableModelEvent e) { if (trialPropertiesTableModel.getRowCount() > 0) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { GuiUtil.initialiseTableColumnWidths(trialPropertiesTable); } }); trialPropertiesTableModel.removeTableModelListener(this); } } }); // int tnsColumnIndex = -1; // for (int col = trialPropertiesTableModel.getColumnCount(); --col >= 0; ) { // if (TraitNameStyle.class == trialPropertiesTableModel.getColumnClass(col)) { // tnsColumnIndex = col; // break; // } // } editAction.setEnabled(false); trialPropertiesTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { int vrow = trialPropertiesTable.getSelectedRow(); editAction.setEnabled(vrow >= 0 && trialPropertiesTableModel.isCellEditable(vrow, 1)); } } }); errorMessage.setForeground(Color.RED); Box top = Box.createHorizontalBox(); top.add(errorMessage); top.add(Box.createHorizontalGlue()); top.add(new JButton(editAction)); JPanel main = new JPanel(new BorderLayout()); main.add(new JScrollPane(trialPropertiesTable), BorderLayout.CENTER); main.add(legendPanel, BorderLayout.SOUTH); JScrollPane trialDataTableScrollPane = new JScrollPane(trialDataTable); // The preferred height of the viewport is determined // by whether or not we need to use hh:mm:ss in the name of any of // the scoring data sets. JViewport viewPort = new JViewport() { @Override public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); d.height = 32; TableModel model = trialDataTable.getModel(); if (model instanceof TrialData) { if (((TrialData) model).isUsingHMSformat()) { d.height = 48; } } return d; } }; trialDataTableScrollPane.setColumnHeader(viewPort); JTableHeader th = trialDataTable.getTableHeader(); th.setDefaultRenderer(trialDataTableHeaderRenderer); th.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int column = th.columnAtPoint(e.getPoint()); trialDataTableHeaderRenderer.columnSelected = column; boolean shifted = 0 != (MouseEvent.SHIFT_MASK & e.getModifiers()); boolean right = SwingUtilities.isRightMouseButton(e); updateDeleteSamplesAction(shifted, right); e.consume(); } }); trialDataTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { removeTraitInstancesAction.setEnabled(trialDataTable.getSelectedRowCount() > 0); } } }); removeTraitInstancesAction.setEnabled(false); KDClientUtils.initAction(ImageId.PLUS_BLUE_24, addSampleGroupAction, Msg.TOOLTIP_ADD_SAMPLES_FOR_SCORING()); KDClientUtils.initAction(ImageId.TRASH_24, deleteSamplesAction, Msg.TOOLTIP_DELETE_COLLECTED_SAMPLES()); KDClientUtils.initAction(ImageId.EXPORT_24, exportSamplesAction, Msg.TOOLTIP_EXPORT_SAMPLES_OR_TRAITS()); KDClientUtils.initAction(ImageId.MINUS_GOLD_24, removeTraitInstancesAction, Msg.TOOLTIP_REMOVE_TRAIT_INSTANCES_WITH_NO_DATA()); JPanel trialDataPanel = new JPanel(new BorderLayout()); Box buttons = Box.createHorizontalBox(); buttons.add(new JButton(removeTraitInstancesAction)); buttons.add(Box.createHorizontalGlue()); buttons.add(new JButton(exportSamplesAction)); buttons.add(Box.createHorizontalGlue()); buttons.add(new JButton(addSampleGroupAction)); buttons.add(Box.createHorizontalStrut(8)); buttons.add(new JButton(deleteSamplesAction)); trialDataPanel.add(GuiUtil.createLabelSeparator("Measurements by Source", buttons), BorderLayout.NORTH); trialDataPanel.add(trialDataTableScrollPane, BorderLayout.CENTER); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, main, trialDataPanel); splitPane.setResizeWeight(0.5); add(top, BorderLayout.NORTH); add(splitPane, BorderLayout.CENTER); trialDataTable.setDefaultRenderer(Object.class, new TrialDataCellRenderer()); trialDataTable.addPropertyChangeListener("model", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { trialDataTableHeaderRenderer.columnSelected = -1; updateDeleteSamplesAction(false, false); } }); }
From source file:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java
/** * Constructs the pane for the spreadsheet. * //from w w w . j a v a2s . co 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); }