Copy tab contents to another tab
Hi,
I am designing a GUI application which has a JTabbedPane at the center. I have 2 tabs in the pane and i want the second tab to look same as the first one (i want to use the same components on the second tab too). In other words, i want them to be grafically the same. I do not want to duplicate code and create the same elements as in the first tab. How can i do this copying?
Create a method that creates a JPanel, and all the components it will contains. Add those components to the panel and lay them out correctly. Then return that panel. Whenever you need to add a copy of that panel to the tabbedpane, create a new one with that method.
As I read this I get the sense that these two panels are meant to be EXACTLY the same. Meaning, if panel1 has a textfield1, then panel2 has the same textfield1. So that what you alter the text in textfield1 of panel1, the text is also altered in the textfield1 in panel2. Is this the case?
Or, are the tabs meant to be autonomous and simply laid out the same?
In the first case, the tabs will be the same object added twice to the tabbed pane. In the latter case, the tabs are simply differing instantiations of the tab class you created.
You can't have the same component added to different containers. A component has a single parent, and if you add it to a second container, it gets removed from the first. Try switching the order of the specified lines to see the difference when you add the button in a different order:
package sandbox;
public class ParentTest extends javax.swing.JFrame {
private javax.swing.JButton button;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
public ParentTest() {
initComponents();
}
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
button = new javax.swing.JButton("Hello");
getContentPane().setLayout(new java.awt.FlowLayout());
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("panel 1"));
getContentPane().add(jPanel1);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("panel 2"));
getContentPane().add(jPanel2);
// switch these two lines to see which panel gets the button
jPanel1.add(button);
jPanel2.add(button);
pack();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ParentTest().setVisible(true);
}
});
}
}