java 根据文本大小自动调整 JTable 列的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7033502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Resizing JTable columns automatically based on text size
提问by David
I have a JTable with some fields with long text and some with little text.
我有一个 JTable,其中一些字段带有长文本,一些字段带有少量文本。
By default, this is how it looks:
默认情况下,它是这样的:
Notice how the "Name" and "Title" rows are not shortened.
请注意“名称”和“标题”行没有缩短。
I would like to know two things:
我想知道两件事:
- How to manually set the width of Headers(Such as Name, Title, Surname)
- How to automatically resize all of them depending on the text.
- 如何手动设置标题的宽度(如姓名、职务、姓氏)
- 如何根据文本自动调整所有大小。
Here is the code:
这是代码:
String[] columnNames = {"Name", "Title", "Surname", "ID"};
Object[][] testData = {
{"John", "Mr.", "Doe", "61020384U"},
};
nameTable = new JTable(testData, columnNames);
nameTable.setFont(new Font("Tahoma", Font.PLAIN, 11));
window.add(new JScrollPane(nameTable));
I have looked at the Swing Tutorialsbut I either must have missed something or it isn't there.
我看过Swing 教程,但我一定是漏掉了一些东西,或者它不存在。
回答by mKorbel
I think that by defalut is there 80pixels, but you can change that with follows, for example ...
我认为默认情况下有 80pixels,但您可以通过以下方式更改它,例如......
TableColumnModel tcm = myTable.getColumnModel();
tcm.getColumn(0).setPreferredWidth(100); //Name
tcm.getColumn(1).setPreferredWidth(40); //Title
tcm.getColumn(2).setPreferredWidth(400); //Surname
tcm.getColumn(3).setPreferredWidth(40); //ID
EDIT
编辑
to your second question is better look here, please there are lots of usefull examples about TableColumn
你的第二个问题最好看这里,请有很多关于 TableColumn 的有用例子
回答by camickr
2.How to automatically resize all of them depending on the text.
2.如何根据文本自动调整所有大小。
Check out the Table Column Adjuster.
查看表格列调整器。