X-Git-Url: http://source.jalview.org/gitweb/?a=blobdiff_plain;f=src%2Fjalview%2Fgui%2FFeatureSettings.java;h=22800ea30f07175787f964904cb3d3e1ac6ef560;hb=e3d51e28d7989c00473258af20b8999085636fc9;hp=7dae70387af45bd3f515697e9a661035d0cb1790;hpb=daeacba9a61069114333b550a987242d8e47e7f7;p=jalview.git diff --git a/src/jalview/gui/FeatureSettings.java b/src/jalview/gui/FeatureSettings.java index 7dae703..22800ea 100755 --- a/src/jalview/gui/FeatureSettings.java +++ b/src/jalview/gui/FeatureSettings.java @@ -1,496 +1,1358 @@ -/* - * Jalview - A Sequence Alignment Editor and Viewer - * Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA - */ -package jalview.gui; - -import jalview.datamodel.*; -import javax.swing.*; -import javax.swing.event.*; -import java.awt.*; -import java.util.*; -import javax.swing.BorderFactory; -import java.awt.event.*; -import javax.swing.table.*; -import java.io.*; -import jalview.io.JalviewFileChooser; - -public class FeatureSettings extends JPanel -{ - - final FeatureRenderer fr; - final AlignmentPanel ap; - final AlignViewport av; - Object [][] originalData; - final JInternalFrame frame; - JScrollPane scrollPane = new JScrollPane(); - JTable table; - - public FeatureSettings(AlignViewport av, final AlignmentPanel ap) - { - this.ap = ap; - this.av = av; - fr = ap.seqPanel.seqCanvas.getFeatureRenderer(); - av.alignment.getSequences(); - frame = new JInternalFrame(); - frame.setContentPane(this); - Desktop.addInternalFrame(frame, "Sequence Feature Settings", 400, 300); - - setTableData(); - - final JSlider transparency = new JSlider(0, 70, 0); - transparency.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent evt) - { - fr.setTransparency( (float) (100 - transparency.getValue()) / 100f); - ap.repaint(); - } - }); - - JPanel transPanel = new JPanel(new FlowLayout()); - transPanel.add(new JLabel("Transparency")); - transPanel.add(transparency); - - ////////////////////////////////////////////// - //We're going to need those OK cancel buttons - JPanel buttonPanel = new JPanel(new FlowLayout()); - JButton button = new JButton("OK"); - button.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent evt) - { - try - { - frame.setClosed(true); - } - catch (Exception exe) - {} - } - }); - buttonPanel.add(button); - button = new JButton("Cancel"); - button.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent evt) - { - try - { - updateFeatureRenderer(originalData); - frame.setClosed(true); - } - catch (Exception exe) - {} - } - }); - buttonPanel.add(button); - - button = new JButton("Load Colours"); - button.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent evt) - { - load(); - } - }); - buttonPanel.add(button); - button = new JButton("Save Colours"); - button.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent evt) - { - save(); - } - }); - buttonPanel.add(button); - - this.setLayout(new BorderLayout()); - JPanel bigPanel = new JPanel(new BorderLayout()); - bigPanel.add(transPanel, BorderLayout.SOUTH); - bigPanel.add(scrollPane, BorderLayout.CENTER); - - add(bigPanel, BorderLayout.CENTER); - add(buttonPanel, BorderLayout.SOUTH); - - - } - - void setTableData() - { - Vector allFeatures = new Vector(); - Vector features; - Enumeration e; - SequenceFeature sf; - - for(int i=0; i< av.alignment.getHeight(); i++) - { - features = av.alignment.getSequenceAt(i).getDatasetSequence().getSequenceFeatures(); - if(features==null) - continue; - - e = features.elements(); - while(e.hasMoreElements()) - { - sf = (SequenceFeature)e.nextElement(); - if(!allFeatures.contains(sf.getType())) - { - allFeatures.addElement(sf.getType()); - } - } - } - if(allFeatures.size()<1) - { - try{ - frame.setClosed(true); - }catch(Exception ex){} - return; - } - - int fSize = allFeatures.size(); - - String type; - boolean originalExists = false; - if(originalData!=null) - originalExists = true; - else - originalData = new Object[fSize][3]; - - Object [][] data = new Object[fSize][3]; - for(int i=0; i tmpfeatures[index].getEnd()) + { + avWidth[1] += 1 + tmpfeatures[index].getBegin() + - tmpfeatures[index].getEnd(); + } + else + { + avWidth[1] += 1 + tmpfeatures[index].getEnd() + - tmpfeatures[index].getBegin(); + } + index++; + } + } + + int fSize = visibleChecks.size(); + Object[][] data = new Object[fSize][3]; + int dataIndex = 0; + + if (fr.renderOrder != null) + { + if (!handlingUpdate) + fr.findAllFeatures(groupChanged != null); // prod to update + // colourschemes. but don't + // affect display + // First add the checks in the previous render order, + // in case the window has been closed and reopened + for (int ro = fr.renderOrder.length - 1; ro > -1; ro--) + { + type = fr.renderOrder[ro]; + + if (!visibleChecks.contains(type)) + { + continue; + } + + data[dataIndex][0] = type; + data[dataIndex][1] = fr.getColour(type); + data[dataIndex][2] = new Boolean(af.getViewport().featuresDisplayed + .containsKey(type)); + dataIndex++; + visibleChecks.removeElement(type); + } + } + + fSize = visibleChecks.size(); + for (int i = 0; i < fSize; i++) + { + // These must be extra features belonging to the group + // which was just selected + type = visibleChecks.elementAt(i).toString(); + data[dataIndex][0] = type; + + data[dataIndex][1] = fr.getColour(type); + if (data[dataIndex][1] == null) + { + // "Colour has been updated in another view!!" + fr.renderOrder = null; + return; + } + + data[dataIndex][2] = new Boolean(true); + dataIndex++; + } + + if (originalData == null) + { + originalData = new Object[data.length][3]; + System.arraycopy(data, 0, originalData, 0, data.length); + } + + table.setModel(new FeatureTableModel(data)); + table.getColumnModel().getColumn(0).setPreferredWidth(200); + + if (groupPanel != null) + { + groupPanel.setLayout(new GridLayout(fr.featureGroups.size() / 4 + 1, + 4)); + + groupPanel.validate(); + bigPanel.add(groupPanel, BorderLayout.NORTH); + } + + updateFeatureRenderer(data, groupChanged != null); + resettingTable = false; + } + + /** + * reorder data based on the featureRenderers global priority list. + * + * @param data + */ + private void ensureOrder(Object[][] data) + { + boolean sort = false; + float[] order = new float[data.length]; + for (int i = 0; i < order.length; i++) + { + order[i] = fr.getOrder(data[i][0].toString()); + if (order[i] < 0) + order[i] = fr.setOrder(data[i][0].toString(), i / order.length); + if (i > 1) + sort = sort || order[i - 1] > order[i]; + } + if (sort) + jalview.util.QuickSort.sort(order, data); + } + + void load() + { + JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache + .getProperty("LAST_DIRECTORY"), new String[] + { "fc" }, new String[] + { "Sequence Feature Colours" }, "Sequence Feature Colours"); + chooser.setFileView(new jalview.io.JalviewFileView()); + chooser.setDialogTitle("Load Feature Colours"); + chooser.setToolTipText("Load"); + + int value = chooser.showOpenDialog(this); + + if (value == JalviewFileChooser.APPROVE_OPTION) + { + File file = chooser.getSelectedFile(); + + try + { + InputStreamReader in = new InputStreamReader(new FileInputStream( + file), "UTF-8"); + + jalview.binding.JalviewUserColours jucs = new jalview.binding.JalviewUserColours(); + jucs = (jalview.binding.JalviewUserColours) jucs.unmarshal(in); + + for (int i = jucs.getColourCount() - 1; i >= 0; i--) + { + String name; + fr.setColour(name = jucs.getColour(i).getName(), new Color( + Integer.parseInt(jucs.getColour(i).getRGB(), 16))); + fr.setOrder(name, (i == 0) ? 0 : i / jucs.getColourCount()); + } + if (table != null) + { + resetTable(null); + Object[][] data = ((FeatureTableModel) table.getModel()) + .getData(); + ensureOrder(data); + updateFeatureRenderer(data, false); + table.repaint(); + } + } catch (Exception ex) + { + System.out.println("Error loading User Colour File\n" + ex); + } + } + } + + void save() + { + JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache + .getProperty("LAST_DIRECTORY"), new String[] + { "fc" }, new String[] + { "Sequence Feature Colours" }, "Sequence Feature Colours"); + chooser.setFileView(new jalview.io.JalviewFileView()); + chooser.setDialogTitle("Save Feature Colour Scheme"); + chooser.setToolTipText("Save"); + + int value = chooser.showSaveDialog(this); + + if (value == JalviewFileChooser.APPROVE_OPTION) + { + String choice = chooser.getSelectedFile().getPath(); + jalview.binding.JalviewUserColours ucs = new jalview.binding.JalviewUserColours(); + ucs.setSchemeName("Sequence Features"); + try + { + PrintWriter out = new PrintWriter(new OutputStreamWriter( + new FileOutputStream(choice), "UTF-8")); + + Enumeration e = fr.featureColours.keys(); + float[] sortOrder = new float[fr.featureColours.size()]; + String[] sortTypes = new String[fr.featureColours.size()]; + int i = 0; + while (e.hasMoreElements()) + { + sortTypes[i] = e.nextElement().toString(); + sortOrder[i] = fr.getOrder(sortTypes[i]); + i++; + } + jalview.util.QuickSort.sort(sortOrder, sortTypes); + sortOrder = null; + for (i = 0; i < sortTypes.length; i++) + { + jalview.binding.Colour col = new jalview.binding.Colour(); + col.setName(sortTypes[i]); + col.setRGB(jalview.util.Format.getHexString(fr.getColour(col + .getName()))); + ucs.addColour(col); + } + ucs.marshal(out); + out.close(); + } catch (Exception ex) + { + ex.printStackTrace(); + } + } + } + + public void invertSelection() + { + for (int i = 0; i < table.getRowCount(); i++) + { + Boolean value = (Boolean) table.getValueAt(i, 2); + + table.setValueAt(new Boolean(!value.booleanValue()), i, 2); + } + } + + public void orderByAvWidth() + { + if (table == null || table.getModel() == null) + return; + Object[][] data = ((FeatureTableModel) table.getModel()).getData(); + float[] width = new float[data.length]; + float[] awidth; + float max = 0; + int num = 0; + for (int i = 0; i < data.length; i++) + { + awidth = (float[]) typeWidth.get(data[i][0]); + if (awidth[0] > 0) + { + width[i] = awidth[1] / awidth[0];// *awidth[0]*awidth[2]; - better + // weight - but have to make per + // sequence, too (awidth[2]) + // if (width[i]==1) // hack to distinguish single width sequences. + num++; + } + else + { + width[i] = 0; + } + if (max < width[i]) + max = width[i]; + } + boolean sort = false; + for (int i = 0; i < width.length; i++) + { + // awidth = (float[]) typeWidth.get(data[i][0]); + if (width[i] == 0) + { + width[i] = fr.getOrder(data[i][0].toString()); + if (width[i] < 0) + { + width[i] = fr.setOrder(data[i][0].toString(), i / data.length); + } + } + else + { + width[i] /= max; // normalize + fr.setOrder(data[i][0].toString(), width[i]); // store for later + } + if (i > 0) + sort = sort || width[i - 1] > width[i]; + } + if (sort) + jalview.util.QuickSort.sort(width, data); + // update global priority order + + updateFeatureRenderer(data, false); + table.repaint(); + } + + public void close() + { + try + { + frame.setClosed(true); + } catch (Exception exe) + { + } + + } + + public void updateFeatureRenderer(Object[][] data) + { + updateFeatureRenderer(data, true); + } + + private void updateFeatureRenderer(Object[][] data, boolean visibleNew) + { + fr.setFeaturePriority(data, visibleNew); + af.alignPanel.paintAlignment(true); + } + + int selectedRow = -1; + + JTabbedPane tabbedPane = new JTabbedPane(); + + BorderLayout borderLayout1 = new BorderLayout(); + + BorderLayout borderLayout2 = new BorderLayout(); + + BorderLayout borderLayout3 = new BorderLayout(); + + JPanel bigPanel = new JPanel(); + + BorderLayout borderLayout4 = new BorderLayout(); + + JButton invert = new JButton(); + + JPanel buttonPanel = new JPanel(); + + JButton cancel = new JButton(); + + JButton ok = new JButton(); + + JButton loadColours = new JButton(); + + JButton saveColours = new JButton(); + + JPanel dasButtonPanel = new JPanel(); + + JButton fetchDAS = new JButton(); + + JButton saveDAS = new JButton(); + + JButton cancelDAS = new JButton(); + + JButton optimizeOrder = new JButton(); + + JButton sortByScore = new JButton(); + + JButton sortByDens = new JButton(); + + JPanel transbuttons = new JPanel(new BorderLayout()); + + private void jbInit() throws Exception + { + this.setLayout(borderLayout1); + settingsPane.setLayout(borderLayout2); + dasSettingsPane.setLayout(borderLayout3); + bigPanel.setLayout(borderLayout4); + invert.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11)); + invert.setText("Invert Selection"); + invert.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + invertSelection(); + } + }); + optimizeOrder.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11)); + optimizeOrder.setText("Optimise Order"); + optimizeOrder.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + orderByAvWidth(); + } + }); + sortByScore.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11)); + sortByScore.setText("Seq sort by Score"); + sortByScore.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + sortByScore(null); + } + }); + sortByDens.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11)); + sortByDens.setText("Seq Sort by density"); + sortByDens.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + sortByDens(null); + } + }); + cancel.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11)); + cancel.setText("Cancel"); + cancel.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + updateFeatureRenderer(originalData); + close(); + } + }); + ok.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11)); + ok.setText("OK"); + ok.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + close(); + } + }); + loadColours.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11)); + loadColours.setText("Load Colours"); + loadColours.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + load(); + } + }); + saveColours.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11)); + saveColours.setText("Save Colours"); + saveColours.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + save(); + } + }); + transparency.addChangeListener(new ChangeListener() + { + public void stateChanged(ChangeEvent evt) + { + fr.setTransparency((float) (100 - transparency.getValue()) / 100f); + af.alignPanel.paintAlignment(true); + } + }); + + transparency.setMaximum(70); + fetchDAS.setText("Fetch DAS Features"); + fetchDAS.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + fetchDAS_actionPerformed(e); + } + }); + saveDAS.setText("Save as default"); + saveDAS.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + saveDAS_actionPerformed(e); + } + }); + dasButtonPanel.setBorder(BorderFactory.createEtchedBorder()); + dasSettingsPane.setBorder(null); + cancelDAS.setEnabled(false); + cancelDAS.setText("Cancel Fetch"); + cancelDAS.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + cancelDAS_actionPerformed(e); + } + }); + this.add(tabbedPane, java.awt.BorderLayout.CENTER); + tabbedPane.addTab("Feature Settings", settingsPane); + tabbedPane.addTab("DAS Settings", dasSettingsPane); + bigPanel.add(transPanel, java.awt.BorderLayout.SOUTH); + transPanel.add(transparency); + transbuttons.add(invert, java.awt.BorderLayout.NORTH); + transbuttons.add(optimizeOrder, java.awt.BorderLayout.SOUTH); + transPanel.add(transbuttons); + buttonPanel.add(ok); + buttonPanel.add(cancel); + buttonPanel.add(loadColours); + buttonPanel.add(saveColours); + buttonPanel.add(sortByScore); + buttonPanel.add(sortByDens); + bigPanel.add(scrollPane, java.awt.BorderLayout.CENTER); + dasSettingsPane.add(dasButtonPanel, java.awt.BorderLayout.SOUTH); + dasButtonPanel.add(fetchDAS); + dasButtonPanel.add(cancelDAS); + dasButtonPanel.add(saveDAS); + settingsPane.add(bigPanel, java.awt.BorderLayout.CENTER); + settingsPane.add(buttonPanel, java.awt.BorderLayout.SOUTH); + } + + protected void sortByDens(String[] typ) + { + sortBy(typ, "Sort by Density", AlignmentSorter.FEATURE_DENSITY); + } + + protected void sortBy(String[] typ, String methodText, final String method) + { + if (typ == null) + { + typ = getDisplayedFeatureTypes(); + } + String gps[] = null; + gps = getDisplayedFeatureGroups(); + if (typ != null) + { + for (int i = 0; i < typ.length; i++) + { + System.err.println("Sorting on Types:" + typ[i]); + } + } + if (gps != null) + { + + for (int i = 0; i < gps.length; i++) + { + System.err.println("Sorting on groups:" + gps[i]); + } + } + AlignmentPanel alignPanel = af.alignPanel; + AlignmentI al = alignPanel.av.getAlignment(); + + int start, stop; + SequenceGroup sg = alignPanel.av.getSelectionGroup(); + if (sg != null) + { + start = sg.getStartRes(); + stop = sg.getEndRes(); + } + else + { + start = 0; + stop = al.getWidth(); + } + SequenceI[] oldOrder = al.getSequencesArray(); + AlignmentSorter.sortByFeature(typ, gps, start, stop, al, method); + af.addHistoryItem(new OrderCommand(methodText, oldOrder, alignPanel.av + .getAlignment())); + alignPanel.paintAlignment(true); + + } + + protected void sortByScore(String[] typ) + { + sortBy(typ, "Sort by Feature Score", AlignmentSorter.FEATURE_SCORE); + } + + private String[] getDisplayedFeatureTypes() + { + String[] typ = null; + if (fr != null) + { + synchronized (fr.renderOrder) + { + typ = new String[fr.renderOrder.length]; + System.arraycopy(fr.renderOrder, 0, typ, 0, typ.length); + for (int i = 0; i < typ.length; i++) + { + if (af.viewport.featuresDisplayed.get(typ[i]) == null) + { + typ[i] = null; + } + } + } + } + return typ; + } + + private String[] getDisplayedFeatureGroups() + { + String[] gps = null; + if (fr != null) + { + + if (fr.featureGroups != null) + { + Enumeration en = fr.featureGroups.keys(); + gps = new String[fr.featureColours.size()]; + int g = 0; + boolean valid = false; + while (en.hasMoreElements()) + { + String gp = (String) en.nextElement(); + Boolean on = (Boolean) fr.featureGroups.get(gp); + if (on != null && on.booleanValue()) + { + valid = true; + gps[g++] = gp; + } + } + while (g < gps.length) + { + gps[g++] = null; + } + if (!valid) + { + return null; + } + } + } + return gps; + } + + public void fetchDAS_actionPerformed(ActionEvent e) + { + fetchDAS.setEnabled(false); + cancelDAS.setEnabled(true); + Vector selectedSources = dassourceBrowser.getSelectedSources(); + doDasFeatureFetch(selectedSources, true, true); + } + + /** + * get the features from selectedSources for all or the current selection + * + * @param selectedSources + * @param checkDbRefs + * @param promptFetchDbRefs + */ + private void doDasFeatureFetch(Vector selectedSources, + boolean checkDbRefs, boolean promptFetchDbRefs) + { + SequenceI[] dataset, seqs; + int iSize; + AlignViewport vp = af.getViewport(); + if (vp.getSelectionGroup() != null + && vp.getSelectionGroup().getSize() > 0) + { + iSize = vp.getSelectionGroup().getSize(); + dataset = new SequenceI[iSize]; + seqs = vp.getSelectionGroup().getSequencesInOrder(vp.getAlignment()); + } + else + { + iSize = vp.getAlignment().getHeight(); + seqs = vp.getAlignment().getSequencesArray(); + } + + dataset = new SequenceI[iSize]; + for (int i = 0; i < iSize; i++) + { + dataset[i] = seqs[i].getDatasetSequence(); + } + + cancelDAS.setEnabled(true); + dasFeatureFetcher = new jalview.ws.DasSequenceFeatureFetcher(dataset, + this, selectedSources, checkDbRefs, promptFetchDbRefs); + af.getViewport().setShowSequenceFeatures(true); + af.showSeqFeatures.setSelected(true); + } + + /** + * blocking call to initialise the das source browser + */ + public void initDasSources() + { + dassourceBrowser.initDasSources(); + } + + /** + * examine the current list of das sources and return any matching the given + * nicknames in sources + * + * @param sources + * Vector of Strings to resolve to DAS source nicknames. + * @return sources that are present in source list. + */ + public Vector resolveSourceNicknames(Vector sources) + { + return dassourceBrowser.resolveSourceNicknames(sources); + } + + /** + * get currently selected das sources. ensure you have called initDasSources + * before calling this. + * + * @return vector of selected das source nicknames + */ + public Vector getSelectedSources() + { + return dassourceBrowser.getSelectedSources(); + } + + /** + * properly initialise DAS fetcher and then initiate a new thread to fetch + * features from the named sources (rather than any turned on by default) + * + * @param sources + */ + public void fetchDasFeatures(Vector sources) + { + initDasSources(); + Vector resolved = resolveSourceNicknames(sources); + if (resolved.size() == 0) + { + resolved = dassourceBrowser.getSelectedSources(); + } + if (resolved.size() > 0) + { + final Vector dassources = resolved; + SwingUtilities.invokeLater(new Runnable() + { + + public void run() + { + fetchDAS.setEnabled(false); + cancelDAS.setEnabled(true); + doDasFeatureFetch(dassources, true, false); + + } + }); + } + } + + public void saveDAS_actionPerformed(ActionEvent e) + { + dassourceBrowser + .saveProperties(jalview.bin.Cache.applicationProperties); + } + + public void complete() + { + fetchDAS.setEnabled(true); + cancelDAS.setEnabled(false); + } + + public void cancelDAS_actionPerformed(ActionEvent e) + { + if (dasFeatureFetcher != null) + { + dasFeatureFetcher.cancel(); + } + fetchDAS.setEnabled(true); + cancelDAS.setEnabled(false); + } + + public void noDasSourceActive() + { + complete(); + JOptionPane.showInternalConfirmDialog(Desktop.desktop, + "No das sources were selected.\n" + + "Please select some sources and\n" + " try again.", + "No Sources Selected", JOptionPane.DEFAULT_OPTION, + JOptionPane.INFORMATION_MESSAGE); + } + + // /////////////////////////////////////////////////////////////////////// + // http://java.sun.com/docs/books/tutorial/uiswing/components/table.html + // /////////////////////////////////////////////////////////////////////// + class FeatureTableModel extends AbstractTableModel + { + FeatureTableModel(Object[][] data) + { + this.data = data; + } + + private String[] columnNames = + { "Feature Type", "Colour", "Display" }; + + private Object[][] data; + + public Object[][] getData() + { + return data; + } + + public void setData(Object[][] data) + { + this.data = data; + } + + public int getColumnCount() + { + return columnNames.length; + } + + public Object[] getRow(int row) + { + return data[row]; + } + + public int getRowCount() + { + return data.length; + } + + public String getColumnName(int col) + { + return columnNames[col]; + } + + public Object getValueAt(int row, int col) + { + return data[row][col]; + } + + public Class getColumnClass(int c) + { + return getValueAt(0, c).getClass(); + } + + public boolean isCellEditable(int row, int col) + { + return col == 0 ? false : true; + } + + public void setValueAt(Object value, int row, int col) + { + data[row][col] = value; + fireTableCellUpdated(row, col); + updateFeatureRenderer(data); + } + + } + + class ColorRenderer extends JLabel implements TableCellRenderer + { + javax.swing.border.Border unselectedBorder = null; + + javax.swing.border.Border selectedBorder = null; + + public ColorRenderer() + { + setOpaque(true); // MUST do this for background to show up. + } + + public Component getTableCellRendererComponent(JTable table, + Object color, boolean isSelected, boolean hasFocus, int row, + int column) + { + Color newColor; + color = fr.featureColours.get((String) table.getModel().getValueAt( + row, 0)); + if (color instanceof GraduatedColor) + { + newColor = ((GraduatedColor) color).getMaxColor(); + Color minCol = ((GraduatedColor) color).getMinColor();; + setBackground(newColor); + setToolTipText("RGB value: Max (" + newColor.getRed() + ", " + + newColor.getGreen() + ", " + newColor.getBlue() + + ")\nMin (" + minCol.getRed() + ", " + minCol.getGreen() + + ", " + minCol.getBlue() + ")"); + } + else + { + newColor = (Color) color; + setBackground(newColor); + setToolTipText("RGB value: " + newColor.getRed() + ", " + + newColor.getGreen() + ", " + newColor.getBlue()); + } + if (isSelected) + { + if (selectedBorder == null) + { + selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, + table.getSelectionBackground()); + } + setBorder(selectedBorder); + } + else + { + if (unselectedBorder == null) + { + unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, + table.getBackground()); + } + setBorder(unselectedBorder); + } + + return this; + } + } +} + +class ColorEditor extends AbstractCellEditor implements TableCellEditor, + ActionListener +{ + Color currentColor; + + JButton button; + + JColorChooser colorChooser; + + JDialog dialog; + + protected static final String EDIT = "edit"; + + public ColorEditor() + { + // Set up the editor (from the table's point of view), + // which is a button. + // This button brings up the color chooser dialog, + // which is the editor from the user's point of view. + button = new JButton(); + button.setActionCommand(EDIT); + button.addActionListener(this); + button.setBorderPainted(false); + // Set up the dialog that the button brings up. + colorChooser = new JColorChooser(); + dialog = JColorChooser.createDialog(button, "Select new Colour", true, // modal + colorChooser, this, // OK button handler + null); // no CANCEL button handler + } + + /** + * Handles events from the editor button and from the dialog's OK button. + */ + public void actionPerformed(ActionEvent e) + { + + if (EDIT.equals(e.getActionCommand())) + { + // The user has clicked the cell, so + // bring up the dialog. + button.setBackground(currentColor); + colorChooser.setColor(currentColor); + dialog.setVisible(true); + + // Make the renderer reappear. + fireEditingStopped(); + + } + else + { // User pressed dialog's "OK" button. + currentColor = colorChooser.getColor(); + } + } + + // Implement the one CellEditor method that AbstractCellEditor doesn't. + public Object getCellEditorValue() + { + return currentColor; + } + + // Implement the one method defined by TableCellEditor. + public Component getTableCellEditorComponent(JTable table, Object value, + boolean isSelected, int row, int column) + { + currentColor = (Color) value; + return button; + } +}