The JPanel contentpane confusion

旧街凉风 提交于 2019-12-05 08:47:39

Some random thoughts:

  • Yes, JPanels and other components are often "nested". This is where a firm understanding of the Swing/AWT layout managers is essential.
  • While the type returned by a JFrame's getContentPane() is technically a Container, it's also a JPanel (which inherits eventually from Container).
  • I believe that you can make anything that derives from Container the contentPane, but you need to take care that it is opaque.

for that there is method

frame.setJMenuBar(menuBar);

for todays Java Swing GUI, is not neccesary declare ContentPane, from Java5, and with BorderLayout as default LayoutManager

then frame.add(myPanel); //is same as frame.add(myPanel, BorderLayout.CENTER) and occupated whole Container

basic stuff about how to use LayourManagers

getContentPane() always returns a Container instance. However, you should note that JPanel objects are Container instances, as well as other classes in the Swing framework. The actual class of the instance returned is irrelevant, as you do not have control over which implementation of Container is used as a contentPane (unless you have forced a specific contentPane), and most of the time this should not be a problem.

You can add many GUI widgets in a JFrame, such as JButton, JLabel, etc. However, they will be automatically added to the associated contentPane.

JPanel does not handle the objects positioning, the LayoutManager associated with your panel does; either automatically based on its own set of rules (e.g. FlowLayout), or by using the constraints you have specified when adding the object to the container (the GridBagLayout layout manager is a good example). The JavaDoc on the LayoutManagers usually contain enough information to get you started on using them.

You can have nested panels, yes. A Container can contain other Container instances. While it seems to be a complicated solution, it does enable you to control exactly how your GUI is displayed. Depending on which LayoutManager you are using, on the needs you have to fulfill with your user interface, and on your own preferences/habits as a developper, you might need less or more nested panels.

You need to see this API doc for JComponent.

If you look at the inheritance hierarchy, you will see that the JComponent extends Component so a JComponent is a Component.

Also under Direct Known Subclasses, you can see the list of all the classes that extend the JComponent including JMenuBar and JPanel.

So, JMenuBar and JPanel are two more specialized versions of JComponent (or Container).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!