2012-04-03 84 views
1

我寫了一個小函數,它將在對話框中顯示一個表格,並且正在尋找關於清理什麼的建議,以及在處理擺動時什麼是更好的編程實踐。應該對這個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編程。

爲了澄清,我正在研究是否可以取出任何東西或改進任何東西。

+2

要使你的'JDialog'居中,你可以簡單地使用'setLocationRelativeTo(null)'。 – Stripies 2012-04-03 23:31:23

+1

或者,考慮'setLocationByPlatform(true)'。 – trashgod 2012-04-04 01:01:45

+1

[sscce](http://sscce.org/)通常比片段更具有定位性,這在[貢獻者](http://stackoverflow.com/tags/swing/topusers)的答案中經常可見。 – trashgod 2012-04-04 01:11:33

回答

2

使用setLocationByPlatform(true)有什麼好處?

使用setLocationRelativeTo(null)是示例,演示和實用程序的便利選擇。優質應用程序保留用戶的首選位置,可能會記錄java.util.Preferences實例中的最新設置。由於用戶的體驗因平臺而異,因此setLocationByPlatform(true)代表實施者盡力滿足該期望。當沒有偏好存在時,這是默認位置的更好選擇。