简体   繁体   English

如何为JPanel添加空间,以使JScrollPane不在组件的顶部?

[英]How do I add space to a JPanel, so that JScrollPane doesn't sit on top of my components?

I have a JScrollPane and when I load my application the bar is sitting on top of one of my buttons. 我有一个JScrollPane,当我加载应用程序时,工具栏位于我的按钮之一上方。 What I would like to do is add some space to the side of my button so that the scroll bar draws over the space and not my button. 我想做的是在按钮的侧面添加一些空间,以便滚动条绘制空间而不是按钮。

Example code that I tried: 我尝试过的示例代码:

JPanel eButton = new JPanel(new BorderLayout());
JPanel spaceFiller = new JPanel();
spaceFiller.setSize(30, 10);
eButton.add(editButton, BorderLayout.EAST);
eButton.add(spaceFiller, BorderLayout.WEST);

The problem with this code is that it still overwrites my button and no space is added. 此代码的问题在于它仍然会覆盖我的按钮,并且没有添加任何空间。 What is the best way to make sure that JScrollPane doesn't overlap the components in my JFrame? 确保JScrollPane不与JFrame中的组件重叠的最佳方法是什么?

Thanks 谢谢

为了确保尊重JPanel的大小,您应该使用setPreferredSize()而不是setSize()。

In your sample code, didn't you reverse EAST and WEST? 在示例代码中,您没有反转EAST和WEST吗? Shouldn't it be like: 它不应该像这样:

eButton.add(editButton, BorderLayout.WEST); 
eButton.add(spaceFiller, BorderLayout.EAST); 

That would make more sense, sicne the scrollbar will appear on the right side (EAST). 这样会更有意义,因为滚动条将出现在右侧(EAST)。

Please note that the solution you suggest, even though it may work (after exchanging EAST and WEST) looks more like a hack than a real solution. 请注意,即使您建议的解决方案可能可行(在交换EAST和WEST之后)也可能看起来像黑客,而不是真正的解决方案。

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

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