JButton扩展到占据整个框架/容器
-
10-07-2019 - |
题
嘿大家好我正在尝试使用按钮和标签制作一个swing GUI。即时通讯使用边框布局和标签(在北方字段中)显示正常,但按钮占据框架的其余部分(它在中心字段中)。任何想法如何解决这个问题?
解决方案
您必须将按钮添加到另一个面板,然后将该面板添加到框架中。
事实证明,BorderLayout扩展了组件在中间的内容
您的代码现在应该如下所示:
在
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 );
....
}
将其更改为:
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);
....
}
之前/之后
在http://img372.imageshack.us/img372/2860/beforedl1.png之前 http://img508.imageshack.us/img508/341/aftergq7.png 之后
其他提示
或者只使用绝对布局。它位于Layouts托盘上。
或者启用它:
frame = new JFrame();
... //your code here
// to set absolute layout.
frame.getContentPane().setLayout(null);
这样,您可以随意将控件放在任何地方。
再次:)
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);
}
}
不隶属于 StackOverflow