import java.awt.*;
import javax.swing.*;
public class GridBagDemo extends JFrame {
/**
*
*/
private static final long serialVersionUID = -1511810356038746853L;
public static void main(String args[]) {
GridBagDemo demo = new GridBagDemo();
}
public GridBagDemo() {
init();
this.setSize(600,600);
this.setVisible(true);
}
public void init() {
JLabel name = new JLabel("dasdasd");
name.setSize(new Dimension(100,100));
JScrollPane right = new JScrollPane();
//right.setSize(new Dimension(500,300));
right.setBackground(Color.RED);
JScrollPane left = new JScrollPane();
left.setBackground(Color.BLUE);
left.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
JLabel jLabel = null;
JPanel jPanel = new JPanel(new GridLayout(0,1,0,0));
for(int i = 0 ; i < 100; i++) {
jLabel = new JLabel("asdasd");
jPanel.add(jLabel);
}
this.getContentPane().add(jPanel);
left.setViewportView(jPanel);
this.getContentPane().add(name);
this.getContentPane().add(left);
this.getContentPane().add(right);
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
GridBagConstraints s= new GridBagConstraints();
s.fill = GridBagConstraints.BOTH;
s.insets = new Insets(5, 5, 5, 5);
s.gridx = 1;
s.gridy = 1;
s.gridwidth = 1;
s.gridheight = 1;
s.weightx = 0;
s.weighty = 0;
layout.setConstraints(name, s);
s.fill = GridBagConstraints.BOTH;
s.insets = new Insets(5, 5, 5, 5);
s.gridx = 1;
s.gridy = 2;
s.gridwidth = 1;
s.gridheight = 8;
s.weightx = 0;
s.weighty = 0;
layout.setConstraints(left, s);
s.fill = GridBagConstraints.BOTH;
s.gridwidth = 0;
s.gridheight = 9;
s.gridx = 2;
s.gridy = 1;
s.weightx = 1;
s.weighty = 1;
layout.setConstraints(right, s);
}
}
左上角第一个Label为基本cell所有其他grid里的都是以其作为宽高倍数判断的,而且设定大小无效
gridwidth <span style="font-family: Arial, Helvetica, sans-serif;">当前元素面积为基本cell的倍数</span>
gridx 元素位置
weightx <span style="font-family: Arial, Helvetica, sans-serif;">窗体放大系数</span>
还有有个问题困扰我,如何在JPanel上添加 带滚动条的JPanel,而不是在JFrame上。