JButton扩展占用整个框架/容器
问题描述:
嘿大家。我试图用一个按钮和一个标签来制作一个图形用户界面。即时通讯使用边界布局和标签(在北方领域)显示正常,但按钮占据框架的其余部分(它在中心字段)。任何想法如何解决这个问题?JButton扩展占用整个框架/容器
答
您必须将按钮添加到另一个面板,然后将该面板添加到框架。
原来的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);
....
}
之前/之后
Before http://img372.imageshack.us/img372/2860/beforedl1.png After http://img508.imageshack.us/img508/341/aftergq7.png
答
再次:)
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);
}
}
答
或者只是使用绝对布局。它在Layouts Pallet上。
或用启用它:
frame = new JFrame();
... //your code here
// to set absolute layout.
frame.getContentPane().setLayout(null);
这样,您可以自由放置控制任何你喜欢的。
面板上的默认LayoutManger是什么?的FlowLayout? – 2008-11-23 02:23:49