2012-04-03 4 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); 

にすることができます。

明確にするために、私は何かを取り除いたり、改善したりできるかどうかを探しています。

+2

'JDialog'を中央に配置するには、' setLocationRelativeTo(null) 'を使うだけです。 – Stripies

+1

また、 'setLocationByPlatform(true)'を考慮してください。 – trashgod

+1

[sscce](http://sscce.org/)は、これらの[投稿者](http://stackoverflow.com/tags/swing/topusers)の回答によく見られるように、断片よりもしばしば使い捨てです。 – trashgod

答えて

2

setLocationByPlatform(true)を使用する利点は何ですか?

デモとユーティリティの例としては、setLocationRelativeTo(null)を使用するのが便利です。高品質のアプリケーションでは、ユーザの好みの位置が保持され、最新の設定がjava.util.Preferencesのインスタンスに記録される可能性があります。ユーザーの経験はプラットフォームによって異なるため、setLocationByPlatform(true)はその期待に応えるための実装者の最善の努力を表しています。まだ環境設定が存在しない場合は、デフォルトの場所に適しています。

関連する問題