main()にSwingコードを書くのはマズイのか?
http://www.atmarkit.co.jp/fjava/rensai4/programer01/programer01_2.html
いがぴょんが記事を書いたのだが、気になるコードがあります。
読者からの指摘でそのように修正したようです。
以下が修正されたコードです。(@ITより一部転載、加筆)
import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class SimpleSwingFrame extends JPanel { public SimpleSwingFrame() { // 背景色を白色にします setBackground(Color.white); } public void paintComponent(final Graphics argGraphics) { super.paintComponent(argGraphics); // 赤色で画面の大きさいっぱいに円を描画します argGraphics.setColor(Color.red); final Rectangle rect = getBounds(); argGraphics.drawOval(0, 0, rect.width, rect.height); } /// ココから☆ private static void createAndShowGUI() { // JFrameを作成して自分自身を張り付け、これを表示します final JFrame frame = new JFrame("シンプルなSwingフレームサンプル"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new SimpleSwingFrame()); frame.setLocationRelativeTo(null); frame.setSize(400, 400); frame.setVisible(true); } public static void main(final String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } /// ココまで☆ }
コレが修正される前のコードです。
http://homepage2.nifty.com/igat/igapyon/diary/2007/ig070105.html
/// ココから☆ public static void main(final String[] args) { // JFrameを作成して自分自身を貼り付け、これを表示します。 final JFrame frame = new JFrame("シンプルなSwingフレームサンプル"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new SimpleSwingFrame()); frame.setLocationRelativeTo(null); frame.setSize(400, 400); frame.setVisible(true); } /// ココまで☆ }
おそらく、
「SwingはAWTのイベントディスパッチスレッドで処理しなければならない。」
ので修正したのでしょうが、修正前のコードではホントに問題があるのでしょうか?