Reputation: 9
Basically I need to duplicate a JPanel
, for example if we do it with Integer
variables this should work:
Integer intaux,int1;
int1 = 3;
intaux = int1;
But this doesn't work with panels:
jPanelaux = jPanel1;
Is there any setter method I don't know?
Upvotes: 0
Views: 4204
Reputation: 12347
If you only want a duplicate image of the original panel then creating another JPanel that uses the original JPanel to paint could work.
JPanel dup = new JPanel(){
@Override
public void paintComponent(Graphics g){
jPanel1.paintComponent(g);
}
@Override
public Dimension getPreferredSize(){
return jPanel1.getPreferredSize();
}
@Override
public Dimension getMaximumSize(){
return jPanel1.getMaximumSize();
}
@Override
public Dimension getMinimumSize(){
return jPanel1.getMinimumSize();
}
};
This would only create a view of the original panel and none of the components would be functional, eg JButton or JTextField would not receive input.There would also need to be some work done to cause repainting.
Upvotes: -1
Reputation: 109547
Make your own JPanel child class that contains all you want. Something like:
public class MyPanel extends JPanel {
JButton okButton;
JButton cancelButton;
JTextField nameTextField;
public MyPanel() {
okButton = new JButton();
JLabel nameLabel = new JLabel("Name:");
setLayOut(...);
add(okButton);
...
}
}
Either you use a GUI editor, or copy all from your current code.
Then you can use two new MyPanel()
s to have identical complex components.
Upvotes: 1
Reputation:
As Kira San already said, you will need an instance for every panel you want to display.
For example:
public class MyPanel extends JPanel {
//creates a JPanel with the text "hello"
public MyPanel() {
super();
this.add(new JLabel("Hello"));
}
}
public class someClass {
public void someMethod() {
MyPanel myPanel = new MyPanel();
//here we add the same instance of MyPanel twice to panel1, which ..
JPanel panel1 = new JPanel();
//...adds myPanel
panel1.add(myPanel);
//...removes myPanel from the container it was added to first and adds it to this container (which is panel1 in both cases)
panel1.add(myPanel);
//here we add two separate instances of MyPanel to panel2, which should both be shown
JPanel panel2 = new JPanel();
panel2.add(new MyPanel());
panel2.add(new MyPanel());
}
}
Upvotes: 1