Quick problem with JTable
I've set up my frame with a JTree on the left and a JTable on the right, and used a BorderLayout to accomplish this. However, as soon as I put any data in my JTable, it expands to cover nearly the whole frame, and my JTree with it. The table currently has no data in at all (I'm verifying my SelectionListener), just a couple of column headers that are fifteen characters total. There's no way it needs the extra space.
Here's my setup code:
primaryframe = new javax.swing.JFrame();
primaryframe.setTitle("Bus Route Finder");
primaryframe.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
primaryframe.setSize(500, 500);
primaryframe.setLayout(
new java.awt.BorderLayout()
);
// Set up the tree and it's dependent objects(model, scrollpane, etc).
javax.swing.tree.DefaultMutableTreeNode node = new javax.swing.tree.DefaultMutableTreeNode(dataroot.GetName());
node.setUserObject(dataroot);
CreateNodes(dataroot, node);
primaryframe.add(
treescrollpane = new javax.swing.JScrollPane(
datatree = new javax.swing.JTree(
treemodel = new javax.swing.tree.DefaultTreeModel(
node
)
)
),
java.awt.BorderLayout.WEST
);
datatree.addTreeSelec开发者_JS百科tionListener(new javax.swing.event.TreeSelectionListener() {
public void valueChanged(javax.swing.event.TreeSelectionEvent e) {
javax.swing.JTree tree = (javax.swing.JTree)e.getSource();
javax.swing.tree.DefaultMutableTreeNode newnode = (javax.swing.tree.DefaultMutableTreeNode)tree.getSelectionPath().getLastPathComponent();
Controller.TreeData data = (Controller.TreeData)newnode.getUserObject();
tablemodel.setNumRows(0);
tablemodel.setColumnCount(0);
for(int i = 0; i < data.GetNumberOfFields(); i++) {
tablemodel.addColumn(data.GetFieldName(i));
}
}
});
primaryframe.add(
tablescrollpane = new javax.swing.JScrollPane(
datatable = new JTable(
tablemodel = new javax.swing.table.DefaultTableModel()
)
),
java.awt.BorderLayout.EAST
);
BorderLayout is awfully finicky. I would recommend using GridLayout if you know you want just the two items - have one row with two columns. Not sure if that will help or not, but I've always had much greater success with GridLayout.
If you're adamant about using BorderLayout, try setting the maximum size of the objects going in there, such as the JTable, using setMaximumSize(Dimension).
精彩评论