应该对这个JDialog代码片段进行哪些改进?
问题描述:
我写了一个小函数,它将在对话框中显示一个表格,并且正在寻找关于清理什么的建议,以及在处理摆动时什么是更好的编程实践。应该对这个JDialog代码片段进行哪些改进?
可以到我的代码
//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);
做出哪些改进,我向所有人开放的建设性批评意见作为我的目标是学习正确的技术与Swing编程。
为了澄清,我正在研究是否可以取出任何东西或改进任何东西。
答
使用
setLocationByPlatform(true)
有什么好处?
使用setLocationRelativeTo(null)
是示例,演示和实用程序的便利选择。优质应用程序保留用户的首选位置,可能会记录java.util.Preferences
实例中的最新设置。由于用户的体验因平台而异,因此setLocationByPlatform(true)
代表实施者尽力满足该期望。当没有偏好存在时,这是默认位置的更好选择。
要使你的'JDialog'居中,你可以简单地使用'setLocationRelativeTo(null)'。 – Stripies 2012-04-03 23:31:23
或者,考虑'setLocationByPlatform(true)'。 – trashgod 2012-04-04 01:01:45
[sscce](http://sscce.org/)通常比片段更具有定位性,这在[贡献者](http://stackoverflow.com/tags/swing/topusers)的答案中经常可见。 – trashgod 2012-04-04 01:11:33