【发布时间】:2015-06-19 11:55:11
【问题描述】:
抱歉标题不好,想不到更好的了。
我正在开发一款纸牌游戏。
下面的方法接受一个 Card 对象作为参数,并返回一个 JLayeredPane 和一个带有卡片图像的 JLabel。
private JLayeredPane getCardPane(Card card) {
JLayeredPane cardPane = new JLayeredPane();
GridBagLayout gblCardPane = new GridBagLayout();
cardPane.setLayout(gblCardPane);
cardImageIcon = card.getImageIcon();
JLabel lblCard = new JLabel() {
@Override
public void paintComponent(Graphics g) {
g.drawImage(cardImageIcon.getImage(), 0, 0, null);
super.paintComponent(g);
}
};
GridBagConstraints gbcLblCard = new GridBagConstraints();
cardPane.add(lblCard,gbcLblCard);
return cardPane;
}
我有一个类似下面的部分,将我手中的所有卡片添加到另一个 JLayeredPane jlpMyCards:
for (int i = 0; i < hand.getCardCount(); i++) {
JLayeredPane thisCard = getCardPane(hand.getCard(i));
//JOptionPane.showMessageDialog(null,thisCard);
jlpMyCards.add(thisCard);
}
最后将 jlpMyCards 添加到框架中。
在渲染帧上,我看到所有卡片都在手(按计数),但所有卡片都显示最后加载的图像。 - 为什么?
我尝试用
打印卡片JOptionPane.showMessageDialog(null,thisCard);
弹出对话框显示正确的图像。
注意:我猜 Card 类中的以下方法也可能会产生问题。
public ImageIcon getImageIcon() {
BufferedImage img = null;
try {
img = ImageIO.read(new File(this.getClass().getResource(
getValueAsString().toLowerCase() + "_of_"+
getSuitAsString().toLowerCase() + ".png").toURI()));
//Rescaling Image
Image dimg = img.getScaledInstance(100, 146, Image.SCALE_SMOOTH);
return new ImageIcon(dimg);
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
【问题讨论】:
-
@AndrewThompson 我不知道 MCVE。我会把问题放在 MCVE 中;)
-
@AndrewThompson 按照您在第二条评论中的建议进行了更改。
-
猜测一下,您的
for循环阻塞了 EDT;见Concurrency in Swing 和How to Use Swing Timers。 -
为什么要绘制图标而不是设置 JLabel 的图标?
标签: java swing bufferedimage