gpt4 book ai didi

java - 如何将 Swing 组件从对象添加到 arraylist 中的 swing 组件?

转载 作者:行者123 更新时间:2023-11-29 04:52:37 27 4
gpt4 key购买 nike

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

尝试获取面板中的 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());
}

正在使用的类;

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

为什么这行不通?

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

}

最佳答案

I have a TabbedPane that should go on every Panel

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

你需要:

  1. 为每个面板创建一个新的选项卡式 Pane ,或者

  2. 或者将框架的主要布局设为 BorderLayout。然后,您可以将选项卡式 Pane 添加到 BorderLayout 的“PAGE_START”,然后使用 CardLayout 将面板添加到 BorderLayout 的“CENTER”。这将是更好的解决方案。

关于java - 如何将 Swing 组件从对象添加到 arraylist 中的 swing 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34862961/

27 4 0