【发布时间】:2012-04-03 23:21:11
【问题描述】:
我编写了一个小函数,它将在对话框中显示一个表格,我正在寻找关于清理什么以及在处理摆动时更好的编程实践的建议。
可以对我的代码进行哪些改进
//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 编程的正确技术。
为了澄清,我正在寻找是否可以取出任何东西或改进任何东西。
【问题讨论】:
-
要将
JDialog居中,您只需使用setLocationRelativeTo(null)即可。 -
或者,考虑
setLocationByPlatform(true)。 -
sscce 通常比片段更具决定性,正如在这些contributors 的答案中经常看到的那样。
-
@trashgod "dispositive" 呵呵。不得不看那个。我今天的“学习单词”。 :)
-
为了让您的示例更加 SSCCE,它必须是独立的。换句话说,如果尝试帮助的人可以将您的代码复制并粘贴到 .java 文件中并进行编译,那么他们的工作量要比他们需要计算出您想要的“表格模型和居中”和其他需要完成的工作......