⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 basictableui.java

📁 java jdk 1.4的源码
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
    /**     * Return the maximum size of the table. The maximum height is the     * row heighttimes the number of rows.     * The maximum width is the sum of the maximum widths of each column.     */    public Dimension getMaximumSize(JComponent c) {        long width = 0;        Enumeration enumeration = table.getColumnModel().getColumns();        while (enumeration.hasMoreElements()) {            TableColumn aColumn = (TableColumn)enumeration.nextElement();            width = width + aColumn.getMaxWidth();        }        return createTableSize(width);    }////  Paint methods and support//    /** Paint a representation of the <code>table</code> instance     * that was set in installUI().     */    public void paint(Graphics g, JComponent c) {	if (table.getRowCount() <= 0 || table.getColumnCount() <= 0) {	    return;	}	Rectangle clip = g.getClipBounds();	Point upperLeft = clip.getLocation();	Point lowerRight = new Point(clip.x + clip.width - 1, clip.y + clip.height - 1);        int rMin = table.rowAtPoint(upperLeft);        int rMax = table.rowAtPoint(lowerRight);        // This should never happen.        if (rMin == -1) {	    rMin = 0;        }        // If the table does not have enough rows to fill the view we'll get -1.        // Replace this with the index of the last row.        if (rMax == -1) {	    rMax = table.getRowCount()-1;        }        boolean ltr = table.getComponentOrientation().isLeftToRight();        int cMin = table.columnAtPoint(ltr ? upperLeft : lowerRight);         int cMax = table.columnAtPoint(ltr ? lowerRight : upperLeft);                // This should never happen.        if (cMin == -1) {	    cMin = 0;        }	// If the table does not have enough columns to fill the view we'll get -1.        // Replace this with the index of the last column.        if (cMax == -1) {	    cMax = table.getColumnCount()-1;        }        // Paint the grid.        paintGrid(g, rMin, rMax, cMin, cMax);        // Paint the cells.	paintCells(g, rMin, rMax, cMin, cMax);    }    /*     * Paints the grid lines within <I>aRect</I>, using the grid     * color set with <I>setGridColor</I>. Paints vertical lines     * if <code>getShowVerticalLines()</code> returns true and paints     * horizontal lines if <code>getShowHorizontalLines()</code>     * returns true.     */    private void paintGrid(Graphics g, int rMin, int rMax, int cMin, int cMax) {        g.setColor(table.getGridColor());	Rectangle minCell = table.getCellRect(rMin, cMin, true);	Rectangle maxCell = table.getCellRect(rMax, cMax, true);        Rectangle damagedArea = minCell.union( maxCell );        if (table.getShowHorizontalLines()) {	    int tableWidth = damagedArea.x + damagedArea.width;	    int y = damagedArea.y;	    for (int row = rMin; row <= rMax; row++) {		y += table.getRowHeight(row);		g.drawLine(damagedArea.x, y - 1, tableWidth - 1, y - 1);	    }	}        if (table.getShowVerticalLines()) {	    TableColumnModel cm = table.getColumnModel();	    int tableHeight = damagedArea.y + damagedArea.height;	    int x;	    if (table.getComponentOrientation().isLeftToRight()) {		x = damagedArea.x;		for (int column = cMin; column <= cMax; column++) {		    int w = cm.getColumn(column).getWidth();		    x += w;		    g.drawLine(x - 1, 0, x - 1, tableHeight - 1);		}	    } else {		x = damagedArea.x + damagedArea.width;		for (int column = cMin; column < cMax; column++) {		    int w = cm.getColumn(column).getWidth();		    x -= w;		    g.drawLine(x - 1, 0, x - 1, tableHeight - 1);		}		x -= cm.getColumn(cMax).getWidth();		g.drawLine(x, 0, x, tableHeight - 1);	    }	}    }    private int viewIndexForColumn(TableColumn aColumn) {        TableColumnModel cm = table.getColumnModel();        for (int column = 0; column < cm.getColumnCount(); column++) {            if (cm.getColumn(column) == aColumn) {                return column;            }        }        return -1;    }    private void paintCells(Graphics g, int rMin, int rMax, int cMin, int cMax) {	JTableHeader header = table.getTableHeader();	TableColumn draggedColumn = (header == null) ? null : header.getDraggedColumn();	TableColumnModel cm = table.getColumnModel();	int columnMargin = cm.getColumnMargin();        Rectangle cellRect;	TableColumn aColumn;	int columnWidth;	if (table.getComponentOrientation().isLeftToRight()) {	    for(int row = rMin; row <= rMax; row++) {		cellRect = table.getCellRect(row, cMin, false);                for(int column = cMin; column <= cMax; column++) {                    aColumn = cm.getColumn(column);                    columnWidth = aColumn.getWidth();                    cellRect.width = columnWidth - columnMargin;                    if (aColumn != draggedColumn) {                        paintCell(g, cellRect, row, column);                    }                    cellRect.x += columnWidth;        	}	    }	} else {	    for(int row = rMin; row <= rMax; row++) {                cellRect = table.getCellRect(row, cMin, false);                aColumn = cm.getColumn(cMin);                if (aColumn != draggedColumn) {                    columnWidth = aColumn.getWidth();                    cellRect.width = columnWidth - columnMargin;                    paintCell(g, cellRect, row, cMin);                }                for(int column = cMin+1; column <= cMax; column++) {                    aColumn = cm.getColumn(column);                    columnWidth = aColumn.getWidth();                    cellRect.width = columnWidth - columnMargin;                    cellRect.x -= columnWidth;                    if (aColumn != draggedColumn) {                        paintCell(g, cellRect, row, column);                    }        	}	    }	}        // Paint the dragged column if we are dragging.        if (draggedColumn != null) {	    paintDraggedArea(g, rMin, rMax, draggedColumn, header.getDraggedDistance());	}	// Remove any renderers that may be left in the rendererPane.	rendererPane.removeAll();    }    private void paintDraggedArea(Graphics g, int rMin, int rMax, TableColumn draggedColumn, int distance) {        int draggedColumnIndex = viewIndexForColumn(draggedColumn);        Rectangle minCell = table.getCellRect(rMin, draggedColumnIndex, true);	Rectangle maxCell = table.getCellRect(rMax, draggedColumnIndex, true);	Rectangle vacatedColumnRect = minCell.union(maxCell);	// Paint a gray well in place of the moving column.	g.setColor(table.getParent().getBackground());	g.fillRect(vacatedColumnRect.x, vacatedColumnRect.y,		   vacatedColumnRect.width, vacatedColumnRect.height);	// Move to the where the cell has been dragged.	vacatedColumnRect.x += distance;	// Fill the background.	g.setColor(table.getBackground());	g.fillRect(vacatedColumnRect.x, vacatedColumnRect.y,		   vacatedColumnRect.width, vacatedColumnRect.height);	// Paint the vertical grid lines if necessary.	if (table.getShowVerticalLines()) {	    g.setColor(table.getGridColor());	    int x1 = vacatedColumnRect.x;	    int y1 = vacatedColumnRect.y;	    int x2 = x1 + vacatedColumnRect.width - 1;	    int y2 = y1 + vacatedColumnRect.height - 1;	    // Left	    g.drawLine(x1-1, y1, x1-1, y2);	    // Right	    g.drawLine(x2, y1, x2, y2);	}	for(int row = rMin; row <= rMax; row++) {	    // Render the cell value	    Rectangle r = table.getCellRect(row, draggedColumnIndex, false);	    r.x += distance;	    paintCell(g, r, row, draggedColumnIndex);	    // Paint the (lower) horizontal grid line if necessary.	    if (table.getShowHorizontalLines()) {		g.setColor(table.getGridColor());		Rectangle rcr = table.getCellRect(row, draggedColumnIndex, true);		rcr.x += distance;		int x1 = rcr.x;		int y1 = rcr.y;		int x2 = x1 + rcr.width - 1;		int y2 = y1 + rcr.height - 1;		g.drawLine(x1, y2, x2, y2);	    }	}    }    private void paintCell(Graphics g, Rectangle cellRect, int row, int column) {        if (table.isEditing() && table.getEditingRow()==row &&                                 table.getEditingColumn()==column) {            Component component = table.getEditorComponent();	    component.setBounds(cellRect);            component.validate();        }        else {            TableCellRenderer renderer = table.getCellRenderer(row, column);            Component component = table.prepareRenderer(renderer, row, column);            rendererPane.paintComponent(g, component, table, cellRect.x, cellRect.y,                                        cellRect.width, cellRect.height, true);        }    }    private static final TableDragGestureRecognizer defaultDragRecognizer = new TableDragGestureRecognizer();    /**     * Drag gesture recognizer for JTable components     */    static class TableDragGestureRecognizer extends BasicDragGestureRecognizer {	/**	 * Determines if the following are true:	 * <ul>	 * <li>the press event is located over a selection	 * <li>the dragEnabled property is true	 * <li>A TranferHandler is installed	 * </ul>	 * <p>	 * This is implemented to perform the superclass behavior	 * followed by a check if the dragEnabled	 * property is set and if the location picked is selected.	 */        protected boolean isDragPossible(MouseEvent e) {	    if (super.isDragPossible(e)) {		JTable table = (JTable) this.getComponent(e);		if (table.getDragEnabled()) {		    Point p = e.getPoint();		    int row = table.rowAtPoint(p);		    int column = table.columnAtPoint(p);		    if ((column != -1) && (row != -1) && table.isCellSelected(row, column)) {			return true;		    }		}	    }	    return false;	}    }    private static DropTargetListener defaultDropTargetListener = null;    /**     * A DropTargetListener to extend the default Swing handling of drop operations     * by moving the tree selection to the nearest location to the mouse pointer.     * Also adds autoscroll capability.     */    static class TableDropTargetListener extends BasicDropTargetListener {	/**	 * called to save the state of a component in case it needs to	 * be restored because a drop is not performed.	 */        protected void saveComponentState(JComponent comp) {	    JTable table = (JTable) comp;	    rows = table.getSelectedRows();	    cols = table.getSelectedColumns();	}	/**	 * called to restore the state of a component	 * because a drop was not performed.	 */        protected void restoreComponentState(JComponent comp) {	    JTable table = (JTable) comp;	    table.clearSelection();	    for (int i = 0; i < rows.length; i++) {		table.addRowSelectionInterval(rows[i], rows[i]);	    }	    for (int i = 0; i < cols.length; i++) {		table.addColumnSelectionInterval(cols[i], cols[i]);	    }	}	/**	 * called to set the insertion location to match the current	 * mouse pointer coordinates.	 */        protected void updateInsertionLocation(JComponent comp, Point p) {	    JTable table = (JTable) comp;            int row = table.rowAtPoint(p);            int col = table.columnAtPoint(p);	    if (row != -1) {		table.setRowSelectionInterval(row, row);	    }	    if (col != -1) {		table.setColumnSelectionInterval(col, col);	    }	}	private int[] rows;	private int[] cols;    }    private static final TransferHandler defaultTransferHandler = new TableTransferHandler();    static class TableTransferHandler extends TransferHandler implements UIResource {	/**	 * Create a Transferable to use as the source for a data transfer.	 *	 * @param c  The component holding the data to be transfered.  This	 *  argument is provided to enable sharing of TransferHandlers by	 *  multiple components.	 * @return  The representation of the data to be transfered.	 *	 */        protected Transferable createTransferable(JComponent c) {	    if (c instanceof JTable) {		JTable table = (JTable) c;		int[] rows;		int[] cols;				if (!table.getRowSelectionAllowed() && !table.getColumnSelectionAllowed()) {		    return null;		}		                if (!table.getRowSelectionAllowed()) {                    int rowCount = table.getRowCount();                    rows = new int[rowCount];                    for (int counter = 0; counter < rowCount; counter++) {                        rows[counter] = counter;                    }                } else {		    rows = table.getSelectedRows();		}		                if (!table.getColumnSelectionAllowed()) {                    int colCount = table.getColumnCount();                    cols = new int[colCount];                    for (int counter = 0; counter < colCount; counter++) {                        cols[counter] = counter;                    }                } else {		    cols = table.getSelectedColumns();		}                		if (rows == null || cols == null || rows.length == 0 || cols.length == 0) {		    return null;		}                                StringBuffer plainBuf = new StringBuffer();                StringBuffer htmlBuf = new StringBuffer();                                htmlBuf.append("<html>\n<body>\n<table>\n");                                for (int row = 0; row < rows.length; row++) {                    htmlBuf.append("<tr>\n");                    for (int col = 0; col < cols.length; col++) {                        Object obj = table.getValueAt(rows[row], cols[col]);                        String val = ((obj == null) ? "" : obj.toString());                        plainBuf.append(val + "\t");                        htmlBuf.append("  <td>" + val + "</td>\n");                    }                    // we want a newline at the end of each line and not a tab                    plainBuf.deleteCharAt(plainBuf.length() - 1).append("\n");                    htmlBuf.append("</tr>\n");                }                // remove the last newline                plainBuf.deleteCharAt(plainBuf.length() - 1);                htmlBuf.append("</table>\n</body>\n</html>");                                return new BasicTransferable(plainBuf.toString(), htmlBuf.toString());	    }	    return null;	}        public int getSourceActions(JComponent c) {	    return COPY;	}    }    /**     * PropertyChangeListener for the table. Updates the appropriate     * varaible, or TreeState, based on what changes.     */    private class PropertyChangeHandler implements	               PropertyChangeListener {	public void propertyChange(PropertyChangeEvent event) {	    String changeName = event.getPropertyName();	    if (changeName.equals("componentOrientation")) {		InputMap inputMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);		SwingUtilities.replaceUIInputMap(table,				JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT,				inputMap);		UIManager.getLookAndFeelDefaults().put("Table.actionMap",                                                       null);		ActionMap actionMap = getActionMap();		SwingUtilities.replaceUIActionMap(table, actionMap);		JTableHeader header = table.getTableHeader();		if (header != null) {		    header.setComponentOrientation((ComponentOrientation)event.getNewValue());		}            } else if ("transferHandler".equals(changeName)) {                DropTarget dropTarget = table.getDropTarget();                if (dropTarget instanceof UIResource) {                    if (defaultDropTargetListener == null) {                        defaultDropTargetListener = new TableDropTargetListener();                    }                    try {                        dropTarget.addDropTargetListener(defaultDropTargetListener);                    } catch (TooManyListenersException tmle) {                        // should not happen... swing drop target is multicast                    }                }            }	}    } // End of BasicTableUI.PropertyChangeHandler}  // End of Class BasicTableUI

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -