我在这个程序中有三个选项卡,第三个选项卡,我有一个JTalbe和JButton . 我使用GridBagLayout作为LayoutManager,但设置我想要的地方非常棘手 . (但它确实比我认为的其他LayoutManagers强大 . )无论如何,如下图所示 . 左边是我做过的那个,右边是我想要设置的那个 . 你们能给我一个暗示吗?
这是左窗口的代码 .
private static void thirdTab(JPanel panel) {
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc=new GridBagConstraints();
String[] columnNames={"name","number","Contents"};
Object [][]data={
{"ken","11","haha"},
{"ben","22","hehe"},
};
DefaultTableModel defTableModel=new DefaultTableModel(data,columnNames){
public boolean isCellEditable(int rowIndex, int mColIndex){
return false;
}
};
JTable table=new JTable(defTableModel);
table.getTableHeader().setReorderingAllowed(false) ;
JScrollPane sroll=new JScrollPane(table);
//First Column
gbc.anchor=GridBagConstraints.LAST_LINE_START;
gbc.weightx=0.1;
gbc.weighty=0.1;
gbc.gridx=0;
gbc.gridy=1;
JButton button=new JButton("View/Edit");
panel.add(button,gbc);
gbc.gridx=0;
gbc.gridy=0;
gbc.fill=GridBagConstraints.BOTH;
panel.add(sroll,gbc);
panel.setVisible(true);
}
1 回答
好吧,我使用GridBagLayout很多,但我认为你需要使用值为“CENTER”的"anchor"约束 . 请阅读How to Use GridBagLayout上Swing教程中的部分,以更好地描述约束 .
或者,另一个选项是将包含表的滚动窗格添加到BorderLayout的CENTER . 然后创建一个JPanelm,默认情况下使用FlowLayout . 您将按钮添加到此面板,然后将面板添加到BorderLayout.SOUTH .