1

I've seen a couple of ways of doing theism they both seem to work but I'm just wondering if one is better practice over the other.

For example, with a JFrame called myFrame you could do:

myFrame.add(new JButton("OK"));

And you can also do:

Container c = myFrame.getContentPane();
c.add(new JButton("OK"));

Is one of these 'correct'?

4

3 に答える 3

6

A literal copy from the class javadoc of JFrame

The JFrame class is slightly incompatible with Frame. Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame. This is different from the AWT Frame case. As a conveniance add and its variants, remove and setLayout have been overridden to forward to the contentPane as necessary. This means you can write:

   frame.add(child);

And the child will be added to the contentPane. The content pane will always be non-null. Attempting to set it to null will cause the JFrame to throw an exception. The default content pane will have a BorderLayout manager set on it. Refer to RootPaneContainer for details on adding, removing and setting the LayoutManager of a JFrame.

So both are equivalent, and both are correct

于 2012-04-10T10:27:04.010 に答える
2

Java5以降は不要

  • に追加JComponentsするにはContentPane、ちょうどJFrame.add(JComponent)

  • JFrameが実装されたBorderLayout後、エリアmyFrame.add(new JButton("OK"));に配置されますCENTER

于 2012-04-10T10:27:24.897 に答える
1

私は間違いなくそれを言うだろう

Container c = myFrame.getContentPane();
c.add(new JButton("OK"));

最も実用的なものです。後でコンテナを使用する必要がある可能性が高いため、

myFrame.getContentPane();

後でもう一度書く必要はありません。たとえば、フレームに別のレイアウトを設定する必要がある場合に使用されます。ただし、前述のように、両方を使用できます。

于 2012-04-10T10:33:03.367 に答える