【发布时间】:2016-10-08 18:49:34
【问题描述】:
我正在尝试将ImageIcon 放在JLabel 上,但它没有出现在JFrame 中。我找不到错误的代码,我的控制台也没有显示任何错误。
代码如下:
public class Gui extends JFrame implements ActionListener {
private JLabel card;
private JButton bBet;
private ImageIcon c2 = new ImageIcon("./images/c2.jpg");
private ImageIcon d2 = new ImageIcon("./images/d2.jpg");
private ImageIcon h2 = new ImageIcon("./images/h2.jpg");
private ImageIcon s2 = new ImageIcon("./images/s2.jpg");
private JPanel panel;
private int cardx1 = 250, cardy1 = 400;
public Gui() {
this.setTitle("Simple Blackjack");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1200, 800);
this.setLayout(null);
panel = new JPanel();
panel.setBounds(10, 10, 1200, 800);
panel.setLayout(null);
bBet = new JButton("Bet");
bBet.setBounds(10, 70, 200, 35);
bBet.addActionListener(this);
panel.add(bBet);
this.add(panel);
this.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == bBet) {
random = getRandom();
addLabel(cardx1, cardy1, random);
}
}
public void addLabel(int x, int y, int random) {
Random r = new Random(4);
int which = r.nextInt();
card = new JLabel();
card.setBounds(x, y, 166, 230);
switch (random) {
case 0:
if (which == 0){
card.setIcon(c2);
} else if (which == 1) {
card.setIcon(d2);
} else if (which == 2) {
card.setIcon(h2);
} else if (which == 3) {
card.setIcon(s2);
}
break;
}
panel.add(card);
panel.repaint();
}
【问题讨论】:
-
你在哪里添加了图片图标?
-
这里:私有 ImageIcon c2 = new ImageIcon("./images/c2.jpg");在这里:card.setIcon(c2);
-
尝试重新验证您的面板 (
panel.revalidate()) -
空布局所以重新验证什么都不做
-
@E.Reu 图像部分仅在 actionperform 发生时才有效。只需为您的 jlable 设置背景颜色,看看它是否可见?
card = new JLabel(); card.setOpaque(true); card.setBackground(Color.yellow);
标签: java image swing awt imageicon