下面列出了javax.swing.JTable#getColumnCount ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public TableSearcher(JTable table, String value, Function<Point,Void> functions){
this.action = functions;
this.found = new ArrayList<Point>();
index = -1;
for (int row = 0; row < table.getRowCount(); row++) {
for (int column = 0; column < table.getColumnCount(); column++) {
if (value.equals(getStringValueTable(table, row, column))) {
found.add(new Point(row, column));
}
}
}
if (!found.isEmpty()) {
index = 0;
}
}
private void updateDataTable() {
dataTable = new JTable();
dataTable.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
if(data != null) {
dataModel = new UmbelConceptTableModel(data);
dataTable.setModel(dataModel);
dataTable.setRowSorter(new TableRowSorter(dataModel));
dataTable.setColumnSelectionAllowed(false);
dataTable.setRowSelectionAllowed(true);
dataTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
TableColumn column = null;
for (int i=0; i < dataTable.getColumnCount(); i++) {
column = dataTable.getColumnModel().getColumn(i);
column.setPreferredWidth(dataModel.getColumnWidth(i));
}
tableScrollPane.setViewportView(dataTable);
}
}
/**
* Copy the selected row to clipboard
* @param table JTable
*/
private static void copyTableRowToClipboard(final JTable table) {
int row = table.getSelectedRow();
if(row != -1) {
String strCopy = "";
for(int column = 0; column < table.getColumnCount(); column++) {
Object selectedObject = table.getValueAt(row, column);
if(selectedObject instanceof String) {
if(column == 0) {
strCopy += (String)selectedObject;
} else {
strCopy += "," + (String)selectedObject;
}
}
}
StringSelection ss = new StringSelection(strCopy);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(ss, ss);
}
}
private List<HashMap<String, String>> getTableData(JTable table, String moduleId) {
List<HashMap<String, String>> data = new ArrayList<>();
HashMap<String, String> row;
JtableUtils.removeEmptyRows(table);
int colCount = table.getColumnCount(),
rowCount = table.getRowCount(), i;
for (i = 0; i < rowCount; i++) {
row = new HashMap<>();
row.put("moduleId", moduleId);
for (int j = 0; j < colCount; j++) {
Object val = table.getValueAt(i, j);
row.put(column[j], (val == null) ? "" : val.toString());
}
data.add(row);
}
return data;
}
/**
* create new header vector for modified tableModel * @param table target
* table
*
* @deprecated
* @param col target column
* @return the modified column model
*/
static Vector<String> getColumnIdentifiersremovecol(JTable table, int col) {
Vector<String> columnIdentifiers = new Vector<>();
int j = 0, colCount = table.getColumnCount();
while (j < colCount) {
columnIdentifiers.add(table.getColumnName(j));
j++;
}
columnIdentifiers.remove(col);
return columnIdentifiers;
}
@SuppressWarnings("serial")
public static JPanel makeTable(Border b, String border, Object[][] rowData, Object... colNames) {
JTable t = new JTable(rowData, colNames) {
@Override
public Dimension getPreferredScrollableViewportSize() {
Dimension d = getPreferredSize();
return new Dimension(Integer.max(640, d.width), (d.height));
}
};
JPanel p = new JPanel(new GridLayout(1, 1));
TableRowSorter<?> sorter = new MyTableRowSorter(t.getModel());
if (colNames.length > 0) {
sorter.toggleSortOrder(0);
}
t.setRowSorter(sorter);
sorter.allRowsChanged();
p.add(new JScrollPane(t));
for (int row = 0; row < t.getRowCount(); row++) {
int rowHeight = t.getRowHeight();
for (int column = 0; column < t.getColumnCount(); column++) {
Component comp = t.prepareRenderer(t.getCellRenderer(row, column), row, column);
rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
}
t.setRowHeight(row, rowHeight);
}
Font font = UIManager.getFont("TableHeader.font");
p.setBorder(BorderFactory.createTitledBorder(b, border, TitledBorder.DEFAULT_JUSTIFICATION,
TitledBorder.DEFAULT_POSITION, font, Color.black));
return p;
}
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();
}
}
/**
* setting up the table.
*
* @param table JTable to store this.correlationTableModel
*/
private void setupBasicTableProperties(JTable table) {
table.clearSelection();
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
TableRenderer cellRenderer = new TableRenderer(new JTextField());
table.setRowSelectionAllowed(true);
table.setColumnSelectionAllowed(false);
table.setVisible(true);
table.setModel(this.variationPerParameterTableModel);
initColumnSizes(table);
for (int i = 0; i < table.getColumnCount(); i++) {
TableColumn column = table.getColumnModel().getColumn(i);
column.setCellRenderer(cellRenderer);
}
TableColumn columnName = table.getColumnModel().getColumn(VariationPerParameterTableModel.COLUMN_NAME);
columnName.setCellEditor(new TextCellEditor());
TableColumn columnBasicValue = table.getColumnModel().getColumn(VariationPerParameterTableModel.COLUMN_BASIC_VALUE);
columnBasicValue.setCellEditor(new TextCellEditor());
setupVariationFunctionComboBoxColumn();
this.variationPerParameterTableModel.fireTableDataChanged();
table.setColumnSelectionAllowed(false);
table.setRowSelectionAllowed(true);
//select first row.
table.getSelectionModel().setSelectionInterval(0, 0);
}
public void adjustColumnPreferredWidths(JTable table) {
// Gets max width for cells in column as the preferred width
TableColumnModel columnModel = table.getColumnModel();
for (int col = 0; col < table.getColumnCount(); col++) {
int width = 45;
for (int row = 0; row < table.getRowCount(); row++) {
if (tableCellRenderer == null)
tableCellRenderer = table.getCellRenderer(row, col);
Component comp = table.prepareRenderer(tableCellRenderer, row, col);
width = Math.max(comp.getPreferredSize().width, width);
}
columnModel.getColumn(col).setPreferredWidth(width);
}
}
/**
* Adjust the row heights of a table based on the table contents.
*
* @param table adjusted table
*/
private void adjustRowHeights(JTable table) {
for (int row = 0; row < table.getRowCount(); row++) {
int rowHeight = table.getRowHeight();
for (int column = 0; column < table.getColumnCount(); column++) {
Component comp = table.prepareRenderer(table.getCellRenderer(row, column), row, column);
rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
}
table.setRowHeight(row, rowHeight);
}
}
private void printDebugData(JTable table) {
int numRows = table.getRowCount();
int numCols = table.getColumnCount();
javax.swing.table.TableModel model = table.getModel();
System.out.println("Value of data: ");
for (int i = 0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j = 0; j < numCols; j++) {
System.out.print(" " + model.getValueAt(i, j));
}
System.out.println();
}
System.out.println("--------------------------");
}
public static void findValue(JTable table, String value, Function<Point, Void> action) {
for (int row = 0; row < table.getRowCount(); row++) {
for (int column = 0; column < table.getColumnCount(); column++) {
if (value.equals(table.getValueAt(row, column))) {
action.apply(new Point(row, column));
}
}
}
}
public void resizeColumnWidth(JTable table) {
final TableColumnModel columnModel = table.getColumnModel();
for (int column = 0; column < table.getColumnCount(); column++) {
int width = 50; // Min width
for (int row = 0; row < table.getRowCount(); row++) {
TableCellRenderer renderer = table.getCellRenderer(row, column);
Component comp = table.prepareRenderer(renderer, row, column);
width = Math.max(comp.getPreferredSize().width, width);
}
columnModel.getColumn(column).setPreferredWidth(width);
columnModel.getColumn(column).setMinWidth(minColumnWidths[column]);
}
}
/**
* @param peaksInfoList
* @return
*/
private Dimension calculatedTableDimension(JTable peaksInfoList) {
int numRows = peaksInfoList.getRowCount();
int numCols = peaksInfoList.getColumnCount();
int maxWidth = 0, compWidth, totalWidth = 0, totalHeight = 0;
TableCellRenderer renderer = peaksInfoList.getDefaultRenderer(Object.class);
TableCellRenderer headerRenderer = peaksInfoList.getTableHeader().getDefaultRenderer();
TableModel model = peaksInfoList.getModel();
Component comp;
TableColumn column;
for (int c = 0; c < numCols; c++) {
for (int r = 0; r < numRows; r++) {
if (r == 0) {
comp = headerRenderer.getTableCellRendererComponent(peaksInfoList, model.getColumnName(c),
false, false, r, c);
compWidth = comp.getPreferredSize().width + 10;
maxWidth = Math.max(maxWidth, compWidth);
}
comp = renderer.getTableCellRendererComponent(peaksInfoList, model.getValueAt(r, c), false,
false, r, c);
compWidth = comp.getPreferredSize().width + 10;
maxWidth = Math.max(maxWidth, compWidth);
if (c == 0) {
totalHeight += comp.getPreferredSize().height;
}
// Consider max 10 rows
if (r == 8) {
break;
}
}
totalWidth += maxWidth;
column = peaksInfoList.getColumnModel().getColumn(c);
column.setPreferredWidth(maxWidth);
maxWidth = 0;
}
// add 30x10 px for a scrollbar
totalWidth += 30;
totalHeight += 10;
comp = headerRenderer.getTableCellRendererComponent(peaksInfoList, model.getColumnName(0),
false, false, 0, 0);
totalHeight += comp.getPreferredSize().height;
return new Dimension(totalWidth, totalHeight);
}
/**
*
* @param textComponent
* @param searchPhrase
* if matchCase is false, this must be uppercase
* @param forward
* @param matchCase
* @param wrapAround
* @param selection
* this 2-int array represents the [row, column] of the current
* selection, and will be modified to a new cell coordinate if
* this method returns true.
* @return true if the "selection" argument is now populated with the
* location of this search phrase
*/
private static boolean find(JTable table, String searchPhrase,
boolean forward, boolean matchCase, boolean wrapAround,
int[] selection) {
if (!matchCase)
searchPhrase = searchPhrase.toUpperCase();
int rowCount = table.getRowCount();
int columnCount = table.getColumnCount();
int currentRow = selection[0];
int currentColumn = selection[1];
if (currentRow == -1)
currentRow = 0;
if (currentColumn == -1)
currentColumn = 0;
int initialRow = currentRow;
int initialColumn = currentColumn;
while (true) {
if (forward) {
currentColumn++;
if (currentColumn == columnCount) {
currentColumn = 0;
currentRow++;
}
if (currentRow == rowCount) {
if (wrapAround) {
currentRow = 0;
} else {
return false;
}
}
} else {
currentColumn--;
if (currentColumn == -1) {
currentColumn = columnCount - 1;
currentRow--;
}
if (currentRow == -1) {
if (wrapAround) {
currentRow = rowCount - 1;
} else {
return false;
}
}
}
if (currentRow == initialRow && currentColumn == initialColumn) {
return false;
}
Object value = table.getModel().getValueAt(currentRow,
currentColumn);
String text = value == null ? "" : value.toString();
if (!matchCase) {
text = text.toUpperCase();
}
if (text.contains(searchPhrase)) {
selection[0] = currentRow;
selection[1] = currentColumn;
return true;
}
}
}
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column)
{
if (table == null)
{
return this;
}
if(column == table.getColumnCount() - 1)
{
setBorder(endColumnBorder);
}
else
{
setBorder(noramlBorder);
}
boolean isPaintingForPrint = false;
if(table.getTableHeader() != null)
{
isPaintingForPrint = table.getTableHeader().isPaintingForPrint();
}
Icon sortIcon = null;
if (!isPaintingForPrint && table.getRowSorter() != null)
{
SortOrder sortOrder = getColumnSortOrder(table, column);
if (sortOrder != null)
{
switch (sortOrder)
{
case ASCENDING:
sortIcon = UIManager.getIcon("Table.ascendingSortIcon");
break;
case DESCENDING:
sortIcon = UIManager.getIcon("Table.descendingSortIcon");
break;
case UNSORTED:
break;
}
}
}
setIcon(sortIcon);
setFont(table.getFont());
setValue(value);
return this;
}
/**
* Initialize the dialog's GUI components.
*
* @throws IOException Problem occurred getting JAR information
*/
private void initComponents()
throws IOException
{
JarFile[] jarFiles = getClassPathJars();
// JAR Information table
// Create the table using the appropriate table model
JarInfoTableModel jiModel = new JarInfoTableModel();
jiModel.load(jarFiles);
JTable jtJarInfo = new JTable(jiModel);
jtJarInfo.setRowMargin(0);
jtJarInfo.getColumnModel().setColumnMargin(0);
jtJarInfo.getTableHeader().setReorderingAllowed(false);
jtJarInfo.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
jtJarInfo.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// Add custom renderers for the table cells and headers
for (int iCnt = 0; iCnt < jtJarInfo.getColumnCount(); iCnt++)
{
TableColumn column = jtJarInfo.getColumnModel().getColumn(iCnt);
column.setPreferredWidth(150);
column.setHeaderRenderer(new JarInfoTableHeadRend());
column.setCellRenderer(new JarInfoTableCellRend());
}
// Make the table sortable
jtJarInfo.setAutoCreateRowSorter(true);
// ...and sort it by jar file by default
jtJarInfo.getRowSorter().toggleSortOrder(0);
// Put the table into a scroll pane
JScrollPane jspJarInfoTable = new JScrollPane(jtJarInfo, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jspJarInfoTable.getViewport().setBackground(jtJarInfo.getBackground());
// Put the scroll pane into a panel
JPanel jpJarInfoTable = new JPanel(new BorderLayout(10, 10));
jpJarInfoTable.setPreferredSize(new Dimension(500, 150));
jpJarInfoTable.add(jspJarInfoTable, BorderLayout.CENTER);
jpJarInfoTable.setBorder(new EmptyBorder(5, 5, 5, 5));
JButton jbOK = getOkButton(true);
JPanel jpOK = new JPanel(new FlowLayout(FlowLayout.CENTER));
jpOK.add(jbOK);
getContentPane().add(jpJarInfoTable, BorderLayout.CENTER);
getContentPane().add(jpOK, BorderLayout.SOUTH);
getRootPane().setDefaultButton(jbOK);
initDialog();
jbOK.requestFocusInWindow();
}
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();
}
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
}
/**
* Resizes the table columns based on the column and data preferred widths.
* @param table the original table
* @param model the data model
* @return the table itself
*/
public static JTable autoResizeColWidth(JTable table, AbstractTableModel model) {
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setModel(model);
int margin = 5;
for (int i = 0; i < table.getColumnCount(); i++) {
int vColIndex = i;
DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
TableColumn col = colModel.getColumn(vColIndex);
int width;
// Get width of column header
TableCellRenderer renderer = col.getHeaderRenderer();
if (renderer == null) {
renderer = table.getTableHeader().getDefaultRenderer();
}
Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);
width = comp.getPreferredSize().width;
// Get maximum width of column data
for (int r = 0; r < table.getRowCount(); r++) {
renderer = table.getCellRenderer(r, vColIndex);
comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false,
r, vColIndex);
width = Math.max(width, comp.getPreferredSize().width);
}
// Add margin
width += 2 * margin;
// Set the width
col.setPreferredWidth(width);
}
((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(
SwingConstants.LEFT);
return table;
}