List of usage examples for javax.swing.table TableCellRenderer getTableCellRendererComponent
Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column);
From source file:org.ut.biolab.medsavant.client.view.genetics.variantinfo.VariantFrequencyAggregatePane.java
public void setVariantRecords(Set<VariantRecord> records) { innerPanel.removeAll();/* w w w .j a v a 2 s.co m*/ //This function executes quickly, no need for waitPanel. //innerPanel.add(new WaitPanel("Loading DNA Ids...")); tableModel.setValues(records); aggregateTable = new AggregateTable(tableModel) { @Override //Necessary to enable buttons within the table. public boolean isCellEditable(int rowIndex, int colIndex) { return colIndex == buttonIndex; } //"Disables" selection within the aggregateTable. @Override public TableCellRenderer getCellRenderer(final int rowIndex, final int columnIndex) { final TableCellRenderer renderer = super.getCellRenderer(rowIndex, columnIndex); return new TableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable jtable, final Object o, boolean bln, boolean bln1, int i, int i1) { return renderer.getTableCellRendererComponent(jtable, o, false, false, i, i1); } }; } //This overridden method, together with the custom mouse listener on the //AggregateTable header, disallows moving the first column, and columns //>= dnaIDIndex @Override protected AggregateTable.DraggingHandler createDraggingColumnPropertyChangeListener() { return new AggregateTable.DraggingHandler() { @Override public void columnMoved(TableColumnModelEvent e) { if (fromColumnIndex == -1) { fromColumnIndex = e.getFromIndex(); } toColumnIndex = e.getToIndex(); } }; } }; header = new AggregateTableHeader(aggregateTable); header.addMouseListener(new MouseAdapter() { //Disable moving the first column, or columns with index //>=dnaIDIndex @Override public void mouseReleased(MouseEvent e) { if (toColumnIndex != -1 && ((toColumnIndex == 0 || fromColumnIndex == 0) || (toColumnIndex >= dnaIDIndex || fromColumnIndex >= dnaIDIndex))) { aggregateTable.moveColumn(toColumnIndex, fromColumnIndex); String msg = "This column cannot be moved."; DialogUtils.displayMessage(msg); } else { for (int columnHeaderIndex = 0; columnHeaderIndex < header.getColumnModel().getColumnCount() - 2; columnHeaderIndex++) { String columnTitle = (String) header.getColumnModel().getColumn(columnHeaderIndex) .getHeaderValue(); aggregateColumns[columnHeaderIndex] = columnTitle; } reaggregate(); } //aggregateTable.aggregate(this.aggregateColumns); fromColumnIndex = -1; toColumnIndex = -1; //expandAllButLast(); } }); header.setAutoFilterEnabled(false); header.setReorderingAllowed(true); header.setFont(TABLE_FONT_LARGE); aggregateTable.setTableHeader(header); aggregateTable.setAutoResizeMode(AggregateTable.AUTO_RESIZE_ALL_COLUMNS); aggregateTable.setFont(TABLE_FONT_LARGE); //Setup a custom "summary". This is what calculates frequencies when cells are //collapsed PivotField f = aggregateTable.getAggregateTableModel().getField(BasicVariantColumns.DNA_ID.getAlias()); f.setSummaryType(PivotConstants.SUMMARY_RESERVED_MAX + 1); aggregateTable.getAggregateTableModel().setSummaryCalculator(new SummaryCalculator() { private Set<String> collapsedDNAIDs = new HashSet<String>(); private Values lastRowValues; private int valueCount = 0; private final int SUMMARY_FREQ = PivotConstants.SUMMARY_RESERVED_MAX + 1; @Override public void addValue(PivotValueProvider dataModel, PivotField field, Values rowValues, Values columnValues, Object object) { //this gets called multiple times for all the cells that disappear when //something is collapsed. // row[0] is the value of the corresponding first column: e.g. a Cohort or Family. // columnValues can be ignored (blank) // Object is the value of the item in the cell that disappeared. (i.e. those cells which are being summarized) // field.getName() is the column name corresponding to Object // Useful Debugging code: //if(field.getName().equals(BasicVariantColumns.DNA_ID.getAlias())){ /* System.out.println("=========="); System.out.println("Field : " + field.getName()); System.out.println("Row values: "); for (int i = 0; i < rowValues.getCount(); ++i) { System.out.println("\trow[" + i + "] = " + rowValues.getValueAt(i).getValue()); } System.out.println("Column values: "); for (int i = 0; i < columnValues.getCount(); ++i) { System.out.println("\tcol[" + i + "] = " + columnValues.getValueAt(i).getValue()); } System.out.println("Object: "); System.out.println("\t" + object); System.out.println("=========="); */ // } if (field.getName().equals(BasicVariantColumns.DNA_ID.getAlias())) { collapsedDNAIDs.add((String) object); lastRowValues = rowValues; } else { lastRowValues = null; } valueCount++; } //Should never be called @Override public void addValue(Object o) { LOG.error("Unexpected method invocation in OtherIndividualsSubInspector (1)"); } //Should never be called @Override public void addValue(IPivotDataModel ipdm, PivotField pf, int i, int i1, Object o) { LOG.error("Unexpected method invocation in OtherIndividualsSubInspector (2)"); } //Should never be called @Override public void addValue(PivotValueProvider pvp, PivotField pf, Object o) { LOG.error("Unexpected method invocation in OtherIndividualsSubInspector (3)"); } @Override public void clear() { collapsedDNAIDs.clear(); valueCount = 0; lastRowValues = null; } @Override public Object getSummaryResult(int type) { //if null, then we're not in the DNAId column. Return null //to show a blank in this cell if (lastRowValues == null) { return null; } int numIndividuals = getNumberOfIndividualsInGroup(lastRowValues.getValueAt(0)); return new Frequency(collapsedDNAIDs.size(), numIndividuals); } private int getNumberOfIndividualsInGroup(Value v) { if (aggregateColumns[0].equals("Cohort")) { //LOG.debug("Getting number of individuals in group " + v.getValue()); Set<String> dnaIds = cohortDNAIDMap.get((Cohort) v.getValue()); //for (String id : dnaIds) { //LOG.debug("\tGot id " + id); //} return cohortDNAIDMap.get((Cohort) v.getValue()).size(); } else if (aggregateColumns[0].equals(BasicPatientColumns.FAMILY_ID.getAlias())) { return familyIDdnaIDMap.get((String) v.getValue()).size(); } else { LOG.error("Invalid first column"); return -1; } } @Override public long getCount() { return valueCount; } @Override public int getNumberOfSummaries() { return 1; } @Override public String getSummaryName(Locale locale, int i) { return "Frequency"; } @Override public int[] getAllowedSummaries(Class<?> type) { return new int[] { SUMMARY_FREQ }; } @Override public int[] getAllowedSummaries(Class<?> type, ConverterContext cc) { return new int[] { SUMMARY_FREQ }; } }); //Sets up the context menu for clicking column headers. This will probably not be used //frequently. Limit the available operations to collapsing, expanding, and grouping. TableHeaderPopupMenuInstaller installer = new TableHeaderPopupMenuInstaller(aggregateTable); installer.addTableHeaderPopupMenuCustomizer(new AggregateTablePopupMenuCustomizer() { @Override public void customizePopupMenu(JTableHeader header, JPopupMenu popup, int clickingColumn) { super.customizePopupMenu(header, popup, clickingColumn); for (int i = 0; i < popup.getComponentCount(); i++) { String menuItemName = popup.getComponent(i).getName(); if (!(CONTEXT_MENU_COLLAPSE.equals(menuItemName) || CONTEXT_MENU_COLLAPSE_ALL.equals(menuItemName) || CONTEXT_MENU_EXPAND.equals(menuItemName) || CONTEXT_MENU_EXPAND_ALL.equals(menuItemName) || CONTEXT_MENU_GROUP.equals(menuItemName) || CONTEXT_MENU_UNGROUP.equals(menuItemName))) { popup.remove(popup.getComponent(i)); } } } }); aggregateTable.getAggregateTableModel().setSummaryMode(true); aggregateTable.aggregate(aggregateColumns); aggregateTable.setShowContextMenu(false); expandAllButLast(); setupButtonColumn(); JScrollPane jsp = new JScrollPane(aggregateTable); jsp.setPreferredSize(PREFERRED_SIZE); JPanel bp = new JPanel(); bp.setLayout(new BoxLayout(bp, BoxLayout.X_AXIS)); JButton closeButton = new JButton(IconFactory.getInstance().getIcon(IconFactory.StandardIcon.CLOSE)); closeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { unsplitScreen(); } }); bp.add(Box.createHorizontalGlue()); bp.add(title); bp.add(Box.createHorizontalGlue()); bp.add(closeButton); innerPanel.add(bp); innerPanel.add(jsp); reaggregate(); innerPanel.revalidate(); innerPanel.repaint(); }
From source file:org.wandora.application.gui.OccurrenceTableSingleType.java
/** Creates a new instance of OccurrenceTableSingleType */ public OccurrenceTableSingleType(Topic topic, Topic type, Options options, Wandora wandora) throws TopicMapException { this.wandora = wandora; this.topic = topic; TopicMap tm = wandora.getTopicMap(); try {/*from ww w .jav a 2 s.c o m*/ Options opts = options; if (opts == null) opts = wandora.getOptions(); if (opts != null) { tableType = opts.get(VIEW_OPTIONS_KEY); if (tableType == null || tableType.length() == 0) tableType = VIEW_SCHEMA; defaultRowHeight = opts.getInt(ROW_HEIGHT_OPTIONS_KEY); } } catch (Exception e) { e.printStackTrace(); } this.type = type; HashSet<Topic> langSet = new LinkedHashSet(); if (VIEW_USED.equalsIgnoreCase(tableType) || VIEW_USED_AND_SCHEMA.equalsIgnoreCase(tableType)) { Hashtable<Topic, String> occs = null; Topic langTopic = null; occs = topic.getData(type); for (Enumeration<Topic> keys = occs.keys(); keys.hasMoreElements();) { langTopic = keys.nextElement(); langSet.add(langTopic); } } if (VIEW_SCHEMA.equalsIgnoreCase(tableType) || VIEW_USED_AND_SCHEMA.equalsIgnoreCase(tableType)) { Collection<Topic> langTopics = tm.getTopicsOfType(LANGUAGE_SI); langSet.addAll(langTopics); } langs = langSet.toArray(new Topic[langSet.size()]); data = new String[langs.length]; originalData = new String[langs.length]; colors = new Color[langs.length]; for (int j = 0; j < langs.length; j++) { if (langs[j] != null) { data[j] = topic.getData(type, langs[j]); if (data[j] == null) data[j] = ""; originalData[j] = data[j]; colors[j] = wandora.topicHilights.getOccurrenceColor(topic, type, langs[j]); } } dataModel = new DataTableModel(); sorter = new TableRowSorter(dataModel); final TableCellRenderer oldRenderer = this.getTableHeader().getDefaultRenderer(); this.getTableHeader().setPreferredSize(new Dimension(100, 23)); this.getTableHeader().setDefaultRenderer(new TableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = oldRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); return c; } }); this.setAutoCreateColumnsFromModel(false); TableColumn column = new TableColumn(0, 40, new TopicCellRenderer(), new TopicCellEditor()); this.addColumn(column); column = new TableColumn(1, 400, new DataCellRenderer(), new DataCellEditor()); this.addColumn(column); this.setTableHeader(this.getTableHeader()); this.setModel(dataModel); this.setRowSorter(sorter); sorter.setSortsOnUpdates(true); updateRowHeights(); popupStruct = WandoraMenuManager.getOccurrenceTableMenu(this, options); JPopupMenu popup = UIBox.makePopupMenu(popupStruct, wandora); this.setComponentPopupMenu(popup); this.addMouseListener(this); this.setColumnSelectionAllowed(false); this.setRowSelectionAllowed(false); this.setDragEnabled(true); this.setTransferHandler(new OccurrencesTableTransferHandler()); this.setDropMode(DropMode.ON); this.createDefaultTableSelectionModel(); }
From source file:org.yccheok.jstock.gui.JTableUtilities.java
public static void makeTableColumnWidthFit(JTable jTable, int col, int margin, boolean locking) { // strategy - get max width for cells in column and // make that the preferred width TableColumnModel columnModel = jTable.getColumnModel(); int maxwidth = 0; for (int row = 0; row < jTable.getRowCount(); row++) { TableCellRenderer rend = jTable.getCellRenderer(row, col); Object value = jTable.getValueAt(row, col); Component comp = rend.getTableCellRendererComponent(jTable, value, false, false, row, col); maxwidth = Math.max(comp.getPreferredSize().width + margin, maxwidth); } // for row/*from w w w . j a v a 2s . co m*/ TableColumn column = columnModel.getColumn(col); TableCellRenderer headerRenderer = column.getHeaderRenderer(); if (headerRenderer == null) { headerRenderer = jTable.getTableHeader().getDefaultRenderer(); } Object headerValue = column.getHeaderValue(); Component headerComp = headerRenderer.getTableCellRendererComponent(jTable, headerValue, false, false, 0, col); maxwidth = Math.max(maxwidth, headerComp.getPreferredSize().width + margin); column.setPreferredWidth(maxwidth); if (locking) { // User will not able to adjust the width manually. column.setMinWidth(maxwidth); column.setMaxWidth(maxwidth); } }
From source file:org.yccheok.jstock.gui.PortfolioManagementJPanel.java
private void initTreeTableDefaultRenderer(JXTreeTable treeTable) { final TableCellRenderer doubleOldTableCellRenderer = treeTable.getDefaultRenderer(Double.class); treeTable.setDefaultRenderer(Double.class, new DefaultTableCellRenderer() { @Override//from ww w .j a va 2s .co m public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { final Component c = doubleOldTableCellRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); final String UNITS = GUIBundle.getString("PortfolioManagementJPanel_Units"); // Do not manipulate display for "Units". We do not want 100 // "units" displayed as 100.00 "units". if (false == UNITS.equals(table.getColumnName(column))) { if (value != null) { if (c instanceof JLabel) { // Re-define the displayed value. // Ugly hacking. if (value instanceof DoubleWrapper) { DoubleWrapper v = (DoubleWrapper) value; ((JLabel) c).setText( org.yccheok.jstock.portfolio.Utils.toCurrency(v.decimalPlace, v.value)); } else if (value instanceof DoubleWithCurrency) { DoubleWithCurrency v = (DoubleWithCurrency) value; Currency currency = v.currency(); String content = org.yccheok.jstock.portfolio.Utils.toCurrency(v.decimalPlace(), v.Double()); if (currency == null) { ((JLabel) c).setText(content); } else { String prefix = currency.toString(); if (Currency.GBX.equals(prefix)) { // Special handling. prefix = Currency.GBP; } else if (Currency.ZAC.equals(prefix)) { // Special handling. prefix = Currency.ZAR; } ((JLabel) c).setText(prefix + " " + content); } } else { ((JLabel) c).setText( org.yccheok.jstock.portfolio.Utils.toCurrency(DecimalPlace.Four, value)); } } } } else { if (value != null) { if (c instanceof JLabel) { ((JLabel) c).setText(org.yccheok.jstock.portfolio.Utils.toUnits(value)); } } } return c; } }); treeTable.setDefaultRenderer(SimpleDate.class, new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (value != null) { if (c instanceof JLabel) { DateFormat dateFormat = DateFormat.getDateInstance(); SimpleDate simpleDate = (SimpleDate) value; ((JLabel) c).setText(dateFormat.format(simpleDate.getTime())); } } return c; } }); }
From source file:plugins.ImageRectificationPanel.java
public final void createGui() { this.removeAll(); if (imageGCPsXCoords == null) { return;/* w w w. j av a2 s .c o m*/ } int i; int newN = 0; for (i = 0; i < imageGCPsXCoords.length; i++) { if (useGCP[i]) { newN++; } } double[] X1 = new double[newN]; double[] Y1 = new double[newN]; double[] X2 = new double[newN]; double[] Y2 = new double[newN]; int j = 0; for (i = 0; i < imageGCPsXCoords.length; i++) { if (useGCP[i]) { X1[j] = imageGCPsXCoords[i]; Y1[j] = imageGCPsYCoords[i]; X2[j] = mapGCPsXCoords[i]; Y2[j] = mapGCPsYCoords[i]; j++; } } calculateEquations(X1, Y1, X2, Y2); // gui stuff this.setLayout(new BorderLayout()); DecimalFormat df = new DecimalFormat("###,###,##0.000"); JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS)); JButton btnOK = createButton(bundle.getString("OK"), bundle.getString("OK"), "ok"); JButton btnExit = createButton(bundle.getString("Close"), bundle.getString("Close"), "close"); //JButton btnRefresh = createButton("Cancel", "Cancel"); buttonPane.add(Box.createHorizontalStrut(10)); buttonPane.add(btnOK); buttonPane.add(Box.createHorizontalStrut(5)); //buttonPane.add(btnRefresh); buttonPane.add(Box.createHorizontalStrut(5)); buttonPane.add(btnExit); buttonPane.add(Box.createHorizontalGlue()); progressBar = new JProgressBar(0, 100); buttonPane.add(progressBar); buttonPane.add(Box.createHorizontalStrut(5)); cancel = new JLabel(bundle.getString("Cancel")); cancel.setForeground(Color.BLUE.darker()); cancel.addMouseListener(this); buttonPane.add(cancel); buttonPane.add(Box.createHorizontalStrut(10)); this.add(buttonPane, BorderLayout.SOUTH); Box mainBox = Box.createVerticalBox(); mainBox.add(Box.createVerticalStrut(10)); Box box1 = Box.createHorizontalBox(); box1.add(Box.createHorizontalStrut(10)); box1.add(new JLabel(bundle.getString("PolynomialOrder") + ": ")); SpinnerModel model = new SpinnerNumberModel(polyOrder, //initial value 1, //min 5, //max 1); //step polyOrderSpinner = new JSpinner(model); polyOrderSpinner.setPreferredSize(new Dimension(15, polyOrderSpinner.getPreferredSize().height)); polyOrderSpinner.addChangeListener(this); JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) polyOrderSpinner.getEditor(); editor.getTextField().setEnabled(true); editor.getTextField().setEditable(false); box1.add(polyOrderSpinner); box1.add(Box.createHorizontalGlue()); JLabel label = new JLabel("RMSE: " + df.format(overallRMSE)); box1.add(label); box1.add(Box.createHorizontalStrut(10)); mainBox.add(box1); mainBox.add(Box.createVerticalStrut(10)); // Create columns names int numPoints = imageGCPsXCoords.length; Object dataValues[][] = new Object[numPoints][7]; j = 0; for (i = 0; i < numPoints; i++) { dataValues[i][0] = i + 1; dataValues[i][1] = df.format(imageGCPsXCoords[i]); dataValues[i][2] = df.format(imageGCPsYCoords[i]); dataValues[i][3] = df.format(mapGCPsXCoords[i]); dataValues[i][4] = df.format(mapGCPsYCoords[i]); if (useGCP[i]) { dataValues[i][5] = df.format(residualsXY[j]); j++; } else { dataValues[i][5] = null; } dataValues[i][6] = useGCP[i]; } String columnNames[] = { "GCP", bundle.getString("Image") + " X", bundle.getString("Image") + " Y", bundle.getString("Map") + " X", bundle.getString("Map") + " Y", messages.getString("Error"), "Use" }; DefaultTableModel tableModel = new DefaultTableModel(dataValues, columnNames); dataTable = new JTable(tableModel) { private static final long serialVersionUID = 1L; @Override public Class getColumnClass(int column) { switch (column) { case 0: return Integer.class; case 1: return String.class; //Double.class; case 2: return String.class; //Double.class; case 3: return String.class; //Double.class; case 4: return String.class; //Double.class; case 5: return String.class; //Double.class; case 6: return Boolean.class; default: return String.class; //Double.class; } } @Override public Component prepareRenderer(TableCellRenderer renderer, int index_row, int index_col) { Component comp = super.prepareRenderer(renderer, index_row, index_col); //even index, selected or not selected if (index_row % 2 == 0) { comp.setBackground(Color.WHITE); comp.setForeground(Color.BLACK); } else { comp.setBackground(new Color(225, 245, 255)); //new Color(210, 230, 255)); comp.setForeground(Color.BLACK); } if (isCellSelected(index_row, index_col)) { comp.setForeground(Color.RED); } return comp; } }; tableModel.addTableModelListener(this); TableCellRenderer rend = dataTable.getTableHeader().getDefaultRenderer(); TableColumnModel tcm = dataTable.getColumnModel(); //for (int j = 0; j < tcm.getColumnCount(); j += 1) { TableColumn tc = tcm.getColumn(0); TableCellRenderer rendCol = tc.getHeaderRenderer(); // likely null if (rendCol == null) { rendCol = rend; } Component c = rendCol.getTableCellRendererComponent(dataTable, tc.getHeaderValue(), false, false, 0, 0); tc.setPreferredWidth(35); tc = tcm.getColumn(6); rendCol = tc.getHeaderRenderer(); // likely null if (rendCol == null) { rendCol = rend; } c = rendCol.getTableCellRendererComponent(dataTable, tc.getHeaderValue(), false, false, 0, 6); tc.setPreferredWidth(35); JScrollPane scroll = new JScrollPane(dataTable); mainBox.add(scroll); this.add(mainBox, BorderLayout.CENTER); this.validate(); }