Отображение карт из массива колоды в графическом интерфейсе

У меня есть класс карт и колод. Особенности класса Deck и массив объектов Card. Мне нужно взять случайную карту из колоды и отобразить в метке графического интерфейса. Я пытаюсь создать путь к картам JPG в папке активов «колода», и по какой-то причине компоненту GUI не нравится значение масти и ранга. Может быть проблема с переменной областью... Вот что у меня внутри события для моей кнопки: path.concat(d.drawRandomCard().tostring()).concat(ftype). У меня есть этот код, работающий в моем тестовом классе без графического интерфейса. Я пытаюсь заставить View работать с моими моделями в ООП.

showCard.java

    import javax.swing.*;

import java.awt.event.*;
import java.awt.Color;
import java.awt.Image;

import javax.swing.ImageIcon;


public class ShowCards implements ActionListener {
    final static String LABEL_TEXT = "Random Card!!";
    JFrame frame;
    JPanel contentPane;

    JButton drawCard;
    Card c;
    Deck d;
    JLabel dieFace;
    JLabel testing;

    int[] location = new int[2];
    Image image;

    String path = "deck/";
    String ftype = ".jpg";


    public ShowCards(){
        JButton drawCard;
        JLabel dieFace;
        JLabel testing;

            /* Create and set up the frame */
            frame = new JFrame("Roll");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            /* Create a content pane with a BoxLayout and
             empty borders */
            contentPane = new JPanel();
            contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            contentPane.setBackground(Color.white);
            contentPane.setLayout(new BoxLayout(contentPane,BoxLayout.PAGE_AXIS));

            /* Create a label that shows a die face */
            dieFace = new JLabel(new ImageIcon(this.getClass().getResource("deck/h04.jpg")));
            dieFace.setAlignmentX(JLabel.CENTER_ALIGNMENT);
            dieFace.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
            contentPane.add(dieFace);


            /* Create a label for testing */
            testing = new JLabel("Kiley");
            testing.setAlignmentX(JLabel.CENTER_ALIGNMENT);
            testing.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
            contentPane.add(testing);

            /* Create a Roll Die button */
            drawCard = new JButton("Draw Card");
            drawCard.setAlignmentX(JButton.CENTER_ALIGNMENT);
            drawCard.addActionListener(this);
            contentPane.add(drawCard);

            /* Add content pane to frame */
            frame.setContentPane(contentPane);

            /* Size and then display the frame. */
            frame.pack();
            frame.setVisible(true);
        }


        /**
         * Handle a button click
         * pre: none
         * post: A die has been rolled. Matching image shown.
         */
        public void actionPerformed(ActionEvent event) {

            String drawncard = d.store.getCardSuit().toString()+d.store.getCardRank().toString();       


            //dieFace.setIcon(new ImageIcon(this.getClass().getResource("deck/d.drawRandomCard() + ".jpg")));
            //dieFace.setIcon(new ImageIcon(this.getClass().getResource("deck/s13.jpg")));
            //dieFace = new JLabel(new ImageIcon(this.getClass().getResource("deck/" + d.drawRandomCard().toString()+ ".jpg")));
            //dieFace = new JLabel(new ImageIcon(this.getClass().getResource(path.concat(d.store.getCardSuit().toString()).concat(d.store.getCardRank().toString()).concat(ftype))));
            dieFace = new JLabel(new ImageIcon(this.getClass().getResource(path.concat(drawncard).concat(ftype))));

            // parsing  dieFace = new JLabel(new ImageIcon(this.getClass().getResource(path.concat(String.valueOf(d.drawRandomCard().toString())).concat(ftype))));
            //dieFace = new JLabel(new ImageIcon(this.getClass().getResource("deck/s13.jpg")));
            dieFace.setAlignmentX(JLabel.CENTER_ALIGNMENT);
            dieFace.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
            contentPane.add(dieFace);
            /* Add content pane to frame */
            frame.setContentPane(contentPane);

            /* Size and then display the frame. */
            frame.pack();
            frame.setVisible(true);



            /* int newRoll;

            newRoll = (int)(6 * Math.random() + 1);
            if (newRoll == 1) {
                dieFace.setIcon(new ImageIcon("die1.gif"));
            } else if (newRoll == 2) {
                dieFace.setIcon(new ImageIcon("die2.gif"));
            } else if (newRoll == 3) {
                dieFace.setIcon(new ImageIcon("die3.gif"));
            } else if (newRoll == 4) {
                dieFace.setIcon(new ImageIcon("die4.gif"));
            } else if (newRoll == 5) {
                dieFace.setIcon(new ImageIcon("die5.gif"));
            } else if (newRoll == 6) {
                dieFace.setIcon(new ImageIcon("die6.gif"));
            }

            */


        }


    public Image getImage(){
        ImageIcon ii = new ImageIcon(this.getClass().getResource("deck/h04.jpg"));
        image = ii.getImage();
        return image;
    }
    public void setLocation(int x, int y){
        location[0] = x;
        location[1] = y;
    }
    public int [] getLocation(){
        return location;
    }


