I’m trying to learn GUI in Java, but I’m a little bit confused and wondering whats the difference between this code to add components in a window? When I view code examples it varies a lot, some examples use JPanel and just add by writing: panel.add(something); Some code just use add(something); or contentPane.add(something); I’m just curious. Thanks!
JList text;
JPanel panel = new JPanel();
frame.add(panel);
panel.add(text);
–
setLayout(new FlowLayout);
add(text);
–
Container contentPane;
contentPane = getContentPane();
contentpane.setLayout(new FlowLayout);
contentPane.add(text);
The difference lies in where the code is located. The second section of code would only make sense inside a method of a class that had
setLayoutandaddmethods; most likely this is because the class is a custom GUI component that inherits fromJPanelor anotherContainer.The third section calls
getContentPane, which is a method ofJFrame, so it most likely inherits from that class.If you edit your question to post the surrounding context of the example code (or links to it), I (or someone more experienced with Swing than I) might be able to give a more detailed explanation of how it works.