javax.swing.JTable#getSelectedColumns ( )源码实例Demo

下面列出了javax.swing.JTable#getSelectedColumns ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: FlatLaf   文件: FlatTableCellBorder.java
/**
 * Checks whether at least one selected cell is editable.
 */
protected boolean isSelectionEditable( JTable table ) {
	if( table.getRowSelectionAllowed() ) {
		int columnCount = table.getColumnCount();
		int[] selectedRows = table.getSelectedRows();
		for( int selectedRow : selectedRows ) {
			for( int column = 0; column < columnCount; column++ ) {
				if( table.isCellEditable( selectedRow, column ) )
					return true;
			}
		}
	}

	if( table.getColumnSelectionAllowed() ) {
		int rowCount = table.getRowCount();
		int[] selectedColumns = table.getSelectedColumns();
		for( int selectedColumn : selectedColumns ) {
			for( int row = 0; row < rowCount; row++ ) {
				if( table.isCellEditable( row, selectedColumn ) )
					return true;
			}
		}
	}

	return false;
}
 
/**
 * Reads clipboard data and converts it into supported format and fills the
 * tmodel cells
 *
 * @param table the target tmodel
 */
private static void pasteFromClipboard(JTable table) {
    int startRow = table.getSelectedRows()[0];
    int startCol = table.getSelectedColumns()[0];
    String pasteString;
    try {
        pasteString = (String) (CLIPBOARD.getContents(CLIPBOARD).getTransferData(DataFlavor.stringFlavor));
    } catch (UnsupportedFlavorException | IOException ex) {
        Logger.getLogger(JtableUtils.class.getName()).log(Level.SEVERE, null, ex);
        return;
    }
    String[] lines = pasteString.split(LINE_BREAK);
    for (int i = 0; i < lines.length; i++) {
        String[] cells = lines[i].split(CELL_BREAK);
        if (table.getRowCount() <= startRow + i) {
            ((DefaultTableModel) table.getModel()).addRow(nullRow);
        }
        for (int j = 0; j < cells.length; j++) {
            if (table.getColumnCount() > startCol + j) {
                if (table.isCellEditable(startRow + i, startCol + j)) {
                    table.setValueAt(cells[j], startRow + i, startCol + j);
                }
            }
        }
    }
}
 
@Override
protected Transferable createTransferable(JComponent source) {
    JTable table = (JTable) source;
    if (table.getModel() instanceof TestDataModel) {
        TestDataModel tdm = (TestDataModel) table.getModel();
        TestDataDetail td = new TestDataDetail();
        td.setSheetName(tdm.getName());
        for (int col : table.getSelectedColumns()) {
            if (col > 3) {
                td.getColumnNames().add(table.getColumnName(col));
            }
        }
        return new TransferableNode(td, DataFlavors.TESTDATA_FLAVOR);
    }
    return null;
}
 
源代码4 项目: osp   文件: DataRowTable.java
/**
 *  returns a JLabel that is highlighted if the row is selected.
 *
 * @param  table
 * @param  value
 * @param  isSelected
 * @param  hasFocus
 * @param  row
 * @param  column
 * @return
 */
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
  if(table.isRowSelected(row)) {
    int[] i = table.getSelectedColumns();
    if((i.length==1)&&(table.convertColumnIndexToModel(i[0])==0)) {
      setBackground(PANEL_BACKGROUND);
    } else {
      setBackground(Color.gray);
    }
  } else {
    setBackground(PANEL_BACKGROUND);
  }
  if(value==null){ // added by W. Christian
	  setText("???");  //$NON-NLS-1$
  }else{
	  setText(value.toString());
  }
  return this;
}
 
public static void pasteFromAbove(JTable table) {
    int startRow = table.getSelectedRows()[0];
    int[] cols = table.getSelectedColumns();
    for (int col : cols) {
        table.setValueAt(table.getValueAt(startRow - 1, col), startRow, col);
    }
}
 
/**
 * clear selection by setting empty values
 *
 * @param table to be cleared
 */
