简体   繁体   English

根据值调整JScrollPane中JList的大小

[英]Resize JList in a JScrollPane based on values

I have a JList in a JScrollPane: 我在JScrollPane中有一个JList:

JList list = new JList();
JScrollPane scrollPane = new JScrollPane(list,
                  JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                  JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBounds(0, 0, 201,75);

I need to resize the JList/JScrollPane based on the values in JList. 我需要根据JList中的值调整JList / JScrollPane的大小。 Etc: If values are long, JList/JScrollPane width is more, and if the values are short the width resizes to match the width. 等等:如果值长,则JList / JScrollPane宽度更大;如果值短,则宽度调整大小以匹配宽度。

Can anybody please point me in the right direction? 有人能指出我正确的方向吗?

I need to resize the JList/JScrollPane based on the values in JList. 我需要根据JList中的值调整JList / JScrollPane的大小。 Etc: If values are long, JList/JScrollPane width is more, and if the values are short the width resizes to match the width 等等:如果值长,则JList / JScrollPane宽度更大;如果值短,则宽度将调整大小以匹配宽度

  • its about override JScrollPane.getPreferredScrollableViewportSize , methods for JScrollPane , 它大约覆盖JScrollPane.getPreferredScrollableViewportSize ,对于方法JScrollPane

  • and to get longer text from JList , then to use 并从JList获取更长的文本,然后使用

.

SwingUtilities.computeStringWidth(JList.getFontMetrics(JList.getFont()), maxStringToComputeTheWidth);
  • don't to use NullLayout 不要使用NullLayout

The default behaviour for a JList is to make the list as wide as the largest string in the JList. JList的默认行为是使列表与JList中最大的字符串一样宽。 If this doesn't work for you it is because you are using a null layout and setBounds(). 如果这对您不起作用,那是因为您使用的是null布局和setBounds()。 DO NOT use setBounds(). 不要使用setBounds()。 Use a proper layout manager and let the layout manager do its job and keep your code simple. 使用适当的布局管理器,让布局管理器完成其工作,并使您的代码保持简单。

If you want to manually control the width of the list then you can use: 如果要手动控制列表的宽度,则可以使用:

list.setPrototypeCellValue("some string");

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

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