我試圖在JFrame中創建具有不同寬度的兩個面板。我希望我的右側面板具有左側面板寬度的兩倍。我嘗試使用GridBagLayout,對我的leftpanel使用gridwidth = 1,對我的rightpanel使用gridwidth = 2。但不是變得寬度不同,我得到兩塊寬度相同的面板。我應該改變什麼?任何幫助,將不勝感激。使用GridBagLayout在JFrame中使用不同寬度的多個JPanel
import javax.swing.*;
import java.awt.*;
public class AppFrame2 extends JFrame {
GridBagLayout gbl;
GridBagConstraints gbc;
JPanel leftpanel;
JPanel rightpanel;
public AppFrame2() {
this.setSize(500, 500);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.getContentPane().setBackground(Color.BLACK);
// Settning Frame Layout
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
this.setLayout(gbl);
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
// Add Panels
leftpanel = new JPanel();
leftpanel.setBackground(Color.green);
this.addPanels(0, 0, 1, 1, leftpanel); // row, col, height, width component
rightpanel = new JPanel();
rightpanel.setBackground(Color.red);
this.addPanels(0, 1, 1, 2, rightpanel);
}
private void addPanels(int row, int col, int height, int width,
Component com) {
gbc.gridx = col;
gbc.gridy = row;
gbc.gridheight = height;
gbc.gridwidth = width;
gbl.setConstraints(com, gbc);
this.getContentPane().add(com);
}
public static void main(String[] args) {
new AppFrame2();
}
}
您是否考慮過使用內部填充? – TNT 2014-12-02 18:30:44
它們被調整大小的原因是因爲GridBagLayout引用的東西大小相同。參考這個更好的例子http://stackoverflow.com/questions/4112886/components-in-gridlayout-wit-jpanel-fills-the-grid-incorrectly – Dacotah 2014-12-02 18:33:51
我用gbc.insets(2,2,2,2) , 但後來我刪除它。我不知道任何其他填充。你能舉個例子嗎? – 2014-12-02 18:36:28