【发布时间】:2015-12-31 09:59:13
【问题描述】:
我有一个有 2 列的 JTable,我尝试实现以下目标:
如果第一列中某个单元格的值不适合该单元格,那么您会看到 3 个结束点。在这种情况下,我想调整列和表的大小,以便长值适合,以免改变第二列的宽度。将其视为向左扩展第一列。
示例代码:
/**
* Main.
*
* @param args arguments.
*/
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
String[] columnNames = {"First Name",
"Last Name"};
Object[][] data = {
{"Kathy Lathy Alberta 1234567890 11 12 13 14", "Smith"},
{"John", "Doe"},
{"Sue", "Black"},
{"Jane", "White"},
{"Joe", "Brown"}
};
// Create the table based on data and column names
JTable table = new JTable(new DefaultTableModel(data, columnNames));
// Set an initial size and add it to the main panel
table.setSize(300, 300);
panel.add(table);
// Compute the width of the first column, based on the longest value
int width = 0, row = 0;
for (row = 0; row < table.getRowCount(); row++) {
TableCellRenderer renderer = table.getCellRenderer(row, 0);
Component comp = table.prepareRenderer(renderer, row, 0);
width = Math.max (comp.getPreferredSize().width, width);
}
// Compute the value to be added to the width of the table
int initialWidth = table.getColumnModel().getColumn(0).getPreferredWidth();
int delta = width - initialWidth;
// Try to resize the table and the first column
table.setPreferredSize(new Dimension(table.getPreferredSize().width + delta, table.getHeight()));
table.getColumnModel().getColumn(0).setPreferredWidth(width);
frame.getContentPane().add(panel);
panel.setLayout(new BorderLayout());
panel.setPreferredSize(table.getPreferredSize());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(800, 300);
frame.setVisible(true);
}
会发生什么:
【问题讨论】:
-
JTable真的应该被包裹在JScrollPane中,更多详情请参阅How to Use Scroll Panes