【问题标题】:Adding a JPanel Array to a Container将 JPanel 数组添加到容器
【发布时间】:2013-03-27 07:42:23
【问题描述】:

查看最后一行代码,这是我特别想将我的 JPanel 数组添加到容器的地方。非常感谢你们!

代码:

private JFrame b = new JFrame("Lotus");
private JLabel currentP = new JLabel();
private int currentS;
private Container pieces = new Container();
private JButton exitt = new JButton("EXIT");
private ImageIcon B1=new ImageIcon("C:\\Users\\Brusty\\Downloads\\p1.jpg");  
private ImageIcon B2=new ImageIcon("C:\\Users\\Brusty\\Downloads\\p2.jpg"); 
LinkedList<Stack<Integer>> spotList = new LinkedList<Stack<Integer>>(); 

//Creation of Gamepiece labels
public void Labels(){

JLabel[] labelsP1 = new JLabel[10];
JLabel[] labelsP2 = new JLabel[10];

for(int i = 0 ; i < labelsP1.length ; i++){
    labelsP1[i] = new JLabel(B1); 
    for(int j = 0 ; j < labelsP2.length ; j++){
        labelsP2[j] = new JLabel(B2); 
}
    Container c = b.getContentPane();
    c.setLayout(new GridLayout(13,3)); 
    c.add(pieces); 
    pieces.add(labelsP1);

【问题讨论】:

标签: java arrays swing jpanel containers


【解决方案1】:

不确定我是否真的看到了您的问题。您只需要遍历labelsP1 数组并添加标签...

for (JLabel label : labelsP1) {
    pieces.add(label);
}

【讨论】:

  • 好的,谢谢,我不知道为什么购买调用pieces.add(labelsP1) 导致Eclipse 给我错误:容器类型中的方法add(Component) 不适用于参数(JLabel[])。对不起,如果这个问题有点无聊。
  • 基本上,当它只需要一个 Component 对象时,您正在尝试将一个组件数组传递给 add 方法。假设add 预期Apple 并且您尝试将其传递给Orange,显然,这不会起作用。这两种类型的变量是不兼容的。但是,由于数组中包含Components,因此可以将每个元素传递给add 方法
  • 哇!这很有意义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
相关资源
最近更新 更多