Java JButton 扩展以占据整个框架/容器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/311876/
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
JButton expanding to take up entire frame/container
提问by Michael Hoyle
Hey everyone. I'm trying to make a swing GUI with a button and a label on it. im using a border layout and the label ( in the north field ) shows up fine, but the button takes up the rest of the frame (it's in the center field). any idea how to fix this?
嘿大家。我正在尝试制作一个带有按钮和标签的摆动 GUI。我使用边框布局,标签(在北场)显示得很好,但按钮占据了框架的其余部分(它在中心场)。知道如何解决这个问题吗?
采纳答案by OscarRyz
You have to add the button to another panel, and then add that panel to the frame.
您必须将按钮添加到另一个面板,然后将该面板添加到框架中。
It turns out the BorderLayout expands what ever component is in the middle
事实证明 BorderLayout 扩展了中间的任何组件
Your code should look like this now:
你的代码现在应该是这样的:
Before
前
public static void main( String [] args ) {
JLabel label = new JLabel("Some info");
JButton button = new JButton("Ok");
JFrame frame = ...
frame.add( label, BorderLayout.NORTH );
frame.add( button , BorderLayout.CENTER );
....
}
Change it to something like this:
把它改成这样:
public static void main( String [] args ) {
JLabel label = new JLabel("Some info");
JButton button = new JButton("Ok");
JPanel panel = new JPanel();
panel.add( button );
JFrame frame = ...
frame.add( label, BorderLayout.NORTH );
frame.add( panel , BorderLayout.CENTER);
....
}
Before/After
之前/之后
Before http://img372.imageshack.us/img372/2860/beforedl1.pngAfter http://img508.imageshack.us/img508/341/aftergq7.png
http://img372.imageshack.us/img372/2860/beforedl1.png 之前 http://img508.imageshack.us/img508/341/aftergq7.png之后
回答by OscarRyz
Again :)
再次 :)
import javax.swing.*;
public class TestFrame extends JFrame {
public TestFrame() {
JLabel label = new JLabel("Some info");
JButton button = new JButton("Ok");
Box b = new Box(BoxLayout.Y_AXIS);
b.add(label);
b.add(button);
getContentPane().add(b);
}
public static void main(String[] args) {
JFrame f = new TestFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
回答by Aruman
Or just use Absolute layout. It's on the Layouts Pallet.
或者只是使用绝对布局。它位于布局托盘上。
Or enable it with :
或启用它:
frame = new JFrame();
... //your code here
// to set absolute layout.
frame.getContentPane().setLayout(null);
This way, you can freely place the control anywhere you like.
这样,您可以自由地将控件放置在您喜欢的任何位置。