Add JPanel to multiple JFrames

I have a JPanel that contains a bunch of context.

I would like to be able to add the specified JPanel to two JFrames. Any tips?

This is an example of what I would like

public class Test
{
    public static void main(String [] args)
    {
        JPanel panel = new JPanel();
        panel.add(new JLabel("Hello world"));
        panel.validate();

        JFrame frame1, frame2;
        frame1 = new JFrame("One");
        frame2 = new JFrame("Two");
        frame1.add(panel);
        frame2.add(panel);
        frame1.validate();
        frame2.validate();
        frame1.setVisible(true);
        frame2.setVisible(true);
        frame1.pack();
        frame2.pack();
    }
}

I want both JFrames to display the hello world, not one showing it and the other empty. And if the data is in JPanel updates, I want both JFrames to display it.

Thanks to someone for their help, this has been undermining me for a while.

+4
source share
3 answers

, . java.awt.Container , Component. JFrame Container JPanel comp:

        /* Reparent the component and tidy up the tree state. */
        if (comp.parent != null) {
            comp.parent.remove(comp);
            if (index > component.size()) {
                throw new IllegalArgumentException("illegal component position");
            }
        }

( java.awt.Container.addImpl(Component, Object, int))

, Container, Container. , AWT , .

+6

Swing , , , ...

- ...

    JPanel panel = new JPanel();
    panel.add(new JLabel("Hello world"));

    JFrame frame1, frame2;
    frame1 = new JFrame("One");
    frame1.add(panel);
    frame1.pack();
    frame1.setVisible(true);

    JPanel panel2 = new JPanel();
    panel2.add(new JLabel("Hello world"));
    frame2 = new JFrame("Two");
    frame2.add(panel2);
    frame2.pack();
    frame2.setVisible(true);

+1

, , , JPanels , , , ?

. JPanels, , JPanels, - .

class Data<T> {
.....stuff
  void update();
  T getdata();
}

class DataView<T> extends JPanel {
  private Data<T> data;
  ...stuff
  public DataView(T data) {
     this.data = data;
  }
  ...stuff
  protected void paintComponent(Graphics g) {
     drawData();
     ...stuff
  }
}

public static void main(String[] args ) {
  Data<String> data = new Data();
  DataView<String> dataViewOne = new DataView(data);
  DataView<String> dataViewTwo = new DataView(data);
  ..add to two seperate frames, pack set visible etc..
}
+1
source

All Articles