2013-03-13 38 views
1

如何在gridlayout中設置jbutton的大小?否則按鈕大小有很多寬度,並且它不監聽setSize或setBounds或setPreferedSize。在gridLayout中設置JButton大小

addBut = new JButton("Add"); 

    addBut.addActionListener(this); 
    deleteBut = new JButton("Delete"); 
    deleteBut.addActionListener(this); 
    selectionPanel = new JPanel(); 
    selectionPanel.setLayout(new GridLayout(2,2)); 
    TitledBorder selectionBorder = new TitledBorder("Options"); 
    selectionBorder.setTitleColor(Color.BLUE); 
    selectionPanel.setBorder(selectionBorder); 
    selectionPanel.add(new JLabel("Department Name")); 
    selectionPanel.add(new JTextField(deptName)); 
    selectionPanel.add(addBut); 
    selectionPanel.add(deleteBut); 

    selectionPanel.setPreferredSize(new Dimension(900,100)); 
+0

爲了更快得到更好的幫助,請以'最小'和'更大'的尺寸發佈GUI的[SSCCE](http://sscce.org/)和ASCII藝術。 – 2013-03-14 01:19:19

回答

2

我相信設置GridLayout(2,2)將覆蓋面板的大小更改。更確切地說,使用GridBagConStraints;

private JTextField field1 = new JTextField(); 
private JButton addBtn = new JButton("Save: "); 

public void addComponents(Container pane) { 
     pane.setLayout(new GridBagLayout()); 
     GridBagConstraints c = new GridBagConstraints(); 
// Components 
    c.gridwidth = 1; 
    c.weightx = .01; 
    c.weighty = .2; 
    c.gridx = 0; 
    c.gridy = 1; 
    pane.add(field1, c); 

     c.gridwidth = 1; 
    c.weightx = .01; 
    c.weighty = .2; 
    c.gridx = 0; 
    c.gridy = 1; 
    pane.add(addBtn, c); 
} 
public MainView() { 
     //Create and set up the window. 
     JFrame frame = new JFrame("NAME"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     //Set up the content pane. 
     addComponents(frame.getContentPane()); 

     //Display the window. 
     frame.pack(); 
     frame.setVisible(true); 
     frame.setResizable(false); 
     frame.setSize(400, 125); 
     frame.setLocation(400, 300); 
    } 
+0

如果我設置了約束條件,所有東西都會變成不同的大小,你能不能請更新我的猜測約束代碼,我正在尋找標籤和textfiled在第一行和2個按鈕在下一行。謝謝 – vijay 2013-03-13 15:19:33

0

如果您正在使用GridLayout(); 但希望設置您的組件大小自定義。

然後使用object.setPreferredSize(new Dimension(int,int)); Like below

obj.setPreferredSize(new Dimension(175,90));