2013-08-23 91 views
0

创建自定义的表,我想创建一个表看起来像这样,但随着职称的同步与表:在Java

enter image description here

如何使列任何提示与对齐行,还允许在x轴自动调整大小?为此,我使用了GridBagLayout。也尝试JTable,但有问题来定制它来隐藏所有默认的JTable组件(如我的照片)。

public class MyTableExample extends JFrame { 

    public MyTableExample(){ 
     JPanel contentPanel = new JPanel(new GridBagLayout()); 
     GridBagConstraints c = new GridBagConstraints(); 
     c.weightx = 1; 
     c.fill = GridBagConstraints.HORIZONTAL; 
     contentPanel.add(getTitles(),c); 
     c.gridy = 2; 
     contentPanel.add(getRow(),c); 
     c.gridy = 3; 
     contentPanel.add(getRow(),c); 

     // MainPanel: Helps positioning the contentPanel 
     JPanel mainPanel = new JPanel(new GridBagLayout()); 
     c.weighty = 1; 
     c.anchor = GridBagConstraints.NORTH; 
     c.insets = new Insets(20,20,20,20); 
     mainPanel.add(contentPanel,c); 

     this.add(mainPanel); 
     this.pack(); 
     this.setVisible(true); 
    } 

    private JPanel getRow(){ 
     JPanel rowPanel = new JPanel(new GridBagLayout()); 
     GridBagConstraints c = new GridBagConstraints(); 
     c.weightx = 1; 
     c.weighty = 1; 
     c.fill = GridBagConstraints.HORIZONTAL; 
     c.anchor = GridBagConstraints.WEST; 

     rowPanel.setOpaque(false); 
     JLabel col1 = new JLabel("#rowItem"); 
     JComboBox<String> col2 = new JComboBox<String>(); 
     JButton col3 = new JButton("rowItem"); 
     JLabel col4 = new JLabel("rowItem"); 
     rowPanel.add(col1,c); 
     rowPanel.add(col2,c); 
     rowPanel.add(col3,c); 
     rowPanel.add(col4,c); 

     return rowPanel; 
    } 

    private JPanel getTitles(){ 
     JPanel titlePanel = new JPanel(new GridBagLayout()); 
     GridBagConstraints c = new GridBagConstraints(); 
     c.weightx = 1; 
     c.weighty = 1; 
     c.fill = GridBagConstraints.HORIZONTAL; 
     c.anchor = GridBagConstraints.WEST; 

     titlePanel.setOpaque(false); 
     JLabel t1 = new JLabel("T1"); 
     JLabel t2 = new JLabel("Title2"); 
     JLabel t3 = new JLabel("Title33333333"); 
     JLabel t4 = new JLabel("T4"); 
     titlePanel.add(t1,c); 
     titlePanel.add(t2,c); 
     titlePanel.add(t3,c); 
     titlePanel.add(t4,c); 

     return titlePanel; 
    } 

    public static void main(String[] args){ 
     new MyTableExample(); 
    } 
} 
+0

尝试[MigLayout](http://www.miglayout.com/);) – linski

回答

2

如果您对所有单元格大小相同,GridLayout将是一个简单的解决方案。我在时间上支持哪些新的布局可能会有帮助,但GridBag可以有一些学习曲线。如果你想要一切排列,你需要有一个GridBagLayout,而不是每行一个。

+0

谢谢。通过改变内部JPanel到GridBag它工作。 – Grains

1

使用一个单一的面板,所有组件直接放在此面板中使用的GridBagLayout。这样,所有的组件将被放置在一个单独的网格中,并因此被正确对齐。