如何限制在窗体或面板的边框内动态添加组件
我正在尝试从数据库动态地将组件添加到 jpanel,一个接一个,但是它们水平超出了表单(甚至屏幕)的限制。我正在使用带有 BoxLayout 的面板,它将内部组件定位在 x 轴上。我想做的是限制在表单边框(或容器面板边框)的 x 轴上添加组件。 到目前为止我尝试的是:
- 设置最大尺寸(宽度) 容器 jpanel 但没有 工作。
- 将布局管理器设置为 flowlayout,但它也扩展了 在 x 轴上无限。
- 将容器面板放置在 滚动窗格。这使得一个巨大的 水平滚动条,这意味着 它不限制组件 表格的边框。
我应该制作自定义布局吗?还有比这更简单的想法吗? 我的代码如下所示:
jpanelCases.setLayout(new BoxLayout(this.jpanelCases, BoxLayout.X_AXIS));
db = Database.getInstance();
List<Category> cats = db.getCategories();
for(Category c : cats){
JPanel jp = new JPanel();
//addition of other components to the newly created panel here
jpanelCases.add(jp);
}
I am trying to add components to a jpanel dynamically from a database, one after the other, however they extend beyond the limits of the form (and even the screen) horizontally. I am using a panel with BoxLayout which positions inner components on the x-axis. What I would like to do is limit the addition of components on the x-axis at the border of the form (or the border of the container panel) .
What I tried so far is:
- To set the maximum size (width) of the
container jpanel but that did not
work. - To set the layout manager to
flowlayout, but it also expands
infinitely on the x-axis. - To position the container panel inside a
scrollpane. That makes a huge
horizontal scrollbar, which means that
it does not limit the components to
the border of the form.
Should I make a custom layout? Any ideas simpler than that?
My code looks like:
jpanelCases.setLayout(new BoxLayout(this.jpanelCases, BoxLayout.X_AXIS));
db = Database.getInstance();
List<Category> cats = db.getCategories();
for(Category c : cats){
JPanel jp = new JPanel();
//addition of other components to the newly created panel here
jpanelCases.add(jp);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那么在这种情况下你想做什么:
a) 忽略组件而不将它们添加到框架中
b) 在新行上显示组件
如果答案是“b”,则尝试 WrapLayout。
So what do you want to do in this case:
a) just ignore the components and not add them to the frame
b) display the components on a new line
If the answer is "b", the try the WrapLayout.
尝试涂两块胶水,先涂一层,最后涂一层:
Try to put 2 glues, one at first one at last:
在 JPanel 上使用 JScrollPane 怎么样?这将包含面板内的元素,但不会超出其物理边界。否则,如果您不喜欢滚动的想法,我建议您以某种方式跟踪添加到面板的元素相对于面板物理宽度的宽度总和,并在下一个元素宽度添加到总和时停止添加元素超过面板宽度。
我希望这有帮助!
What about using JScrollPane on the JPanel? This will contain the elements within the panel without exceeding its physical boundaries. Otherwise, if you do not like the scroll idea I suggest that you somehow keep track of the total sum of width of elements added to the panel with respect to the panel physical width, and stop adding elements when the next element width added to the sum exceeds the panel width.
I hope this helps!