应该对此JDialog代码段进行哪些改进?

时间:2012-04-03 23:21:12

标签: java swing jtable jdialog

我编写了一个小函数,它将在对话框中显示一个表格,并且正在寻找有关清理内容的建议以及在处理swing时更好的编程习惯。

可以对我的代码进行哪些改进

//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进行编程的正确技巧。

澄清一下,我正在考虑是否可以采取任何措施或改进其中任何一项。

1 个答案:

答案 0 :(得分:2)

  

使用setLocationByPlatform(true)有什么好处?

使用setLocationRelativeTo(null)是示例,演示和实用程序的便捷选择。质量应用程序保留用户的首选位置,可能在java.util.Preferences的实例中记录最新设置。由于用户的体验因平台而异,setLocationByPlatform(true)代表了实施者为满足期望而付出的最大努力。当没有偏好时,它是默认位置的更好选择。