简体   繁体   English

Java Swing JTable和JScrollPane适应列宽

[英]Java Swing JTable and JScrollPane to Fit Column Width

I am a newbie in Swing and I am using a JTable object in order to display some information. 我是Swing的新手,并且正在使用JTable对象以显示一些信息。 Basically the frame contains a JPanel -> GridBagLayout manager. 基本上,框架包含一个JPanel-> GridBagLayout管理器。 The JPanel contains a JLabel ("Status Table"), a JScrollPane which contains the JTable, the "Sort by" JButton and a JComboBox. JPanel包含一个JLabel(“状态表”),一个JScrollPane(包含JTable),“ Sort by” JButton和JComboBox。

How can I set the width of the columns/ column headers in order to completely display the text contained in them? 如何设置列/列标题的宽度以完全显示其中包含的文本?

I tried to use 我尝试使用

table.getColumnModel().getColumn(i).setPreferredWidth(my_width); 

but the problem is that in order to achieve the results I want, the sum of all the columns' widths is larger than the JScrollPane's width, so nothing will happen, they will remain the same as before. 但是问题是,为了获得我想要的结果,所有列的宽度之和大于JScrollPane的宽度,因此什么也不会发生,它们将保持与以前相同。

I tried to use the setSize method for JScrollPane in order to resize it to be as large as the window... but because of the GridBagLayout manager it seems that it cannot get larger than a certain size, which still doesn't fit the text. 我尝试对JScrollPane使用setSize方法以将其调整为与窗口一样大的大小...但是由于GridBagLayout管理器,看来它不能变得大于一定的大小,这仍然不适合文本。

Additional info: The JTable is built from a model that I've implemented and the only GridBagConstraints that I've modified are gridx, gridy and fill = BOTH. 附加信息:JTable是基于我已经实现的模型构建的,并且我修改的唯一GridBagConstraints是gridx,gridy和fill = BOTH。

表

See the Table Column Adjuster for an easy way to size each column. 有关调整每个列大小的简便方法,请参见表列调整器。

Only the table should be added to the scrollpane. 仅应将表添加到滚动窗格。 You may also need to use: 您可能还需要使用:

table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );

To allow each column to be displayed at its preferred size. 允许每列以其首选大小显示。

the sum of all the columns' widths is larger than the JScrollPane's width, so nothing will happen, 所有列的宽度之和大于JScrollPane的宽度,因此不会发生任何事情,

You have a problem with the gridbag constaints. 您对gridbag容器有问题。 The component should grow to fill all the space. 组件应增长以填充所有空间。 Maybe it will be easier to use a BorderLayout. 也许使用BorderLayout会更容易。 Add the scrollpane to the center and add the other components to the north/south. 将滚动窗格添加到中心,并将其他组件添加到北/南。 You can nest panels with different layout managers to get your desired layout. 您可以将面板与不同的布局管理器嵌套在一起,以获得所需的布局。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM