JAVA:如何将.png文件加载到JLabel

时间:2017-09-18 19:57:57

标签: java swing jframe png jlabel

我正在输入我的第一个对象程序--BlackJack,我的打印卡图像有问题。 我的班级卡扩展了JLabel并具有ImageIcon属性。

package Blackjack;

import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;

public class Card extends JLabel{
    private final String suit, faceName;
    private int cardValue;
    private boolean isVisible = false;
    private BufferedImage cardImage;
    public ImageIcon cardIcon;

public Card(String suit, String faceName){
    this.suit = suit;
    this.faceName = faceName;
    //this.cardImage = getCardImage();
    this.cardIcon = new ImageIcon(getCardImage());

    switch(faceName){
        case "2":
            this.cardValue = 2;
            break;
        case "3":
            this.cardValue = 3;
            break;
        case "4":
            this.cardValue = 4;
            break;
        case "5":
            this.cardValue = 5;
            break;
        case "6":
            this.cardValue = 6;
            break;
        case "7":
            this.cardValue = 7;
            break;
        case "8":
            this.cardValue = 8;
            break;
        case "9":
            this.cardValue = 9;
            break;
        case "10":
            this.cardValue = 10;
            break;
        case "Jack":
            this.cardValue = 10;
            break;
        case "Queen":
            this.cardValue = 10;
            break;
        case "King":
            this.cardValue = 10;
            break;
        case "Ace":
            this.cardValue = 11;
            break;
    }
}

public void setCardVisible(boolean v){
    isVisible = v;
}
public boolean getVisible(){
    return isVisible;
}
public String getCardName(){
    if (isVisible)
        return faceName + " of " + suit;
    else
        return "Karta zakryta";
}
public int getCardValue(){
    if (isVisible)
        return cardValue;
    else
        return 0;
}
public BufferedImage getCardImage(){ //dopisać
    String fileName;
    if (faceName.equals("10"))
        fileName = "T";
    else if (faceName.equals("Jack"))
        fileName = "J";
    else if (faceName.equals("Queen"))
        fileName = "Q";
    else if (faceName.equals("King"))
        fileName = "K";
    else if (faceName.equals("Ace"))
        fileName = "A";
    else
        fileName = faceName;
    fileName = fileName + suit.substring(0, 1).toUpperCase();
    File imgFile = new File("img/" + fileName + ".png");
    try{
        if (isVisible)
            cardImage = ImageIO.read(imgFile);
        else
            cardImage = ImageIO.read(new File("img/RE.png"));
    }
    catch (IOException e) {
        System.err.println("Blad odczytu obrazka");
        e.printStackTrace();
    }
    Dimension dimension = new Dimension(cardImage.getWidth(), cardImage.getHeight());
    setPreferredSize(dimension);
    return cardImage;
}
}

下一课是Table extended JPanel

package Blackjack;

import java.awt.Color;
import javax.swing.JPanel;

public class Table extends JPanel{
    private Deck deck;
    private Player player;
    private Dealer dealer;
    private Hand dealerHand;
    private Hand playerHand;

public Table(Deck d, Dealer dealer, Player player){
    this.deck = d;
    this.deck.shuffleDeck();
    this.dealer = dealer;
    this.player = player;
    this.dealerHand = dealer.getPlayerHand();
    this.playerHand = player.getPlayerHand();

    this.setBackground(Color.GREEN);
}

public Player getPlayer(){
    return player;
}
public Dealer getDealer(){
    return dealer;
}
public Deck getDeck(){
    return deck;
}

}

类游戏扩展了JFrame

package Blackjack;

import java.awt.BorderLayout;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;

