1

コードを最初の例から 2 番目の例に変更すると、何も表示されません (スクリーンショットを参照してください:

メインクラス:

public class Main extends JTabbedPane {
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        JFrame.setDefaultLookAndFeelDecorated(true);

        JFrame f = new JFrame("Math");
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        int x = dim.getWidth() > 800 ? (int) (dim.getWidth() / 2 - 400) : 0;
        int y = dim.getWidth() > 800 ? (int) (dim.getHeight() / 2 - 300) : 0;
        f.setBounds(x, y, 800, 600);
        f.setResizable(false);
        f.setContentPane(new Main());
    }

    Main() {
        super();
        addTab("Pythagoras", new Pythagoras());
    }
}

ピタゴラス (スクリーンショット 1):

public class Pythagoras extends JPanel{

    Pythagoras() {
        super();
        setLayout(new FlowLayout());
        JTextField j = new JTextField("Hi :)");
        add(j);
    }
}

ピタゴラス (スクリーンショット 2):

public class Pythagoras extends JPanel{

    Pythagoras() {
        super();
        setLayout(new FlowLayout());
    }
}

ピタゴラス (スクリーンショット 3):

public class Pythagoras extends JPanel{

        Pythagoras() {
            super();
            setLayout(new FlowLayout());
    add( new JLabel("This works!"));
        }
    }

スクリーンショット 1スクリーンショット 2スクリーンショット 3

4

2 に答える 2

2

イベントディスパッチスレッドでは常に Swing コンポーネントを使用してください。main メソッドのコード全体を次のようにラップする必要があります。

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        // original code here
    }
});

この変更により、すべてがテストで期待どおりに表示されます。

http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.htmlおよびhttp://docs.oracle.com/javase/6/docs/api/javax/swing/package-summary.htmlを参照してください。 #スレッディング

また、引数として文字列のみを受け取る JTextField コンストラクターは、列数が 0 のテキスト フィールドを作成することに注意してください。

于 2011-12-18T00:22:24.573 に答える
0
JFrame f = new JFrame("Math");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int x = dim.getWidth() > 800 ? (int) (dim.getWidth() / 2 - 400) : 0;
int y = dim.getWidth() > 800 ? (int) (dim.getHeight() / 2 - 300) : 0;
f.setContentPane(new Main());
f.setBounds(x, y, 800, 600);
f.setResizable(false);
f.setVisible(true);
于 2011-12-18T09:29:38.430 に答える