如何复制JPanel?

时间:2015-11-12 01:56:10

标签: java swing jpanel

基本上我需要复制一个JPanel,例如,如果我们使用Integer变量这样做,这应该可行:

Integer intaux,int1;
int1 = 3;
intaux = int1;

但这不适用于面板:

jPanelaux = jPanel1;

有什么我不知道的setter方法吗?

3 个答案:

答案 0 :(得分:1)

正如Kira San所说,你需要为你想要展示的每个面板提供一个实例。

例如:

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());
    }
}

答案 1 :(得分:1)

创建包含您想要的所有JPanel子类。 类似的东西:

public class MyPanel extends JPanel {

    JButton okButton;
    JButton cancelButton;
    JTextField nameTextField;

    public MyPanel() {
         okButton = new JButton();
         JLabel nameLabel = new JLabel("Name:");

         setLayOut(...);
         add(okButton);
         ...
    }
}

您可以使用GUI编辑器,也可以从当前代码中复制所有内容。

然后你可以使用两个new MyPanel()来拥有相同的复杂组件。

答案 2 :(得分:-1)

如果您只想要原始面板的重复图像,那么创建另一个使用原始JPanel进行绘制的JPanel可以正常工作。

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();
    }
};

这只会创建一个原始面板的视图,并且没有任何组件可以正常工作,例如JButton或JTextField不会接收输入。还需要完成一些工作才能重新绘制。