I wrote a small function that will display a table inside a dialog and am looking for advice on what to clean up and what is better programming practice when it comes to dealing with swing.
What improvements can be made to my code
//constraints for panel to fill out the frame
GridBagConstraints grid = new java.awt.GridBagConstraints();
grid.fill = java.awt.GridBagConstraints.BOTH;
grid.weightx = 1.0;
grid.weighty = 1.0;
//create jtable based on a table model created from an array
JTable table = new JTable(testModel); //a method creates my test model
table.add(table.getTableHeader(), BorderLayout.PAGE_START);
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(testModel);
table.setRowSorter(sorter);
//add scrollpane for visibility
JScrollPane jscrollpane = new JScrollPane(table);
table.setFillsViewportHeight(true);
//add the scrollpane to a panel
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.add(jscrollpane, grid);
//create for use with the dialog
JFrame frame = new JFrame();
JDialog dialog = new JDialog(frame, "My Test Dialog", true);
dialog.add(panel);
dialog.pack();
dialog.setLocationRelativeTo(null); //added as advice of Stripies
dialog.setVisible(true);
I'm open to all constructive criticism as my goal is to learn the proper techniques for programming with swing.
To clarify, I'm looking whether I can take anything out or improve any of it.
setLocationByPlatform(true)
are? Do you mind explaining why this may be more useful than centering it each time? (Truly curious, not being sarcastic if thats what it comes off as). As for this example, how would I make it more SSCCE? I would think one could simply copy and paste this example and add in whatever table model and centering. Perhaps I didn't fully understand SSCCE though - WilliamShatner 2012-04-05 14:07
What are the benefits of using
setLocationByPlatform(true)
?
Using setLocationRelativeTo(null)
is a convenient choice for examples, demos and utilities. Quality applications preserve the user's preferred position, possibly recording the most recent setting in an instance of java.util.Preferences
. Because a user's experience varies by platform, setLocationByPlatform(true)
represents the implementer's best effort to meet that expectation. It's a better choice for the default location when no preference yet exists.
JDialog
, you can simply usesetLocationRelativeTo(null)
- Stripies 2012-04-03 23:31