public class Game extends JFrame{
    private Table table;

public Game(Table t){
    JFrame frame = new JFrame("BlackJack game");
    frame.setSize(800, 500);
    frame.setLayout(new BorderLayout());

    frame.add(t, BorderLayout.CENTER);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main (String[] args){
    Deck deck = new Deck();
    Player player = new Player();
    Dealer dealer = new Dealer();

    Table table = new Table (deck, dealer, player);

    player.hitCard(deck.drawCard());
    player.getPlayerHand().getCardsInHand().get(0).setCardVisible(true);
    table.getDealer().hitCard(table.getDeck().drawCard());
    dealer.getPlayerHand().getCardsInHand().get(0).setCardVisible(true);
    player.hitCard(deck.drawCard());
    player.getPlayerHand().getCardsInHand().get(1).setCardVisible(true);
    dealer.hitCard(deck.drawCard());

    table.add(player.getPlayerHand().getCardsInHand().get(0));

    for (Card c : player.getPlayerHand().getCardsInHand())
        System.out.println(c.getCardName());
    for (Card c : dealer.getPlayerHand().getCardsInHand())
        System.out.println(c.getCardName());

Game g = new Game(table);

}
}

如何在窗口上正确添加卡片图像?因为这个

table.add(player.getPlayerHand().getCardsInHand().get(0));

没有工作......我只看到带有JPanels的空绿色窗口。

2 个答案:

答案 0 :(得分:1)

主要问题是,您实际上从未设置icon的{​​{1}}属性,因此无法显示

我建议做的是创建面部和背面图像的实例,当可见状态发生变化时,更改JLabel属性

icon

您无需更改public class Card extends JLabel { private final String suit, faceName; private int cardValue; private boolean isVisible = false; private BufferedImage faceImage; private BufferedImage backImage; public Card(String suit, String faceName) { this.suit = suit; this.faceName = faceName; this.faceImage = getCardFaceImage(); backImage = getCardBackImage(); setCardVisible(false); switch (faceName) { case "2": this.cardValue = 2; break; case "3": this.cardValue = 3; break; case "4": this.cardValue = 4; break; case "5": this.cardValue = 5; break; case "6": this.cardValue = 6; break; case "7": this.cardValue = 7; break; case "8": this.cardValue = 8; break; case "9": this.cardValue = 9; break; case "10": this.cardValue = 10; break; case "Jack": this.cardValue = 10; break; case "Queen": this.cardValue = 10; break; case "King": this.cardValue = 10; break; case "Ace": this.cardValue = 11; break; } } public void setCardVisible(boolean v) { isVisible = v; if (isVisible) { setIcon(new ImageIcon(faceImage)); } else { setIcon(new ImageIcon(backImage)); } } public boolean isCardVisible() { return isVisible; } public String getCardName() { if (isVisible) { return faceName + " of " + suit; } else { return "Karta zakryta"; } } public int getCardValue() { if (isVisible) { return cardValue; } else { return 0; } } protected BufferedImage getCardFaceImage() { //dopisać String fileName; if (faceName.equals("10")) { fileName = "T"; } else if (faceName.equals("Jack")) { fileName = "J"; } else if (faceName.equals("Queen")) { fileName = "Q"; } else if (faceName.equals("King")) { fileName = "K"; } else if (faceName.equals("Ace")) { fileName = "A"; } else { fileName = faceName; } BufferedImage img = new BufferedImage(100, 200, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setColor(Color.RED); g2d.fill(new Rectangle(100, 200)); g2d.dispose(); // fileName = fileName + suit.substring(0, 1).toUpperCase(); // File imgFile = new File("img/" + fileName + ".png"); // try { // if (isVisible) { // cardImage = ImageIO.read(imgFile); // } else { // cardImage = ImageIO.read(new File("img/RE.png")); // } // } catch (IOException e) { // System.err.println("Blad odczytu obrazka"); // e.printStackTrace(); // } // Dimension dimension = new Dimension(cardImage.getWidth(), cardImage.getHeight()); // setPreferredSize(dimension); return img; } protected BufferedImage getCardBackImage() { //dopisać BufferedImage img = new BufferedImage(100, 200, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setColor(Color.BLUE); g2d.fill(new Rectangle(100, 200)); g2d.dispose(); return img; } } preferredSize将自行处理。

当您更改卡片的可见性状态时,请不要忘记切换图像...

JLabel

在加载图像后,不要忘记在构造函数中调用它;)

作为一般性建议,不要将public void setCardVisible(boolean v) { isVisible = v; if (isVisible) { setIcon(new ImageIcon(faceImage)); } else { setIcon(new ImageIcon(backImage)); } } 作为卡名称/套装处理,而是允许大量可能的错误,而是使用String

将值约束到一个小的已知组
enum

虽然这看起来像是一个挑剔(而且有点像),你可以扩展public enum CardFace { TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, JACK, QUEEN, KING, ACE } public enum CardSuit { HEARTS, DIAMONDS, CLUBS, SPADES } public class Card extends JLabel { private CardSuit suit; private CardFace face; //... public Card(String CardSuits, CardFace faceName) { 来做其他任务,例如,你可以为每个实例分配它的名字

enum

您甚至可以将面值分配给public enum CardFace { TWO("Two"), ...; private String name; private CardFace(String name) { this.name = name; } public String getName() { return name; } } ...

enum

答案 1 :(得分:-1)

不要在扩展类中创建另一个False(也由@ user1803551指出),只需将帧设置为此即可。这仍然只给你一个窗口。

JFrame

您添加到框架中的任何内容都可以直接从public class Game extends JFrame{ private Table table; public Game(Table t){ setSize(800, 500); setLayout(new BorderLayout()); add(t, BorderLayout.CENTER); //setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main (String[] args){ Deck deck = new Deck(); Player player = new Player(); Dealer dealer = new Dealer(); Table table = new Table (deck, dealer, player); player.hitCard(deck.drawCard()); player.getPlayerHand().getCardsInHand().get(0).setCardVisible(true); table.getDealer().hitCard(table.getDeck().drawCard()); dealer.getPlayerHand().getCardsInHand().get(0).setCardVisible(true); player.hitCard(deck.drawCard()); player.getPlayerHand().getCardsInHand().get(1).setCardVisible(true); dealer.hitCard(deck.drawCard()); table.add(player.getPlayerHand().getCardsInHand().get(0)); for (Card c : player.getPlayerHand().getCardsInHand()) System.out.println(c.getCardName()); for (Card c : dealer.getPlayerHand().getCardsInHand()) System.out.println(c.getCardName()); Game g = new Game(table); //g.setLayout(new BorderLayout()); //g.add(table, BorderLayout.CENTER); // your table g.setVisible(true); } 类完成。

编辑:添加了布局和Game(再次删除)

EDIT2:

在您的代码中,我注意到您确实使用Table进行调试输出。如果没有关于输出的更多信息,除了验证您的图像是否正确加载,甚至文件存在(System.out.println())之外,还没有其他建议,这将显示路径是否也正确。如果它们加载,则输出图像的尺寸并确保File.exists()也已设置。

我最好的建议是使用更多的调试输出来查找问题所在。缺少类JLableDeck,这只会引导我们推测。