Example:
public class JFrameTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
JButton button = new JButton("Hello!");
frame.getContentPane().add(button);
frame.getContentPane().add(button);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
});
}
}
In the above example ‘button’ object is added only once even though there are no errors. The reason why I ask this is, I would like to add a same JPanel object on JFrame and on JDialog (on some table double click for edit/delete feature). I am able to solve it by having two JPanel objects but just wanted to know why it is not possible.
You can only add Swing components once in the Swing hierarchy as you already found out. This is documented in the ‘Using top-level components tutorial’
Not completely sure whether there were technical limitations that let to this decision, but I could imagine that for example the
getParentmethod would give strange results if you were able to add the same component to twoContainers