    /**
     * Create and show the GUI.
     */
    private static void runGUI() {
        JFrame.setDefaultLookAndFeelDecorated(true);

        ShowCards greeting = new ShowCards();

    }


    public static void main(String[] args) {
        /* Methods that create and show a GUI should be
           run from an event-dispatching thread */
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                runGUI();
            }
        });
    }
}

Deck.java

import java.util.Random;
import java.util.ArrayList;

public class Deck 
{

private ArrayList<Card> cards;
String mysuit,myrank;
Card store; // create an object variable to store card drawn

public Deck()
{
    cards = new ArrayList<Card>();


    for(int a =0; a<=3; a++)
    {
        for(int b =0; b<=12;b++)
        {
            cards.add(new Card(a,b));
        }
    }  
}

public Card drawRandomCard()
{
    Random generator = new Random();
    int index = generator.nextInt(cards.size());
    //return cards.remove(index);
    //return cards.get();
    store = cards.get(index);
    mysuit = store.getCardSuit().toString();
    myrank = store.getCardRank().toString();
    return cards.remove(index);




}




public String toString()
{
    String result = "Cards remaining in deck: " + cards;

        return result;

    }    
}

Карта.java

 public class Card
{
    //private String suit;
    private int suit, rank; 
    //private int type, value;
    //private String[] cardSuit = {"Clubs", "Spades", "Diamonds", "Hearts"};
    //private String[] cardRank = {"Ace", "King", "Queen", "Jack", "10",
       //                            "9", "8", "7", "6", "5", "4", "3", "2"};

    private String[] cardSuit = {"c", "d", "h", "s"};
    private String[] cardRank = {"01", "02", "03", "04", "05",
                                   "06", "07", "08", "09", "10", "11", "12", "13"};




    //constructor called to fill in Deck object
    public Card(int suit, int rank)
    {
        this.suit = suit;
        this.rank = rank;
    }

    //access data
    public int getSuit()
    {
    return this.suit;
    }
    public int getRank()
    {
        return this.rank;
    }   

    // have to change Card class to get letter + number combos

    //access data
        public String getCardSuit()
        {
        return cardSuit[this.suit];
        }
        public String getCardRank()
        {
            return cardRank[this.rank];
        }   






    /* public String toString(){

        String cardinfo;
        cardinfo = this.suit + " card " + this.rank;
        return cardinfo;

    }  */

     public String toString()
        {
            //String finalCard = cardSuit[this.suit] + " of " + cardRank[this.rank];
         String finalCard = cardSuit[this.suit] + cardRank[this.rank];

            return finalCard;
        }



}// end class

Я пытаюсь построить путь к случайной карте. Например, 4 червей будет располагаться по пути: deck/h04.jpg. Мне нужно распаковать или проанализировать объект карты, чтобы я мог объединить: колода/ + h + 04 + .jpg. По какой-то причине часть «h04» не работает в компоненте GUI.

Вот класс тестера, который я использовал для тестирования карт и колод. Вы можете видеть, что путь к ресурсам работает в версии без графического интерфейса:

Тестовые классы

public class TestClasses {



    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Card c = new Card(3,12);
        System.out.println(c.getRank());
        System.out.println(c.getSuit());
        System.out.println(c);
        Deck d = new Deck();
        System.out.println("Random card:" + d.drawRandomCard());
        System.out.println("Random card rank:"+ d.store.getCardRank());
        System.out.println("Random card suit:"+ d.store.getCardSuit());
        System.out.println("Random card:" + d.drawRandomCard());
        // we need to parse THIS instance of the random card to display it.
        // A new card is removed each time the method is fired!
        System.out.println("Random card:" + d);
        System.out.println("Card Suit:" + c.getCardSuit());
        System.out.println("Card Rank:" + c.getCardRank());
        System.out.println("Random card:" + d.drawRandomCard().toString());
        System.out.println("Random card:" + d.drawRandomCard().getSuit());
        System.out.println("Random card:" + d.drawRandomCard().getRank());
        System.out.println("Random card:" + d.drawRandomCard().getCardSuit()+"Hello");
        System.out.println("Random card:" + d.drawRandomCard().getCardRank()+"09");
        System.out.println("Random card rank:"+ d.store.getCardRank());
        System.out.println("Random card suit:"+ d.store.getCardSuit());

        System.out.println(d);

        String drawncard = d.store.getCardSuit().toString()+d.store.getCardRank().toString();  

        System.out.println("Card pulled from deck:" + drawncard);
        //System.out.println();


    }

}

person HabsFan    schedule 26.08.2014    source источник
comment
Я предлагаю вам изменить весь ваш подход. Я бы создал все свои ImageIcons в начале программы, перебирая все файлы карточек, помещал их в коллекцию, такую ​​как список массивов или массив, а затем использовал их по мере необходимости. Или, что еще лучше, свяжите Icon с соответствующим и соответствующим объектом Card.   -  person Hovercraft Full Of Eels    schedule 26.08.2014
comment
Сделайте cardSuit и cardRank enum, таким образом вы никогда не будете вне досягаемости...   -  person MadProgrammer    schedule 26.08.2014