如果您使用的是 swing,我真的建议您使用 GridBag 布局。其他布局还有很多不足之处。这完全是一个偏好问题,如果你愿意,你可以手动布局——没有正确的答案。
我更喜欢 GridBag(或 MigLayout——每个人自己)的原因是你有一个组件的首选大小的概念和填充的概念。自从我编写 Swing 代码以来已经有一段时间了(我会尽量保持这种状态!)但你基本上是在寻找类似的东西:
{
//Pseudo Code, I'd have to go read the API again, I wrote a set of utilities so I wouldn't have to think about it.
GridBagConstraints constraints = ....;
constraints.weightX = 1.0; //fill the area by X
constraints.weightY = 1.0; //fill by Y
constraints.fill = GridBagConstraints.BOTH; //or one...
component.setPreferredSize(image.size());
layout.add(component, constraints);
}
基本上你正在做的是说“至少使用我喜欢的尺寸”,但根据这些规则填充。
不使用布局的替代方案只是自己定位组件(这绝对没有错)。
{
JPanel panel =...;
panel.setLayout(null);
...
myButton3.setX(0);
myButton3.setY(2 * buttonHeight); //third button
myButton.setSize(myButton.getPreferredSize()); //which I assume you set
...
panel.add(myButton3);
...
}
无论如何,有很多选择。不要觉得你需要使用布局,写你自己的。你应该关心这些事情并让它发挥作用,但你不应该受苦。布局通常很容易实现,你不应该害怕离开它。
话虽如此,GridBag 会做你想做的事。或者,Mig 很棒,并且有一些不错的 GUI 编辑器。
UPDATE -> ------------------- 这是一个简洁的例子——我真心不提倡这种编程风格,我只是不想要这个例子的垃圾邮件。
package _tests;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Grids extends JFrame
{
private static final long serialVersionUID = 1L;
public static void main(String ... args)
{
new Grids().setVisible(true);
}
public Grids()
{
//Null layout example
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(250, 300);
setMinimumSize(new Dimension(285, 300)); //Windows 8 ~ border size + scrollbar
setTitle("Test layouts");
JPanel scrollTarget = new JPanel()
{
private static final long serialVersionUID = 1L;
{
setSize(250, 1000);
setPreferredSize(new Dimension(250, 1000));
//setLayout(null); -- uncomment for absolute
setLayout(new GridBagLayout());
int lastX = 0;
int lastY = 0;
for(int i = 0; i < 5; i++)
{
final String label = "Button " + i;
JButton tmp = new JButton()
{
private static final long serialVersionUID = 1L;
{
setText(label);
setPreferredSize(new Dimension(250, 200)); //Preferred
}
};
tmp.setSize(tmp.getPreferredSize()); //What you're layout usually does..
//add(tmp);
//tmp.setLocation(lastX, lastY);
//lastY += tmp.getHeight();
add(tmp, getButtonConstraint(0, i));
}
}
};
add(new JScrollPane(scrollTarget));
}
private GridBagConstraints getButtonConstraint(int x, int y)
{
GridBagConstraints tmp = new GridBagConstraints();
tmp.fill = GridBagConstraints.BOTH;
tmp.weightx = 1.0;
tmp.weighty = 1.0;
tmp.gridx = x;
tmp.gridy = y;
tmp.anchor = GridBagConstraints.NORTHEAST;
return tmp;
}
}