我目前正在设计一个使用Java Swing的计算器面板。然而,排列所有的按钮是一件非常痛苦的事情,因为每当我添加一个新按钮或改变按钮的大小时,它们都会自动调整大小和重新定位。
有没有一种布局或者什么东西可以“锁定”按钮的位置,这样当我移动/调整大小/添加其他按钮时,它们就不会受到影响?
谢谢,鲍勃
发布于 2009-05-15 19:05:43
延伸汤姆所说的..。
要使组件变得不可见但又保持其位置,您可以将其与空标签一起放置在CardLayout中,然后交换可见的组件。
您可以创建一个类来为您完成此操作,如下所示,main只显示了一个示例,其中如果您单击一个按钮,它将被删除,同时保留其位置。我放入showComponent/hideComponent和setVisible(t/f) -这取决于你喜欢的风格。
这可能不能完全满足您的需求,但可能对您的应用程序的一部分很有用。
public class Placeholder extends JPanel {
private static final long serialVersionUID = 1L;
private CardLayout cardLayout_;
public Placeholder(JComponent component) {
cardLayout_ = new CardLayout();
setLayout(cardLayout_);
add(component, "visible"); // the component
add(new JLabel(), "hidden"); // empty label
}
public void showComponent() {
cardLayout_.show(this, "visible");
}
public void hideComponent() {
cardLayout_.show(this, "hidden");
}
public void setComponentVisible(boolean visible) {
if (visible)
showComponent();
else
hideComponent();
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setLayout(new GridLayout(2,0));
for (int n = 1; n < 10; n++) {
JButton b = new JButton(n + "");
final Placeholder placeholder = new Placeholder(b);
f.add(placeholder);
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
placeholder.hideComponent();
}
});
}
f.pack();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setVisible(true);
}
}发布于 2009-05-15 18:35:43
我建议不要添加和删除按钮,而是更改它们的可见性属性(setVisible。某些布局管理器会忽略不可见的组件,因此您可能需要在与原始组件的首选/最小/最大尺寸相同的位置添加一个非选项(或匹配背景)组件。更简单的是,你可能想使用OverlayLayout。
发布于 2009-05-15 18:32:31
您可以使用GridBagLayout将它们保留在网格中,但允许它们调整大小
https://stackoverflow.com/questions/870171
复制相似问题