下面列出了javax.swing.table.TableColumn#setPreferredWidth ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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 LogTable(final JTextArea detailTextArea) {
init();
_detailTextArea = detailTextArea;
setModel(new FilteredLogTableModel());
final Enumeration columns = getColumnModel().getColumns();
int i = 0;
while (columns.hasMoreElements()) {
final TableColumn col = (TableColumn) columns.nextElement();
col.setCellRenderer(new LogTableRowRenderer());
col.setPreferredWidth(_colWidths[i]);
_tableColumns[i] = col;
i++;
}
final ListSelectionModel rowSM = getSelectionModel();
rowSM.addListSelectionListener(new LogTableListSelectionListener(this));
//setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
}
@Override public void updateUI() {
// [JDK-6788475] Changing to Nimbus LAF and back doesn't reset look and feel of JTable completely - Java Bug System
// https://bugs.openjdk.java.net/browse/JDK-6788475
// XXX: set dummy ColorUIResource
setSelectionForeground(new ColorUIResource(Color.RED));
setSelectionBackground(new ColorUIResource(Color.RED));
setDefaultRenderer(Object.class, null);
super.updateUI();
putClientProperty("Table.isFileList", Boolean.TRUE);
setCellSelectionEnabled(true);
setIntercellSpacing(new Dimension());
setShowGrid(false);
setAutoCreateRowSorter(true);
setFillsViewportHeight(true);
TableCellRenderer r = new DefaultTableCellRenderer();
setDefaultRenderer(Object.class, (table, value, isSelected, hasFocus, row, column) ->
r.getTableCellRendererComponent(table, value, false, false, row, column));
TableColumn col = getColumnModel().getColumn(0);
col.setCellRenderer(new FileNameRenderer(this));
col.setPreferredWidth(200);
col = getColumnModel().getColumn(1);
col.setPreferredWidth(300);
}
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 setColWidth(int col, int w)
{
final TableModel model = table.getModel();
final TableCellRenderer headerRenderer =
table.getTableHeader().getDefaultRenderer();
if (col < model.getColumnCount()) {
final TableColumn column = table.getColumnModel().getColumn(col);
final Component headerComp =
headerRenderer.getTableCellRendererComponent(null,
column.getHeaderValue(),
false, false, 0, 0);
final int headerWidth = headerComp.getPreferredSize().width;
w = Math.max(headerWidth, w);
// totalWidth += w;
column.setMinWidth(10);
column.setMaxWidth(300);
column.setPreferredWidth(w);
}
}
private void setMyModel(Object[][] data, boolean canEdit) {
DisplayTableModel model = new DisplayTableModel(data,
canEdit,
editable > 2);
if(sortable) {
DisplayTableSorter sorter = new DisplayTableSorter(model);
setModel(sorter);
}
else {
setModel(model);
}
// PENDING - the column size does not shrink the way it should
TableColumnModel tcm = getColumnModel();
if (tcm.getColumnCount() > 0) {
TableColumn column = tcm.getColumn(0);
column.setPreferredWidth(10);
tcm.getColumn(2).setMaxWidth(5);
}
}
void setColumnsSize () {
int columnCount = model.getColumnCount ();
for (int i = 0; i < columnCount; i++) {
TableColumn activeColumn = getColumnModel ().getColumn (i);
activeColumn.setPreferredWidth (this.model.getPreferredWidth (getTableHeader (), i));
}
}
private void createEventInfoPanel() {
eventInfoPanel = new JPanel();
String[] colNames = {"Name", "Label"};
JTable table = new JTable(createData(), colNames);
table.setEnabled(false);
TableColumn firsetColumn = table.getColumnModel().getColumn(0);
firsetColumn.setPreferredWidth(12);
eventInfoPanel.setLayout(new BoxLayout(eventInfoPanel, BoxLayout.Y_AXIS));
eventInfoPanel.setBorder(GuiUtils.getTitledBorder("Parallel execution:"));
eventInfoPanel.add(table);
}
@Override
public boolean restoreColumnsConfig() {
Preconditions.checkState(table != null, "instance was detached, can't do much after that");
ArrayList<Pair<Integer, Integer>> cc = configPairs.find(keyId, null);
if (cc == null) {
return false;
}
TableColumnModel cm = table.getColumnModel();
for (int i = 0; i < cm.getColumnCount(); i++) {
int desiredColumnModelIndex = cc.get(i).getLeft();
if (cm.getColumn(i).getModelIndex() == desiredColumnModelIndex) {
continue;
}
int desiredColumnPhysicalindex = getColumnPhysicalindexByModelIndex(cm, desiredColumnModelIndex);
cm.moveColumn(desiredColumnPhysicalindex, i);
}
// xet sizes
for (int i = 0; i < cm.getColumnCount(); i++) {
TableColumn c = cm.getColumn(i);
c.setPreferredWidth(cc.get(i).getRight());
}
prevColumnsConfig = cc;
return true;
}
public void update() {
((AbstractTableModel) getModel()).fireTableStructureChanged();
TableColumnModel columnModel = getColumnModel();
for (int i = 0; i < columnModel.getColumnCount(); i++) {
TableColumn tableColumn = columnModel.getColumn(i);
tableColumn.setPreferredWidth(120);
}
}
public static void setupCheckboxColumn(@Nonnull TableColumn column) {
int checkboxWidth = new JCheckBox().getPreferredSize().width;
column.setResizable(false);
column.setPreferredWidth(checkboxWidth);
column.setMaxWidth(checkboxWidth);
column.setMinWidth(checkboxWidth);
}
/** Resize all columns in the table to fit widest row including header. */
public static void resizeColumns( JTable table) {
if (table.getGraphics() == null) {
return;
}
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
FontMetrics fm = table.getFontMetrics( renderer.getFont() );
TableColumnModel mod = table.getColumnModel();
for (int iCol = 0; iCol < mod.getColumnCount(); iCol++) {
TableColumn col = mod.getColumn( iCol);
int max = col.getPreferredWidth() - BUF;
String header = table.getModel().getColumnName( iCol);
if (header != null) {
max = Math.max( max, fm.stringWidth( header) );
}
for (int iRow = 0; iRow < table.getModel().getRowCount(); iRow++) {
Object obj = table.getModel().getValueAt(iRow, iCol);
String str = obj == null ? "" : obj.toString();
max = Math.max( max, fm.stringWidth( str) );
}
col.setPreferredWidth( max + BUF);
col.setMaxWidth( MAX);
}
table.revalidate();
table.repaint();
}
private void initTable() {
// Content Model & Renderer
tblPlugins.setModel(new PluginsTableModel());
//tblFolders.getC
// Columns
tblPlugins.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
TableColumn colActive = tblPlugins.getColumnModel().getColumn(PluginsTableModel.COLUMN_INDEX_ACTIVE);
colActive.setPreferredWidth(50);
colActive.setMaxWidth(50);
colActive.setResizable(false);
TableColumn colRemote = tblPlugins.getColumnModel().getColumn(PluginsTableModel.COLUMN_INDEX_NAME);
colRemote.setPreferredWidth(210);
TableColumn colLocal = tblPlugins.getColumnModel().getColumn(PluginsTableModel.COLUMN_INDEX_VERSION);
colLocal.setPreferredWidth(120);
// Other stuff
tblPlugins.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tblPlugins.setShowHorizontalLines(false);
tblPlugins.setShowVerticalLines(false);
tblPlugins.setBorder(BorderFactory.createEmptyBorder());
// Listeners
tblPlugins.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
btnDelete.setEnabled(e.getFirstIndex() >= 0);
}
});
}
private void createActionMap() {
String longestName = "";
actionsByFullName = KeyBindingUtils.getAllActionsByFullName(tool);
Set<Entry<String, List<DockingActionIf>>> entries = actionsByFullName.entrySet();
for (Entry<String, List<DockingActionIf>> entry : entries) {
// pick one action, they are all conceptually the same
List<DockingActionIf> actions = entry.getValue();
DockingActionIf action = actions.get(0);
tableActions.add(action);
String actionName = entry.getKey();
KeyStroke ks = options.getKeyStroke(actionName, null);
keyStrokesByFullName.put(actionName, ks);
addToKeyMap(ks, actionName);
originalValues.put(actionName, ks);
String shortName = action.getName();
if (shortName.length() > longestName.length()) {
longestName = shortName;
}
}
Font f = actionTable.getFont();
FontMetrics fm = actionTable.getFontMetrics(f);
int maxWidth = 0;
for (int i = 0; i < longestName.length(); i++) {
char c = longestName.charAt(i);
maxWidth += fm.charWidth(c);
}
TableColumn col = actionTable.getColumnModel().getColumn(ACTION_NAME);
col.setPreferredWidth(maxWidth);
tableModel.fireTableDataChanged();
}
private void updateTableUI() {
TableColumnModel columnModel = propertiesTable.getColumnModel();
columnModel.getColumn(0).setPreferredWidth(180);
TableColumn columnTwo = columnModel.getColumn(1);
columnTwo.setPreferredWidth(280);
columnTwo.setCellEditor(createCellEditor(getActivationConfigProperties()));
columnTwo.setCellRenderer(new ACPCellRenderer(getActivationConfigProperties()));
propertiesTable.setSelectionModel(new NullSelectionModel());
}
public void componentResized(ComponentEvent evt){
double pw = table.getParent().getParent().getSize().getWidth();
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumn column = table.getColumnModel().getColumn(0);
column.setWidth( ((int)pw/2) - 1 );
column.setPreferredWidth( ((int)pw/2) - 1 );
column = table.getColumnModel().getColumn(1);
column.setWidth( ((int)pw/2) - 1 );
column.setPreferredWidth( ((int)pw/2) - 1 );
}
void setViewColumnsWidth(JTable jt) {
/*
* Resize column 0, 1
*/
TableColumnModel colmodel = jt.getColumnModel();
TableColumn col0 = colmodel.getColumn(0);
col0.setPreferredWidth(200);
TableColumn col1 = colmodel.getColumn(1);
col1.setPreferredWidth(200);
return;
}
/**
* 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;
}
private void init() {
setOpaque( false );
getSelectionModel().clearSelection();
getSelectionModel().setAnchorSelectionIndex(-1);
getSelectionModel().setLeadSelectionIndex(-1);
setAutoscrolls( false );
setShowHorizontalLines(false);
setShowVerticalLines( false);
setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
setTableHeader( null );
// Calc row height here so that TableModel can adjust number of columns.
calcRowHeight(getOffscreenGraphics());
//mouse click into the table performs the switching
addMouseListener( new MouseAdapter() {
@Override
public void mousePressed( MouseEvent e ) {
int row = rowAtPoint( e.getPoint() );
int col = columnAtPoint( e.getPoint() );
if( row >= 0 && col >= 0 ) {
if( select( row, col ) ) {
performSwitching();
}
}
}
});
//icon for top-level items with sub-items
rightArrowLabel.setIcon( new ArrowIcon() );
rightArrowLabel.setIconTextGap( 2 );
rightArrowLabel.setHorizontalTextPosition( JLabel.LEFT );
topItemPanel.setLayout( new BorderLayout(5, 0) );
topItemPanel.add( rightArrowLabel, BorderLayout.EAST );
topItemPanel.getAccessibleContext().setAccessibleDescription( NbBundle.getMessage(Table.class, "ACD_OTHER_EDITORS") );
topItemPanel.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 2) );
//adjust column widths to accomodate the widest item in each column
for( int col=0; col<getColumnCount(); col++ ) {
if( getSwitcherModel().isTopItemColumn( col ) )
adjustColumnWidths( col );
}
//include the width of vertical scrollbar if there are too many rows
int maxRowCount = getSwitcherModel().getMaxRowCount();
if( maxRowCount > MAX_VISIBLE_ROWS && getRowCount() <= MAX_VISIBLE_ROWS ) {
JScrollPane scroll = new JScrollPane();
scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
int scrollWidth = scroll.getVerticalScrollBar().getPreferredSize().width;
TableColumn tc = getColumnModel().getColumn( getColumnCount()-1 );
tc.setMaxWidth( tc.getMaxWidth() + scrollWidth );
tc.setPreferredWidth( tc.getPreferredWidth() + scrollWidth );
tc.setWidth( tc.getWidth() + scrollWidth );
}
}
public QueryBuilderInputTable(QueryBuilder queryBuilder) {
super();
Log.getLogger().entering("QueryBuilderInputTable", "constructor"); // NOI18N
_queryBuilder = queryBuilder;
QueryBuilderInputTableModel queryBuilderInputTableModel = new QueryBuilderInputTableModel();
super.setModel( queryBuilderInputTableModel );
TableColumn column = this.getColumnModel().getColumn(Column_COLUMN);
column.setPreferredWidth(Column_COLUMN_WIDTH);
column = this.getColumnModel().getColumn(Alias_COLUMN);
column.setPreferredWidth(Alias_COLUMN_WIDTH);
column.setCellEditor(new FocusCellEditor(new JTextField()));
column = this.getColumnModel().getColumn(Table_COLUMN);
column.setPreferredWidth(Table_COLUMN_WIDTH);
column = this.getColumnModel().getColumn(SortType_COLUMN);
column.setPreferredWidth(SortType_COLUMN_WIDTH);
column = this.getColumnModel().getColumn(SortOrder_COLUMN);
column.setPreferredWidth(SortOrder_COLUMN_WIDTH);
column = this.getColumnModel().getColumn(Criteria_COLUMN);
column.setPreferredWidth(Criteria_COLUMN_WIDTH);
column.setCellEditor(new FocusCellEditor(new JTextField()));
column = this.getColumnModel().getColumn(CriteriaOrder_COLUMN);
column.setPreferredWidth(CriteriaOrder_COLUMN_WIDTH);
this.getColumnModel().getColumn(0).setCellEditor(
new FocusCellEditor(new JTextField()));
final Object[] sortTypeItems = {
"",
NbBundle.getMessage(QueryBuilderInputTable.class, "ASCENDING"), // NOI18N
NbBundle.getMessage(QueryBuilderInputTable.class, "DESCENDING") // NOI18N
};
TableColumn sortTypeColumn = this.getColumnModel().getColumn(SortType_COLUMN);
JComboBox sortTypeComboBox = new JComboBox(sortTypeItems);
sortTypeColumn.setCellEditor(new DefaultCellEditor(sortTypeComboBox));
sortTypeComboBox.addItemListener(this);
final Object[] sortOrderItems = {""}; // NOI18N
TableColumn sortOrderColumn = this.getColumnModel().getColumn(SortOrder_COLUMN);
_sortOrderComboBox = new JComboBox(sortOrderItems);
sortOrderColumn.setCellEditor(new DefaultCellEditor(_sortOrderComboBox));
_sortOrderComboBox.addItemListener(this);
final Object[] criteriaOrderItems = {""}; // NOI18N
TableColumn criteriaOrderColumn = this.getColumnModel().getColumn(CriteriaOrder_COLUMN);
_criteriaOrderComboBox = new JComboBox(criteriaOrderItems);
criteriaOrderColumn.setCellEditor(new DefaultCellEditor(_criteriaOrderComboBox));
// _criteriaOrderComboBox.addItemListener(this);
this.setAutoResizeMode (JTable.AUTO_RESIZE_OFF);
_inputTablePopup = createInputTablePopup();
MouseListener inputTablePopupListener = new InputTablePopupListener();
super.addMouseListener(inputTablePopupListener);
this.setMinimumSize(new Dimension (200, 200) );
this.setBackground(Color.white);
this.getTableHeader().setReorderingAllowed (false);
addKeyListener(this);
// this.getModel().addTableModelListener(this);
// Listen for checkbox selections in output column; handled by tableChange event instead
// TableColumn outputColumn = this.getColumnModel().getColumn(Output_COLUMN);
// JCheckBox outputCheckBox = new JCheckBox();
// outputColumn.setCellEditor(new DefaultCellEditor(outputCheckBox));
// outputCheckBox.addItemListener(this);
}