2014-01-08 69 views
1

下面從Oracle tutorials複製和修改的地方比按鈕其它組分代碼組件(按鈕,複選框)的不一致放置 - 一個標籤和兩個文本字段和一個額外的按鈕。它產生它應該(如下圖所示)的形式,所以你不應該仔細檢查代碼的第30行左右:使用的GridBagLayout

enter image description here

如果我聯合國註釋掉兩行指到「框」並註釋掉與button相關的相鄰行,看看複選框的位置。

enter image description here

怎麼是怎麼回事我想不通。我想要最後一行上的複選框,因爲代碼SEEMS說它必須定位,但它不是。

所有我做的是改變兩行指的按鈕,而不是指複選框。 GridBagLayout組件依賴的規則是什麼? 我該怎麼做(爲什麼代碼沒有按原樣工作)將底線的複選框取消?

public class Testy { 
    public static void addComponentsToPane(Container pane) { 
     pane.setLayout(new GridBagLayout()); 
     GridBagConstraints c = new GridBagConstraints(); 
     c.fill = GridBagConstraints.HORIZONTAL; 
     c.weightx = 0.5; 
     c.gridx = 0;  c.gridy = 0; 
     JLabel label = new JLabel("Button 1 "); 
     pane.add(label, c); 
     JTextField text = new JTextField("Button 2 "); 
     c.gridx = 1;  c.gridy = 0; 
     pane.add(text, c); 
     JButton button = new JButton("Button 3 "); 
     c.gridx = 2;  c.gridy = 0; 
     pane.add(button, c); 
     text = new JTextField("LONG Text 4 "); 
     c.ipady = 40;  
     c.weightx = 0.0; 
     c.gridwidth = 3; 
     c.gridx = 0;  c.gridy = 1; 
     pane.add(text, c); 
     button = new JButton("5 "); 
     c.ipady = 0;  
     c.weighty = 1.0; 
     c.gridx = 1;  c.gridy = 2;  
     c.gridwidth = 2; 
     pane.add(button, c); 
// Here's the part of the code in question 
     button = new JButton("666"); // This placement is FINE, at bottom of form. 
    // JCheckBox box = new JCheckBox("Me?"); // "box" does NOT get placed on last line. 
     c.weighty = 0;  
     c.gridx = 0;  c.gridy = 3;  
     c.gridwidth = 1; 
    // pane.add(box); 
     pane.add(button, c); 
    } 

這裏是需要進口,這兩種方法,我除去,上述問題代碼區可以看到不滾動:

import java.awt.*; 
import javax.swing.JButton; 
import javax.swing.JCheckBox; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JTextField; 

    private static void createAndShowGUI() /* calls addComponentsToPane() */{ 
     JFrame frame = new JFrame("GridBagLayoutDemo"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
     addComponentsToPane(frame.getContentPane()); 
     frame.pack(); 
     frame.setVisible(true); 
    } 
    public static void main(String[] args) /* calls createAndShowGUI() */ { 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       createAndShowGUI(); 
      }  }); } 
} 

回答