Java 如何将和对象中的Swing组件添加到arraylist中的Swing组件中?

Java 如何将和对象中的Swing组件添加到arraylist中的Swing组件中?,java,swing,Java,Swing,我有一个面板的数组列表,这是一个数组列表,因为它们将进入一个卡片布局。我有一个TabbedPane,应该放在数组列表中的每个面板上,我所做的一切似乎都不起作用 正在尝试在面板中获取选项卡窗格: List<CountryPanel> p = new ArrayList<CountryPanel>(Arrays.asList(new CountryPanel("Finland"), new CountryPanel("Sweden"), new CountryPane

我有一个面板的数组列表,这是一个数组列表,因为它们将进入一个卡片布局。我有一个TabbedPane,应该放在数组列表中的每个面板上,我所做的一切似乎都不起作用

正在尝试在面板中获取选项卡窗格:

    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());
    }
为什么这不起作用

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());
    }
我有一个选项卡式窗格,应该放在每个面板上

你不能那样做。组件只能有一个父级。这就是Swing使用“模型”的原因。可以与多个零部件共享一个模型

您需要:

  • 为每个面板创建一个新的选项卡式窗格,或

  • 或者让框架的主布局为边框布局。然后,您可以将选项卡式窗格添加到BorderLayout的“页面开始”,然后使用CardLayout将面板添加到BorderLayout的“中心”。这将是更好的解决方案


  • 每个选项卡式窗格中的内容位置完全相同,但文本框中的内容编号将不同。我很难相信你不能用一个对象来复制gui。@toxicgrunt,你可以共享“模型”并创建多个组件,每个组件都使用同一个模型。你已经被告知一个组件只能有一个父组件,因此你不能将同一个组件添加到多个面板中。
    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());
        }
    
    public void addGUI(JTabbedPane p){
         card.add(p);
    
     }