toxicgrunt
toxicgrunt

Reputation: 13

How to add a Swing component from and object into a swing component in an arraylist?

I have an array list of panels, its an array list because they are going into a cardlayout. I have a TabbedPane that should go on every Panel in the array list and nothing I do seems to be working.

Trying to get the TabbedPane in the Panel:

    List<CountryPanel> p = new ArrayList<CountryPanel>(Arrays.asList(new CountryPanel("Finland"), new CountryPanel("Sweden"), new CountryPanel("Norway"), new CountryPanel("Estonia")));

    for( int x = 0; x<4; x++ ){
        p.get(x).getPanel().add(new InfoPanel().getTabbedPane());
    }

Classes being used;

 JPanel card;
 Random random = new Random();
 String name;
 String username;

 public CountryPanel(String name) {

        card = new JPanel(new CardLayout());
        this.name = name;
        this.username = username;


 }

 @Override
    public String toString() {
        return name;
    }

 public String getName(){
     return name;
 }
 public JPanel getPanel(){
     return card;
 }

public class InfoPanel extends JPanel {
  private JTable table;
  private JTable table_1;
  static JTabbedPane tabbedPane;
///Giant block of text

public JTabbedPane getTabbedPane(){
    return tabbedPane;
}

Why doesnt this work?

List<CountryPanel> p = new ArrayList<CountryPanel>(Arrays.asList(new CountryPanel("Finland"), new CountryPanel("Sweden"), new CountryPanel("Norway"), new CountryPanel("Estonia")));
    List<InfoPanel> i = new ArrayList<InfoPanel>(Arrays.asList(new InfoPanel("Finland"), new InfoPanel("Sweden"), new InfoPanel("Norway"), new InfoPanel("Estonia")));
    for( int x = 0; x<4; x++ ){

        countryBox.addItem(p.get(x));
        cardPanel.add(p.get(x), p.get(x).toString());
        System.out.println(p.get(x).toString());
        p.get(x).addGUI(i.get(x).getTabbedPane());
    }

New method

public void addGUI(JTabbedPane p){
     card.add(p);

 }

Upvotes: 1

Views: 58

Answers (1)

camickr
camickr

Reputation: 324167

I have a TabbedPane that should go on every Panel

You can't do that. A component can only have a single parent. This is why Swing uses "models". You can share a model with multiple components.

You need to:

  1. Create a new tabbed pane for every panel, or

  2. or have your main layout of the frame be a BorderLayout. Then you can add the tabbed pane to the "PAGE_START" of the BorderLayout and then add your panel using the CardLayout to the "CENTER" of the BorderLayout. This would be the better solution.

Upvotes: 3

Related Questions