MiGLayout有很多吸引力,但BoxLayout
是一種替代方案。
![image](https://i.stack.imgur.com/eWMMF.png)
import java.awt.*;
import java.util.List;
import java.util.ArrayList;
import javax.swing.*;
public class BoxTest extends JPanel {
private List<JTextField> fields = new ArrayList<JTextField>();
public BoxTest() {
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.add(createPane(3, "One ", Color.red));
this.add(createPane(3, "Two ", Color.green));
this.add(createPane(10, "Three ", Color.blue));
}
private JPanel createPane(int n, String s, Color c) {
JPanel outer = new JPanel();
outer.setLayout(new BoxLayout(outer, BoxLayout.Y_AXIS));
outer.setBorder(BorderFactory.createLineBorder(c, 2));
for (int i = 0; i < n; i++) {
JPanel inner = new JPanel();
inner.setLayout(new BoxLayout(inner, BoxLayout.X_AXIS));
JLabel label = new JLabel(s + i + ":", JLabel.RIGHT);
label.setPreferredSize(new Dimension(80, 32));
inner.add(label);
JTextField tf = new JTextField("Stackoverflow!", 32);
inner.add(tf);
fields.add(tf);
outer.add(inner);
}
return outer;
}
private void display() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane jsp = new JScrollPane(this,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.validate();
Dimension d = this.getPreferredSize();
d.height /= 2;
jsp.getViewport().setPreferredSize(d);
jsp.getVerticalScrollBar().setUnitIncrement(
this.getPreferredSize().height/fields.size());
f.add(jsp);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new BoxTest().display();
}
});
}
}
我現在唯一的問題是,當一個框中的標籤不同時,文本框大小不同,就像http://grab.by/5gpW一樣。有沒有辦法解決這個問題,而不寫我自己的LayoutManager? – thepandaatemyface 2010-07-04 17:42:02
@thepandaatemyface:我更新了示例以顯示一種方法。 – trashgod 2010-08-02 15:54:30
@mKorbel使用_mot juste_:設置標籤的首選大小是一種隨意的破解。更精確的方法可能會使用[這裏]討論的技術之一找到最長的標籤(http://stackoverflow.com/questions/5979795/how-to-calculate-the-number-of-rows-and-columns-in - 每行-A-文本通吃的-AJ/5998117#5998117)。 – trashgod 2011-05-15 00:34:57