[英]JPanel and GridBagLayout
我想在JPanel中動態放置按鈕。 為此,我選擇將GridBagLayout應用於此面板(一個包含按鈕的面板)。
問題是我的按鈕從面板的中央出現,而我希望它們從上到下放置。
這是我的代碼:
void placerListeUsers(){
jPanel49.setLayout(new GridBagLayout());
//jPanel49 est le panel sur lequel je place mes boutons.
//jPanel49 est placé dans une JScrollPane
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
//c.anchor=GridBagConstraints.NORTH;
c.weightx = 1;
//c.weighty = 0;
for (int i = 0; i < 5; i++) {
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridy = i;
jPanel49.add(new JButton("Super"), c);
}
以及他產生的東西:
感謝您幫助我解決此問題
問題是我的按鈕從面板的中央出現,而我希望它們從上到下放置。
您需要指定weightx / y約束,否則組件將聚集在中間。
閱讀有關如何使用GridBagLayout的Swing教程。 指定約束部分將為您提供更多信息。
在我看來,您只有垂直按鈕。 也許將GridLayout
或BoxLayout
添加到邊框的BorderLayout.PAGE_START
會更容易。
即使您沒有按要求提供MCVE。 我嘗試為您的布局提供解決方案...;)
問題是,正如camickr已經提到的那樣,在計算按鈕的大小之后,您需要告訴GridBagLayout在哪里將Panel的所有多余空間放在哪里:
對於添加到面板中的最后一個按鈕,需要將weighty設置為1。
public static void main(String[] args) { JFrame frame = new JFrame(); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); Container content = frame.getContentPane(); GridBagLayout layout = new GridBagLayout(); JPanel panel = new JPanel(layout); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.NORTH; c.weightx = 1; int buttonCount = 5; for (int i = 0; i < buttonCount; i++) { c.weighty = i == buttonCount - 1 ? 1 : 0; c.gridwidth = GridBagConstraints.REMAINDER; c.gridy = i; JButton button = new JButton("Super"); panel.add(button, c); } content.add(new JScrollPane(panel)); frame.pack(); frame.setSize(400, 400); frame.setVisible(true); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.