在此JFrame
中帶有4列的GridBagLayout
,棕色線應爲列1和2之間的限制,並且「確定」和「取消」按鈕應位於此限制的兩側:GridBagLayout:柵格寬度大於1時的對齊和寬度
的問題:
- OK +取消設置不與其他按鍵居中。
- 左右
JTextArea
不具有相同的寬度。
當我期待第1列和第2列相等時,第1列似乎具有零寬度。
使用的代碼:
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class GblSO extends JFrame {
// Instance variables
GridBagConstraints gbc = new GridBagConstraints();
public GblSO() {
// Set frame
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
// Text areas
JTextArea left = new JTextArea("Left!");
JTextArea right = new JTextArea("Right!");
setConstraints(1, 1, GridBagConstraints.BOTH, null);
addToFrame(left, 0, 1, 1, 5, GridBagConstraints.CENTER);
addToFrame(right, 3, 1, 1, 5, GridBagConstraints.CENTER);
// Transfer buttons
JButton addBtn = new JButton(">");
JButton rmvBtn = new JButton("<");
setConstraints(0, 0, GridBagConstraints.NONE, new Insets(3, 5, 3, 5));
addToFrame(addBtn, 1, 1, 2, 1, GridBagConstraints.CENTER);
addToFrame(rmvBtn, 1, 3, 2, 1, GridBagConstraints.CENTER);
// OK/Cancel buttons
JButton okBtn = new JButton("OK");
JButton canBtn = new JButton("Cancel");
setConstraints(0, 0, GridBagConstraints.NONE, new Insets(15, 4, 15, 4));
addToFrame(okBtn, 0, 6, 2, 1, GridBagConstraints.EAST);
addToFrame(canBtn, 2, 6, 2, 1, GridBagConstraints.WEST);
// Show
pack();
setVisible(true);
}
private void setConstraints(double weightx, double weighty, int fill, Insets insets) {
gbc.weightx = weightx; // how much cell resizes
gbc.weighty = weighty; // "
gbc.fill = fill; // how component fills cell
gbc.insets = (insets == null ? new Insets(0, 0, 0, 0) : insets);
}
private void addToFrame(Component comp,
int gridx, int gridy, int gridwidth, int gridheight, int anchor) {
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.anchor = anchor;
add(comp, gbc);
}
public static void main(String[] args) {
new GblSO();
}
}
對於只有一個測試:如果我添加>
和<
按鈕將JFrame
分別在柱1和2,並且不跨越多個列,列1和2被迫具有相同的寬度,並且底部的按鈕現在居中。
代碼改爲:
addToFrame(addBtn, 1, 1, 1, 1, GridBagConstraints.CENTER);
addToFrame(rmvBtn, 2, 3, 1, 1, GridBagConstraints.CENTER);
結果:
兩個JTextArea
仍然有不同的寬度:-(,顯然>
和<
不會對齊
我該如何解決這個問題,使按鈕居中,而兩個JTextArea
有相同的寬度?感謝您的幫助。