将图像添加到JLabel阵列的方法

时间:2011-03-10 19:44:07

标签: java image swing jlabel

当我按下nyOmgang按钮时,我试图让bilde()方法添加图像我的JLabel数组,这是一个艰难的一天,我已经卡住了。

private JLabel[] kort = new JLabel[16];
private JLabel[] kortForside = new JLabel[16];
private JButton nyOmgang = new JButton("Del ut kortene");
private ImageIcon bakside = new ImageIcon("image/bgi14.gif");
private ImageIcon[] forside = new ImageIcon[8];
private HovedVinduet vindu;
private int[] index = new int[8];


public Hukommelse(HovedVinduet vindu){
    super(new GridBagLayout());

    this.vindu = vindu;

    setBackground(Color.GREEN);
    setPreferredSize(new Dimension(1280,720));

    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.RELATIVE;
    c.gridx = 5;
    c.gridy = GridBagConstraints.RELATIVE;

    nyOmgang.addActionListener(this);
    add(nyOmgang, c);
    Kortene();





    forside[0] = new ImageIcon("");
    forside[1] = new ImageIcon(""); 
    forside[2] = new ImageIcon("");
    forside[3] = new ImageIcon("");
    forside[4] = new ImageIcon("");
    forside[5] = new ImageIcon("");
    forside[6] = new ImageIcon("");
    forside[7] = new ImageIcon("");

}

public JLabel Kortene() {

    GridBagConstraints c = new GridBagConstraints();

    for (int i = 0; i< kort.length; i++){
        kort[i] = new JLabel();
        add(kort[i]);
        kort[i].addMouseListener(this);
    }
    return null;
}

public JLabel kortForside(){
    int tilfeldig;
    int tracker;
    tracker = 0;
    tilfeldig = (int)(Math.random()*8);
    while (tracker < kort.length ){
        if (index[tilfeldig]<2){
            kortForside[tracker] = new JLabel(forside[tilfeldig]);
            tracker++;
            index[tilfeldig]++;
        }
    }

    return null;
}

public void bilder(){

    for (int i = 0; i<kort.length; i++){
        kort[i] = new JLabel(bakside);
    }

}


@Override
public void mouseClicked(MouseEvent agr0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseEntered(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseReleased(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getActionCommand().equals("Del ut kortene")){  
        bilder();

    }

}

2 个答案:

答案 0 :(得分:1)

我看到你用这样的图标创建了一些标签:

kortForside[tracker] = new JLabel(forside[tilfeldig]);

但是,您的代码中没有任何地方可以将这些标签添加到GUI中。

与您创建的没有图像的其他标签数组不同:

for (int i = 0; i< kort.length; i++){
    kort[i] = new JLabel();
    add(kort[i]);

答案 1 :(得分:1)

在bilder中,改变:

 kort[i] = new JLabel(bakside);

为:

 kort[i].setIcon(bakside);

这样就可以更新面板上的实际标签。在您创建新标签而不是更改现有标签之前。

可能需要在持有标签的容器上调用重绘。