根据文本大小自动调整JTable列的大小 [英] Resizing JTable columns automatically based on text size

查看:62
本文介绍了根据文本大小自动调整JTable列的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JTable,其中有些字段包含长文本,有些字段包含小文本.

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.

我想知道两件事:

  1. 如何手动设置标题的宽度(例如名称,标题,姓氏)
  2. 如何根据文本自动调整它们的大小.

这是代码:

    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));

我看过 Swing教程,但是我要么一定错过了某件事,要么就不在那.

I have looked at the Swing Tutorials but I either must have missed something or it isn't there.

推荐答案

我认为通过defalut可以实现80像素,但是您可以通过以下方式更改它,例如...

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

编辑

第二个问题最好是在此处,请参阅许多有用的示例TableColumn

to your second question is better look here, please there are lots of usefull examples about TableColumn

这篇关于根据文本大小自动调整JTable列的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