Resizing JTable columns automatically based on text size

[亡魂溺海] 提交于 2020-01-02 05:21:12

问题


I have a JTable with some fields with long text and some with little text.

By default, this is how it looks:

Notice how the "Name" and "Title" rows are not shortened.

I would like to know two things:

  1. How to manually set the width of Headers(Such as Name, Title, Surname)
  2. 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 Tutorials but I either must have missed something or it isn't there.


回答1:


I think that by defalut is there 80pixels, but you can change that with follows, for example ...

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




回答2:


2.How to automatically resize all of them depending on the text.

Check out the Table Column Adjuster.



来源:https://stackoverflow.com/questions/7033502/resizing-jtable-columns-automatically-based-on-text-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!