想实现一个界面, 如下:
______________________
| Label| |Button|
|--------------------|
| Table | <--- JPanel
| in ScollPanel |
| |
|____________________| 当这个Panel最大化,改变尺寸的时候, Label 和 Button 的尺寸不会变,在顶端, Table 的尺寸会改变,且 Table 的尺寸始终占据 JPanel 的 90% (高度)。
______________________
| Label| |Button|
|--------------------|
| Table | <--- JPanel
| in ScollPanel |
| |
|____________________| 当这个Panel最大化,改变尺寸的时候, Label 和 Button 的尺寸不会变,在顶端, Table 的尺寸会改变,且 Table 的尺寸始终占据 JPanel 的 90% (高度)。
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;public class TestFrame extends JFrame
{
private JLabel jLabel = new JLabel("Label");
private JButton jButton = new JButton("Button");
private JTable jTable = null; public TestFrame()
{
this.setSize(500, 400); String[] column = new String[]
{
"第一列", "第二列"};
Object[][] data = new Object[0][2];
jTable = new JTable(data, column); this.getContentPane().setLayout(new GridBagLayout());
this.getContentPane().add(jLabel,
new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 0, 0), 0, 0));
this.getContentPane().add(jButton,
new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 0, 0), 0, 0));
this.getContentPane().add(new JScrollPane(jTable),
new GridBagConstraints(0, 1, 2, 1, 1.0, 9.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
} public static void main(String[] args)
{
(new TestFrame()).setVisible(true);
}
}
你不是说要占90%,那肯定不可能靠顶了。
想要靠顶的话,把前两个被add的控件的布局属性从1.0改成0.0。
如下,把红字改成蓝字。
new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0,
new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0,
this.getContentPane().add(jButton,
new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));