1

所以我有一个我正在研究的程序,它在框架中显示 3 张带有标签的随机卡片。到目前为止,我已经将一副纸牌分配给 ImageIcons 数组,然后将它们洗牌。我的问题是,我现在如何将它们分配给 JLabels。请原谅我这个愚蠢的问题,因为我知道这很简单,但我对使用 GUI 很陌生,这让我害怕哈哈

到目前为止,这是我的代码:

package assignment2;
import javax.swing.*;

import java.awt.*;
public class Assignment2 extends JFrame{
    public Assignment2(){

        setLayout(new GridLayout(3,1,5,5));
        add(new JLabel()); ///display one random card
        add(new JLabel()); ////display another random card
        add(new JLabel()); ////display another random card
    }
    public static void main(String[] args) {

        Assignment2 frame = new Assignment2();
        frame.setTitle("MAIN TO THE FRAME");
        frame.setSize(600,300);
        frame.setResizable(true);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final int FINAL_CARDS_NUMBER = 54;

        ImageIcon deckOfCards [] = new ImageIcon [FINAL_CARDS_NUMBER];

        for(int i = 0; i <FINAL_CARDS_NUMBER; i++){
            deckOfCards[i] = new ImageIcon("C:/card/" + (i + 1) + ".png");
        }

        for (int i = 0; i < FINAL_CARDS_NUMBER; i++) {
            int r = i + (int) (Math.random() * (FINAL_CARDS_NUMBER-i));
            ImageIcon t = deckOfCards[r];
            deckOfCards[r] = deckOfCards[i];
            deckOfCards[i] = t;
        }
    }
}
4

1 回答 1

6

First, remove the 3 lines where you add the labels:

add(new JLabel());

Then, in the place where you are getting the ImageIcon, do this:

ImageIcon t = deckOfCards[r];
JLabel label = new JLabel(t);
add(label);

However, I suggest you don't set the layout and add components directly to your JFrame. You would better create a new JPanel and add that to the content pane of your JFrame:

JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 1, 5, 5));
getContentPane().add(panel);

Then, when you add the labels, add them to the panel.

panel.add(new JLabel(t));

Now that you updated the question, I am updating the answer below. First, declare 3 JLabel, instantiate them and add them to the panel as explained above.

JLabel card1 = new JLabel();
JLabel card2 = new JLabel();
JLabel card3 = new JLabel();

Then, after you read the ImageIcon for each, you can set the JLabel image this way:

card1.setIcon(t);
于 2012-09-28T16:31:29.427 回答