java GridBagLayout 中最轻的间隔组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/935293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lightest-weight spacer component in a GridBagLayout
提问by dcstraw
In a GridBagLayout, what component is the best for providing empty space in a panel? Ideally I would like to use a component that has:
在 GridBagLayout 中,哪个组件最适合在面板中提供空白空间?理想情况下,我想使用具有以下特性的组件:
- Low overhead
- No side effect when no empty space is required (i.e. no minimum size)
- A trivial constructor (no parameters)
- 低开销
- 当不需要空白空间时没有副作用(即没有最小尺寸)
- 一个简单的构造函数(无参数)
A JPanel violates #2 above. A Box requires a constructor parameter (#3 above), which is really not necessary in this simple case. A JLabel works well but I worry that it may have some overhead, though admittedly it is probably pretty low.
JPanel 违反了上面的#2。一个 Box 需要一个构造函数参数(上面的#3),这在这个简单的情况下实际上是没有必要的。JLabel 运行良好,但我担心它可能会产生一些开销,尽管不可否认它可能很低。
An anonymous class also seems to work well (i.e. "new JComponent() { }"), but that adds an additional .class file every time I use it. I suppose it's no more overhead than any given event handler though. Would it be worth creating a custom, zero-implementation component derived from JComponent for this? Is there an existing component that I am missing?
匿名类似乎也运行良好(即“new JComponent() { }”),但是每次我使用它时都会添加一个额外的 .class 文件。我想它不会比任何给定的事件处理程序更多的开销。为此创建一个从 JComponent 派生的自定义零实现组件是否值得?是否有我遗漏的现有组件?
FYI GridBagLayout is one of my constraints on the team I'm part of, so other layouts are not an option.
仅供参考 GridBagLayout 是我对我所在团队的限制之一,因此其他布局不是一种选择。
回答by banjollity
You mention Box but it can be used in a "lightweight" fashion with the following four static methods that simply return a component. I use these all the time. They're invisible with respect to painting. In your case it looks like the glues are the way to go. A trivial constructor (like that's a bad thing!), low overhead. The side-effect when no space is required is all down to how you layout your gridbag.
您提到了 Box,但它可以通过以下四个简单地返回组件的静态方法以“轻量级”方式使用。我一直在使用这些。就绘画而言,它们是隐形的。在你的情况下,看起来胶水是要走的路。一个简单的构造函数(就像那是一件坏事!),低开销。不需要空间时的副作用完全取决于您如何布置网格包。
panel.add( Box.createHorizontalGlue() );
panel.add( Box.createVerticalGlue() );
panel.add( Box.createHorizontalStrut( int width ) );
panel.add( Box.createVerticalStrut( int width ) );
JavaDoc here: http://java.sun.com/javase/6/docs/api/javax/swing/Box.html
JavaDoc在这里:http: //java.sun.com/javase/6/docs/api/javax/swing/Box.html