private static void ClearSelection(JTable table) {
    int[] srow = table.getSelectedRows();
    int[] scol = table.getSelectedColumns();
    int lastSrow = srow.length;
    int lastScol = scol.length;
    for (int i = 0; i < lastSrow; i++) {
        for (int j = 0; j < lastScol; j++) {
            if (table.isCellEditable(srow[i], scol[j])) {
                table.setValueAt("", srow[i], scol[j]);
            }
        }
    }
}
 
/**
 * Reads the cell values of selected cells of the <code>tmodel</code> and
 * uploads into clipboard in supported format
 *
 * @param isCut CUT flag,<code>true</code> for CUT and <code>false</code>
 * for COPY
 * @param table the source for the action
 * @see #escape(java.lang.Object)
 */
private static void copyToClipboard(boolean isCut, JTable table) {
    try {
        int numCols = table.getSelectedColumnCount();
        int numRows = table.getSelectedRowCount();
        int[] rowsSelected = table.getSelectedRows();
        int[] colsSelected = table.getSelectedColumns();
        if (numRows != rowsSelected[rowsSelected.length - 1] - rowsSelected[0] + 1 || numRows != rowsSelected.length
                || numCols != colsSelected[colsSelected.length - 1] - colsSelected[0] + 1 || numCols != colsSelected.length) {
            JOptionPane.showMessageDialog(null, "Invalid Selection", "Invalid Selection", JOptionPane.ERROR_MESSAGE);
            return;
        }
        StringBuilder excelStr = new StringBuilder();
        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j < numCols; j++) {
                excelStr.append(escape(table.getValueAt(rowsSelected[i], colsSelected[j])));
                if (isCut) {
                    if (table.isCellEditable(rowsSelected[i], colsSelected[j])) {
                        table.setValueAt("", rowsSelected[i], colsSelected[j]);
                    }
                }
                if (j < numCols - 1) {
                    excelStr.append(CELL_BREAK);
                }
            }
            if (i < numRows - 1) {
                excelStr.append(LINE_BREAK);
            }
        }
        if (!excelStr.toString().isEmpty()) {
            StringSelection sel = new StringSelection(excelStr.toString());
            CLIPBOARD.setContents(sel, sel);
        }

    } catch (HeadlessException ex) {
        Logger.getLogger(JtableUtils.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
public static void copyToClipboard(JTable table, boolean isCut) {
    int numCols = table.getSelectedColumnCount();
    int numRows = table.getSelectedRowCount();
    int[] rowsSelected = table.getSelectedRows();
    int[] colsSelected = table.getSelectedColumns();
    if (numRows != rowsSelected[rowsSelected.length - 1] - rowsSelected[0] + 1 || numRows != rowsSelected.length
            || numCols != colsSelected[colsSelected.length - 1] - colsSelected[0] + 1 || numCols != colsSelected.length) {

        Logger.getLogger(XTableUtils.class.getName()).info("Invalid Copy Selection");
        return;
    }
    if (table.getModel() instanceof UndoRedoModel) {
        ((UndoRedoModel) table.getModel()).startGroupEdit();
    }

    StringBuilder excelStr = new StringBuilder();

    for (int i = 0; i < numRows; i++) {
        for (int j = 0; j < numCols; j++) {
            excelStr.append(escape(table.getValueAt(rowsSelected[i], colsSelected[j])));
            if (isCut) {
                table.setValueAt("", rowsSelected[i], colsSelected[j]);
            }
            if (j < numCols - 1) {
                excelStr.append(CELL_BREAK);
            }
        }
        excelStr.append(LINE_BREAK);
    }

    if (table.getModel() instanceof UndoRedoModel) {
        ((UndoRedoModel) table.getModel()).stopGroupEdit();
    }

    StringSelection sel = new StringSelection(excelStr.toString());

    CLIPBOARD.setContents(sel, sel);
}
 
public static void pasteFromClipboard(JTable table) {
    int startRow = table.getSelectedRows()[0];
    int startCol = table.getSelectedColumns()[0];

    String pasteString;
    try {
        pasteString = (String) (CLIPBOARD.getContents(null).getTransferData(DataFlavor.stringFlavor));
    } catch (Exception e) {
        Logger.getLogger(XTableUtils.class.getName()).log(Level.WARNING, "Invalid Paste Type", e);
        return;
    }
    if (table.getModel() instanceof UndoRedoModel) {
        ((UndoRedoModel) table.getModel()).startGroupEdit();
    }
    String[] lines = pasteString.split(LINE_BREAK);

    for (int i = 0; i < lines.length; i++) {
        String[] cells = lines[i].split(CELL_BREAK);
        for (int j = 0; j < cells.length; j++) {
            if (table.getRowCount() <= startRow + i) {
                if (table.getModel() instanceof DataModel) {
                    if (!((DataModel) table.getModel()).addRow()) {
                        return;
                    }
                }
            }
            if (table.getRowCount() > startRow + i && table.getColumnCount() > startCol + j) {
                table.setValueAt(cells[j], startRow + i, startCol + j);
            }
        }
    }
    if (table.getModel() instanceof UndoRedoModel) {
        ((UndoRedoModel) table.getModel()).stopGroupEdit();
    }
}
 
源代码10 项目: Repeat   文件: SwingUtil.java
public static void clearSelectedTable(JTable table) {
	int[] columns = table.getSelectedColumns();
	int[] rows = table.getSelectedRows();

	for (int i = 0; i < rows.length; i++) {
		for (int j = 0; j < columns.length; j++) {
			table.setValueAt("", rows[i], columns[j]);
		}
	}
}
 
源代码11 项目: osp   文件: DataTable.java
/**
 *  returns a JLabel that is highlighted if the row is selected.
 *
 * @param  table
 * @param  value
 * @param  isSelected
 * @param  hasFocus
 * @param  row
 * @param  column
 * @return
 */
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
  if(table.isRowSelected(row)) {
    int[] i = table.getSelectedColumns();
    if((i.length==1)&&(table.convertColumnIndexToModel(i[0])==0)) {
      setBackground(PANEL_BACKGROUND);
    } else {
      setBackground(Color.gray);
    }
  } else {
    setBackground(PANEL_BACKGROUND);
  }
  setText(value.toString());
  return this;
}
 
源代码12 项目: marathonv5   文件: RTable.java
private String getSelection() {
    JTable table = (JTable) component;
    boolean rowSelectionAllowed = table.getRowSelectionAllowed();
    boolean columnSelectionAllowed = table.getColumnSelectionAllowed();

    if (!rowSelectionAllowed && !columnSelectionAllowed) {
        return null;
    }

    int[] rows = table.getSelectedRows();
    int[] columns = table.getSelectedColumns();
    int rowCount = table.getRowCount();
    int columnCount = table.getColumnCount();

    if (rows.length == rowCount && columns.length == columnCount) {
        return "all";
    }

    if (rows.length == 0 && columns.length == 0) {
        return "";
    }

    StringBuffer text = new StringBuffer();

    text.append("rows:[");
    for (int i = 0; i < rows.length; i++) {
        text.append(rows[i]);
        if (i != rows.length - 1) {
            text.append(",");
        }
    }
    text.append("],");
    text.append("columns:[");
    for (int i = 0; i < columns.length; i++) {
        String columnName = getColumnName(columns[i]);
        text.append(escape(columnName));
        if (i != columns.length - 1) {
            text.append(",");
        }
    }
    text.append("]");
    return text.toString();
}
 
源代码13 项目: jeveassets   文件: MenuManager.java
private void selectClickedCell(final MouseEvent e) {
	Object source = e.getSource();
	if (source instanceof JTable) {
		JTable jSelectTable = (JTable) source;

		Point point = e.getPoint();
		if (!jSelectTable.getVisibleRect().contains(point)) { //Ignore clickes outside table
			return;
		}

		int clickedRow = jSelectTable.rowAtPoint(point);
		int clickedColumn = jSelectTable.columnAtPoint(point);

		//Rows
		boolean clickInRowsSelection;
		if (jSelectTable.getRowSelectionAllowed()) { //clicked in selected rows?
			clickInRowsSelection = false;
			int[] selectedRows = jSelectTable.getSelectedRows();
			for (int i = 0; i < selectedRows.length; i++) {
				if (selectedRows[i] == clickedRow) {
					clickInRowsSelection = true;
					break;
				}
			}
		} else { //Row selection not allowed - all rows selected
			clickInRowsSelection = true;
		}

		//Column
		boolean clickInColumnsSelection;
		if (jSelectTable.getColumnSelectionAllowed()) { //clicked in selected columns?
			clickInColumnsSelection = false;
			int[] selectedColumns = jSelectTable.getSelectedColumns();
			for (int i = 0; i < selectedColumns.length; i++) {
				if (selectedColumns[i] == clickedColumn) {
					clickInColumnsSelection = true;
					break;
				}
			}
		} else { //Column selection not allowed - all columns selected
			clickInColumnsSelection = true;
		}

		//Clicked outside selection, select clicked cell
		if ( (!clickInRowsSelection || !clickInColumnsSelection) && clickedRow >= 0 && clickedColumn >= 0) {
			jSelectTable.setRowSelectionInterval(clickedRow, clickedRow);
			jSelectTable.setColumnSelectionInterval(clickedColumn, clickedColumn);
		}
	}
}
 
源代码14 项目: jeveassets   文件: CopyHandler.java
private static void copy(JTable jTable) {
	//Rows
	int[] rows;
	if (jTable.getRowSelectionAllowed()) { //Selected rows
		rows = jTable.getSelectedRows();
	} else { //All rows (if row selection is not allowed)
		rows = new int[jTable.getRowCount()];
		for (int i = 0; i < jTable.getRowCount(); i++) {
			rows[i] = i;
		}
	}

	//Columns
	int[] columns;
	if (jTable.getColumnSelectionAllowed()) { //Selected columns
		columns = jTable.getSelectedColumns();
	} else { //All columns (if column selection is not allowed)
		columns = new int[jTable.getColumnCount()];
		for (int i = 0; i < jTable.getColumnCount(); i++) {
			columns[i] = i;
		}
	}
	StringBuilder tableText = new StringBuilder(); //Table text buffer
	String separatorText = ""; //Separator text buffer (is never added to, only set for each separator)
	int rowCount = 0; //used to find last row

	for (int row : rows) {
		rowCount++; //count rows
		StringBuilder rowText = new StringBuilder(); //Row text buffer
		boolean firstColumn = true; //used to find first column
		for (int column : columns) {
			//Get value
			Object value = jTable.getValueAt(row, column);

			//Handle Separator
			if (value instanceof SeparatorList.Separator) {
				SeparatorList.Separator<?> separator = (SeparatorList.Separator) value;
				Object object = separator.first();
				if (object instanceof CopySeparator) {
					CopySeparator copySeparator = (CopySeparator) object;
					separatorText = copySeparator.getCopyString();
				}
				break;
			}

			//Add tab separator (except for first column)
			if (firstColumn) {
				firstColumn = false;
			} else {
				rowText.append("\t");
			}

			//Add value
			if (value != null) { //Ignore null
				//Format value to displayed value
				if (value instanceof Float) {
					rowText.append(Formater.floatFormat(value));
				} else if (value instanceof Double) {
					rowText.append(Formater.doubleFormat(value));
				} else if (value instanceof Integer) {
					rowText.append(Formater.integerFormat(value));
				} else if (value instanceof Long) {
					rowText.append(Formater.longFormat(value));
				} else if (value instanceof Date) {
					rowText.append(Formater.columnDate(value));
				} else if (value instanceof HierarchyColumn) {
					HierarchyColumn hierarchyColumn = (HierarchyColumn) value;
					rowText.append(hierarchyColumn.getExport());
				} else {
					rowText.append(value.toString()); //Default
				}
			}
		}

		//Add
		if (rowText.length() > 0 || (!separatorText.isEmpty() && rowCount == rows.length)) {
			tableText.append(separatorText); //Add separator text (will be empty for normal tables)
			if (rowText.length() > 0 && !separatorText.isEmpty()) { //Add tab separator (if needed)
				tableText.append("\t");
			}
			tableText.append(rowText.toString()); //Add row text (will be empty if only copying sinlge separator)
			if (rowCount != rows.length) {
				tableText.append("\r\n");
			} //Add end line
		}
	}
	toClipboard(tableText.toString()); //Send it all to the clipboard
}
 
 方法所在类
 同类方法