下面列出了怎么用javax.swing.table.TableColumn的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* @Title : setHistTabWidth
* @Description: set history table width
* @Param : @param tab
* @Return : void
* @Throws :
*/
public static void setHistTabWidth(JTable tab)
{
int width[] = { 35, 260, 81, 144, 50, 80 };
TableColumnModel cols = tab.getColumnModel();
for (int i = 0; i < width.length; i++)
{
if (width[i] < 0)
{
continue;
}
TableColumn col = cols.getColumn(i);
if (i == 1 || i == 4 || i == 5)
{
col.setMinWidth(width[i]);
continue;
}
col.setMinWidth(width[i]);
col.setMaxWidth(width[i]);
}
}
private static int calcMaxWidth(JTable table) {
int colsNum = table.getColumnModel().getColumnCount();
int totalWidth = 0;
for (int col = 0; col < colsNum - 1; col++) {
TableColumn column = table.getColumnModel().getColumn(col);
int preferred = column.getPreferredWidth();
int width = Math.max(preferred, columnMaxWidth(table, col));
totalWidth += width;
column.setMinWidth(width);
column.setMaxWidth(width);
column.setWidth(width);
column.setPreferredWidth(width);
}
totalWidth += columnMaxWidth(table, colsNum - 1);
return totalWidth;
}
public void setColumnModel(DynamicTableColumnModel columnModel)
{
if (this.dynamicColumnModel != null)
{
this.dynamicColumnModel.removeDynamicTableColumnModelListener(listener);
}
this.dynamicColumnModel = columnModel;
columnModel.addDynamicTableColumnModelListener(listener);
super.setColumnModel(columnModel);
List<TableColumn> columns = columnModel.getAvailableColumns();
menu.getItems().clear();
if (!columns.isEmpty())
{
for (TableColumn column : columns)
{
menu.getItems().add(createMenuItem(column));
}
cornerButton.setVisible(true);
}
else
{
cornerButton.setVisible(false);
}
}
void apply(TableColumnModel tcm) {
int count = Math.min(tcm.getColumnCount(), widths.length);
for(int i = 0; i < count; i++) {
TableColumn col = tcm.getColumn(i);
col.setPreferredWidth(widths[col.getModelIndex()]);
col.setWidth(widths[col.getModelIndex()]);
}
int last = Math.min(tcm.getColumnCount(), order.length) - 1;
int idx = 0;
for(int i = last; i >= 0; i--) {
for(int j = 0; j <= i; j++) {
if(tcm.getColumn(j).getModelIndex() == order[idx]) {
tcm.moveColumn(j, last);
break;
}
}
idx++;
}
installListeners(tcm);
}
/**
* Creates and returns a JTable containing all the system properties. This method returns a
* table that is configured so that the user can sort the properties by clicking on the table
* header.
*
* @return a system properties table.
*/
public static SortableTable createSystemPropertiesTable() {
final SystemPropertiesTableModel properties = new SystemPropertiesTableModel();
final SortableTable table = new SortableTable(properties);
final TableColumnModel model = table.getColumnModel();
TableColumn column = model.getColumn(0);
column.setPreferredWidth(200);
column = model.getColumn(1);
column.setPreferredWidth(350);
table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
return table;
}
private TableColumn getResizingColumn(JTableHeader header, Point p, int column) {
if (column == -1) {
return null;
}
Rectangle r = header.getHeaderRect(column);
r.grow(-3, 0);
if (r.contains(p)) {
return null;
}
int midPoint = r.x + r.width / 2;
int columnIndex = 0;
if (header.getComponentOrientation().isLeftToRight()) {
columnIndex = (p.x < midPoint) ? column - 1 : column;
} else {
columnIndex = (p.x < midPoint) ? column : column - 1;
}
if (columnIndex == -1) {
return null;
}
return header.getColumnModel().getColumn(columnIndex);
}
private static JScrollPane createToggleButtonSelectionPane(JTable table, JTable rowheaderTable,
JToggleButton button)
{
rowheaderTable.setAutoCreateColumnsFromModel(false);
// force the tables to share models
rowheaderTable.setModel(table.getModel());
rowheaderTable.setSelectionModel(table.getSelectionModel());
rowheaderTable.setRowHeight(table.getRowHeight());
rowheaderTable.setIntercellSpacing(table.getIntercellSpacing());
rowheaderTable.setShowGrid(false);
rowheaderTable.setFocusable(false);
TableColumn column = new TableColumn(-1);
column.setHeaderValue(new Object());
column.setCellRenderer(new TableCellUtilities.ToggleButtonRenderer(button));
rowheaderTable.addColumn(column);
rowheaderTable.setPreferredScrollableViewportSize(new Dimension(20, 0));
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(table);
scrollPane.setRowHeaderView(rowheaderTable);
return scrollPane;
}
private boolean fireUpdateEvent(DefaultTableModel m, TableColumn column, Object status) {
if (status == Status.INDETERMINATE) {
List<?> data = m.getDataVector();
List<Boolean> l = data.stream()
.map(v -> (Boolean) ((List<?>) v).get(targetColumnIndex))
.distinct()
.collect(Collectors.toList());
boolean notDuplicates = l.size() == 1;
if (notDuplicates) {
boolean isSelected = l.get(0);
column.setHeaderValue(isSelected ? Status.SELECTED : Status.DESELECTED);
return true;
} else {
return false;
}
} else {
column.setHeaderValue(Status.INDETERMINATE);
return true;
}
}
private void rescaleTableColumns()
{
// iterate over all columns to resize them individually
TableColumnModel columnModel = previewTable.getColumnModel();
for(int columnIdx = 0; columnIdx < columnModel.getColumnCount(); ++columnIdx)
{
// get the current column
TableColumn column = columnModel.getColumn(columnIdx);
// get the renderer for the column header to calculate the preferred with for the header
TableCellRenderer renderer = column.getHeaderRenderer();
// check if the renderer is null
if(renderer == null)
{
// if it is null use the default renderer for header
renderer = previewTable.getTableHeader().getDefaultRenderer();
}
// create a cell to calculate its preferred size
Component comp = renderer.getTableCellRendererComponent(previewTable, column.getHeaderValue(), false, false, 0, columnIdx);
int width = comp.getPreferredSize().width;
// set the maximum width which was calculated
column.setPreferredWidth(width);
}
}
public Test6505027(JFrame main) {
Container container = main;
if (INTERNAL) {
JInternalFrame frame = new JInternalFrame();
frame.setBounds(OFFSET, OFFSET, WIDTH, HEIGHT);
frame.setVisible(true);
JDesktopPane desktop = new JDesktopPane();
desktop.add(frame, new Integer(1));
container.add(desktop);
container = frame;
}
if (TERMINATE) {
this.table.putClientProperty(KEY, Boolean.TRUE);
}
TableColumn column = this.table.getColumn(COLUMNS[1]);
column.setCellEditor(new DefaultCellEditor(new JComboBox(ITEMS)));
container.add(BorderLayout.NORTH, new JTextField());
container.add(BorderLayout.CENTER, new JScrollPane(this.table));
}
/**
* Creates a panel that contains a table based on the specified table model.
*
* @param model the table model to use when constructing the table.
*
* @return The panel.
*/
public static JPanel createTablePanel(TableModel model) {
JPanel panel = new JPanel(new BorderLayout());
JTable table = new JTable(model);
for (int columnIndex = 0; columnIndex < model.getColumnCount();
columnIndex++) {
TableColumn column = table.getColumnModel().getColumn(columnIndex);
Class c = model.getColumnClass(columnIndex);
if (c.equals(Number.class)) {
column.setCellRenderer(new NumberCellRenderer());
}
}
panel.add(new JScrollPane(table));
return panel;
}
@Override
public void setColumnCollapsed(Column column, boolean collapsed) {
if (!getColumnControlVisible()) {
return;
}
checkNotNullArgument(column, "column must be non null");
if (column.isCollapsed() != collapsed) {
column.setCollapsed(collapsed);
}
TableColumn tableColumn = getColumn(column);
if (tableColumn instanceof TableColumnExt) {
((TableColumnExt) tableColumn).setVisible(!collapsed);
}
}
/**
* From Stackoverflow: http://stackoverflow.com/a/17627497
*
* @param table
* The table to be resized
*/
public void resizeColumnWidth(JTable table) {
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
final TableColumnModel columnModel = table.getColumnModel();
for (int column = 0; column < table.getColumnCount(); column++) {
TableColumn tableColumn = columnModel.getColumn(column);
TableCellRenderer r = tableColumn.getHeaderRenderer();
if (r == null) {
r = table.getTableHeader().getDefaultRenderer();
}
Component component = r.getTableCellRendererComponent(table, tableColumn.getHeaderValue(), false, false, 0,
column);
int width = component.getPreferredSize().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 + 1, width);
}
tableColumn.setPreferredWidth(width);
}
}
private void setPrefferedColumnsSize() {
TableColumn col = table.getColumnModel().getColumn(0);
int width = 110;
col.setMinWidth(width);
col.setMaxWidth(width);
col.setPreferredWidth(width);
col = table.getColumnModel().getColumn(1);
width = 90;
col.setMinWidth(width);
col.setMaxWidth(width);
col.setPreferredWidth(width);
col = table.getColumnModel().getColumn(2);
width = 200;
col.setMinWidth(width);
col.setMaxWidth(width);
col.setPreferredWidth(width);
}
/**
* Get the dimension of this ColumnGroup.
*
* @param table the table the header is being rendered in
* @return the dimension of the ColumnGroup
*/
@SuppressWarnings("unchecked")
public Dimension getSize(JTable table) {
Component comp = renderer.getTableCellRendererComponent(
table, getHeaderValue(), false, false, -1, -1);
int height = comp.getPreferredSize().height;
int width = 0;
Iterator iter = v.iterator();
while (iter.hasNext()) {
Object obj = iter.next();
if (obj instanceof TableColumn) {
TableColumn aColumn = (TableColumn) obj;
width += aColumn.getWidth();
} else {
width += ((ColumnGroup) obj).getSize(table).width;
}
}
return new Dimension(width, height);
}
public void reloadData(Object aobj[][]) {
dataTableModel.setData(aobj);
columnCount = aobj[0].length;
Object obj = null;
Object obj1 = null;
boolean flag = false;
boolean flag1 = false;
Object aobj1[] = dataTableModel.getLongestRow();
if (aobj1 == null)
return;
for (int k = 0; k < visibleColumnCount; k++) {
TableColumn tablecolumn = table.getColumnModel().getColumn(k);
Component component = table.getTableHeader().getDefaultRenderer().getTableCellRendererComponent(null, tablecolumn.getHeaderValue(), false, false, 0, 0);
int i = component.getPreferredSize().width;
component = table.getDefaultRenderer(sorterTableModel.getColumnClass(k)).getTableCellRendererComponent(table, aobj1[k], false, false, 0, k);
int j = component.getPreferredSize().width;
tablecolumn.setPreferredWidth(Math.max(i, j));
}
}
public LogTable(JTextArea detailTextArea) {
super();
init();
_detailTextArea = detailTextArea;
setModel(new FilteredLogTableModel());
Enumeration columns = getColumnModel().getColumns();
int i = 0;
while (columns.hasMoreElements()) {
TableColumn col = (TableColumn) columns.nextElement();
col.setCellRenderer(new LogTableRowRenderer());
col.setPreferredWidth(_colWidths[i]);
_tableColumns[i] = col;
i++;
}
ListSelectionModel rowSM = getSelectionModel();
rowSM.addListSelectionListener(new LogTableListSelectionListener(this));
//setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
}
void hideColumn(TableColumn column, ProfilerTable table) {
hiddenColumnWidths.put(column.getModelIndex(), column.getWidth());
column.setMinWidth(0);
column.setMaxWidth(0);
int selected = table.getSelectedColumn();
if (selected != -1 && getColumn(selected).equals(column)) {
int newSelected = getPreviousVisibleColumn(selected);
getSelectionModel().setSelectionInterval(newSelected, newSelected);
}
if (table.isSortable()) {
ProfilerRowSorter sorter = table._getRowSorter();
int sortColumn = sorter.getSortColumn();
if (sortColumn == column.getModelIndex()) {
int newSortColumn = table.convertColumnIndexToView(sortColumn);
newSortColumn = getPreviousVisibleColumn(newSortColumn);
sorter.setSortColumn(getColumn(newSortColumn).getModelIndex());
}
}
}
private void setupTableColumns() {
TableColumn column = table.getColumnModel().getColumn(0);
PCellEditor editor = new PCellEditor(false, core);
PCellRenderer renderer = new PCellRenderer(false, core);
editor.setBackground(Color.gray);
renderer.setBackground(Color.lightGray);
column.setCellEditor(editor);
column.setCellRenderer(renderer);
Enumeration<TableColumn> colIt = table.getColumnModel().getColumns();
colIt.nextElement(); // first column is always labels
while (colIt.hasMoreElements()) {
TableColumn col = colIt.nextElement();
col.setCellEditor(new PCellEditor(true, core));
col.setCellRenderer(new PCellRenderer(true, core));
}
}
/**
* Method getColumn
*
* @param columnIndex
* @return
*/
public TableColumn getColumn(int columnIndex) {
TableColumn tableColumn;
try {
tableColumn = super.getColumn(columnIndex);
} catch(Exception ex) { // return an empty column if the columnIndex is not valid.
return new TableColumn();
}
String headerValue = (String) tableColumn.getHeaderValue();
if(headerValue==null) {
return tableColumn;
}
else if(headerValue.equals(rowName)&&(tableColumn.getModelIndex()==0)) {
tableColumn.setMaxWidth(labelColumnWidth);
tableColumn.setMinWidth(labelColumnWidth);
tableColumn.setResizable(false);
}
else {
tableColumn.setMinWidth(minimumDataColumnWidth);
}
return tableColumn;
}
/** @return the column position of the hidden column or -1 if the column is not hidden */
private int removeHiddenColumn(TableColumn column, boolean doShift) {
int hiddenIndex = -1;
for (int i = 0; i < hiddenColumns.size(); i++) {
if (column.equals(hiddenColumns.get(i))) {
hiddenIndex = i;
break;
}
}
if (hiddenIndex >= 0) {
hiddenColumns.remove(hiddenIndex);
int hi = hiddenColumnsPosition.remove(hiddenIndex);
if (doShift) {
int n = hiddenColumnsPosition.size();
for (int i = 0; i < n; i++) {
int index = hiddenColumnsPosition.get(i);
if (index > hi) {
hiddenColumnsPosition.set(i, --index);
}
}
}
return hi;
} else {
return -1;
}
}
public static void initializeTable(JTable table)
{
table.setAutoCreateColumnsFromModel(false);
JTableHeader header = table.getTableHeader();
TableColumnModel columns = new DefaultTableColumnModel();
TableCellRenderer headerRenderer = header.getDefaultRenderer();
columns.addColumn(Utilities.createTableColumn(0, "in_level", headerRenderer, false));
columns.addColumn(Utilities.createTableColumn(1, "in_class", headerRenderer, true));
TableColumn remainCol = Utilities.createTableColumn(2, "in_iskRemain", headerRenderer, false);
remainCol.setCellRenderer(new BoldNumberRenderer());
columns.addColumn(remainCol);
columns.addColumn(Utilities.createTableColumn(3, "in_gained", headerRenderer, false));
table.setDefaultRenderer(Integer.class, new TableCellUtilities.AlignRenderer(SwingConstants.CENTER));
table.setColumnModel(columns);
table.setFocusable(false);
header.setReorderingAllowed(false);
header.setResizingAllowed(false);
}
private void saveColumnSettings(Element columnElement, TableColumn column) {
TableModel tableModel = table.getUnwrappedTableModel();
if (!(tableModel instanceof ConfigurableColumnTableModel)) {
return;
}
ConfigurableColumnTableModel configurableTableModel =
(ConfigurableColumnTableModel) tableModel;
Settings settings = configurableTableModel.getColumnSettings(column.getModelIndex());
if (settings == null) {
return;
}
for (String name : settings.getNames()) {
Object value = settings.getValue(name);
if (value instanceof String) {
addSettingElement(columnElement, name, "String", (String) value);
}
else if (value instanceof Long) {
addSettingElement(columnElement, name, "Long", value.toString());
}
// else if (value instanceof byte[]) // we don't handle this case; OBE?
}
}
public static void store(final Storage storage, final JTable table) {
final TableColumnModel model = table.getTableHeader().getColumnModel();
final int columnCount = model.getColumnCount();
final boolean[] storedColumns = new boolean[columnCount];
Arrays.fill(storedColumns, false);
for (int i = 0; i < columnCount; i++) {
final TableColumn column = model.getColumn(i);
storage.put(widthPropertyName(i), String.valueOf(column.getWidth()));
final int modelIndex = column.getModelIndex();
storage.put(orderPropertyName(i), String.valueOf(modelIndex));
if (storedColumns[modelIndex]) {
LOG.error("columnCount: " + columnCount + " current: " + i + " modelINdex: " + modelIndex);
}
storedColumns[modelIndex] = true;
}
}
public ColorLegendTable(List<Pair<Color, String>> items) {
setModel(new TableModel(items));
// Make the table non-editable
setFocusable(false);
setRowSelectionAllowed(false);
setRowHeight(SizeHelper.getComponentHeightFromFont(getFont()));
setDefaultRenderer(Color.class, new ColorDataRenderer());
setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
// Make the table transparent
setShowGrid(false);
setOpaque(false);
DefaultTableCellRenderer renderer = (DefaultTableCellRenderer) getDefaultRenderer(Object.class);
renderer.setOpaque(false);
// Set the color cells square shape
TableColumnModel columnModel = getColumnModel();
int colorCellSize = getRowHeight();
TableColumn column = columnModel.getColumn(0);
column.setMinWidth(colorCellSize);
column.setMaxWidth(colorCellSize);
}
/**
* populates transforms of currently selected rule
*/
private void populateTransforms() {
DeclensionGenRule curRule = (DeclensionGenRule) lstRules.getSelectedValue();
transModel = new DefaultTableModel();
transModel.addColumn("Regex");
transModel.addColumn("Replacement");
tblTransforms.setModel(transModel);
// do not populate if multiple selections
if (lstRules.getSelectedIndices().length > 1) {
return;
}
boolean useConFont = !core.getPropertiesManager().isOverrideRegexFont();
TableColumn column = tblTransforms.getColumnModel().getColumn(0);
column.setCellEditor(new PCellEditor(useConFont, core));
column.setCellRenderer(new PCellRenderer(useConFont, core));
column = tblTransforms.getColumnModel().getColumn(1);
column.setCellEditor(new PCellEditor(useConFont, core));
column.setCellRenderer(new PCellRenderer(useConFont, core));
// do nothing if nothing selected in rule list
if (curRule == null) {
return;
}
DeclensionGenTransform[] curTransforms = curRule.getTransforms();
for (DeclensionGenTransform curTrans : curTransforms) {
Object[] newRow = {curTrans.regex, curTrans.replaceText};
transModel.addRow(newRow);
}
tblTransforms.setModel(transModel);
}
private void setImportLayoutTableColumnsWidth() {
if (importLayoutTable.getColumnCount() > 1) {
int tableWidth = importLayoutTable.getPreferredSize().width;
TableColumn column = importLayoutTable.getColumnModel().getColumn(0);
int colWidth = importLayoutTable.getTableHeader().getDefaultRenderer().getTableCellRendererComponent(importLayoutTable, column.getHeaderValue(), false, false, 0, 0).getPreferredSize().width;
column.setPreferredWidth(colWidth);
importLayoutTable.getColumnModel().getColumn(1).setPreferredWidth(tableWidth - colWidth);
}
}
private MainPanel() {
super(new BorderLayout());
table.setRowSorter(new TableRowSorter<>(model));
addProgressValue("Name 1", 100, null);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.getViewport().setBackground(Color.WHITE);
table.setComponentPopupMenu(new TablePopupMenu());
table.setFillsViewportHeight(true);
table.setIntercellSpacing(new Dimension());
table.setShowGrid(false);
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
TableColumn column = table.getColumnModel().getColumn(0);
column.setMaxWidth(60);
column.setMinWidth(60);
column.setResizable(false);
// addHierarchyListener(e -> {
// if ((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0 && !e.getComponent().isDisplayable()) {
// executor.shutdownNow();
// }
// });
JButton button = new JButton("add");
button.addActionListener(e -> addActionPerformed());
add(button, BorderLayout.SOUTH);
add(scrollPane);
setPreferredSize(new Dimension(320, 240));
}
private void setColumnEditors() {
TableColumnModel tcm = getColumnModel();
for (int i = 0; i < columnNames.length; i++) {
TableColumn tc = tcm.getColumn(i);
if (isColumnEditable(i)) {
tc.setCellEditor(valueCellEditor);
} else {
tc.setCellEditor(editor);
}
}
}
public static void getJTableOptions(final String name, final JTable table,
final Properties properties) {
final Integer colCount = getObjectInteger(name + "_col_count",
properties);
if (colCount == null || colCount.intValue() != table.getColumnCount())
return;
final String cNames[] = new String[table.getColumnCount()];
final Object cols[] = new Object[table.getColumnCount()];
for (int i = 0; i < cNames.length; i++) {
cNames[i] = table.getColumnName(i);
cols[i] = table.getColumnModel().getColumn(i);
}
for (final String element : cNames) {
final int width = getInteger(name + "_col_" + element + "_width",
table.getColumn(element).getWidth(), properties);
table.getColumn(element).setPreferredWidth(width);
}
final TableColumnModel cm = table.getColumnModel();
final int tci[] = new int[cNames.length];
for (int i = 0; i < cNames.length; i++)
cm.removeColumn((TableColumn) cols[i]);
for (int i = 0; i < cNames.length; i++) {
tci[i] = getInteger(name + "_col_" + cNames[i] + "_index", i,
properties);
}
for (int i = 0; i < cNames.length; i++)
for (int j = 0; j < cNames.length; j++)
if (tci[j] == i)
cm.addColumn((TableColumn) cols[j]);
}