Bạn có thể xây dựng LayoutManager của riêng bạn để căn giữa một thành phần đơn (cả trục hoặc chỉ một). Đây là một trong đó hiện nó trên cả hai trục, bạn có thể dễ dàng thay đổi nó để có trung tâm theo chiều dọc hoặc ngang.
Sơ đồ bố trí thực hiện hiện đầu tiên con có thể nhìn thấy, bạn có thể thay đổi điều đó quá ...
public class CentreLayout implements LayoutManager, java.io.Serializable {
public void addLayoutComponent(String name, Component comp) {
}
public void removeLayoutComponent(Component comp) {
}
public Dimension preferredLayoutSize(Container target) {
return target.getPreferredSize();
}
public Dimension minimumLayoutSize(Container target) {
return target.getMinimumSize();
}
public void layoutContainer(Container target) {
synchronized (target.getTreeLock()) {
Insets insets = target.getInsets();
Dimension size = target.getSize();
int w = size.width - (insets.left + insets.right);
int h = size.height - (insets.top + insets.bottom);
int count = target.getComponentCount();
for (int i = 0; i < count; i++) {
Component m = target.getComponent(i);
if (m.isVisible()) {
Dimension d = m.getPreferredSize();
m.setBounds((w - d.width)/2, (h - d.height)/2, d.width, d.height);
break;
}
}
}
}
}
Nguồn
2009-05-23 02:51:42
Tôi đã luôn tự hỏi làm thế nào để làm điều này, cuối cùng tôi đã từ bỏ và sử dụng MigLayout để thay thế. – gencoreoperative
Đây là những gì tôi nghĩ về gridbag: http://madbean.com/anim/totallygridbag/ :) – qben
GridBagLayout không HARD khi container nhỏ hơn kích thước ưa thích (nhưng lớn hơn kích thước tối thiểu) của trẻ. –