在 JFrame 问题中重新加载 GUI

Reloading GUI in JFrame Troubles

我正在创建 Blackjack 游戏,每次用户单击按钮时都需要刷新 JFrame。但是,框架 未更新! 我已经尝试了数小时试图修复此问题,但没有成功。

如何根据用于加载图像的 ImageIcon 对象堆栈正确地重新加载框架中的所有元素?

这是我的代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Stack;

public class Blackjack extends JFrame implements ActionListener {
    public void drawGUI(boolean firstTime) {
        getContentPane().removeAll();

        setLayout(new GridLayout(3, 9, 1, 1));
        updateValues();

        add(new JLabel(DEALER_TEXT, SwingConstants.CENTER));
        add(new JLabel("Value: " + computerValue, SwingConstants.CENTER));
        for(int i = 0; i < computerCards.size(); i++)
            add(new JLabel(computerCards.get(i).getImagePath()));

        leaveSpacing(false);

        add(new JLabel(USER_TEXT, SwingConstants.CENTER));
        add(new JLabel("Value: " + userValue, SwingConstants.CENTER));
        for(int i = 0; i < userCards.size(); i++)
            add(new JLabel(userCards.get(i).getImagePath()));

        leaveSpacing(true);

        if(firstTime) {
            hitButton.addActionListener(this);
            standButton.addActionListener(this);
        }

        leaveSpacing(3);
        add(hitButton);
        add(standButton);
        leaveSpacing(1);
    }
}

您需要在 drawGUI(); 方法结束时调用 revalidate();repaint();。这应该可以解决问题。

之前在 SO 上已经回答过这个问题,请参阅:Java Swing revalidate and repaint

这个(工作)怎么样 mcve :

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class BalckJack extends JFrame implements ActionListener {

    private JButton hitButton = new JButton("Hit");
    private int computerValue;

    public static void main(String[] args) {

        BalckJack frame = new BalckJack();
        frame.setTitle("Cards");
        frame.setSize(800, 320);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public BalckJack() {

        computerValue = 0;

        for(int i = 0; i < 27; i++) {
            add(new JLabel(new ImageIcon("")));
        }

        drawGUI(true);
    }

    public void drawGUI(boolean firstTime) {

        getContentPane().removeAll();

        setLayout(new GridLayout(1, 2, 1, 1));

        add(new JLabel("Value: " + computerValue++, SwingConstants.CENTER));

        if(firstTime) {
            hitButton.addActionListener(this);
        }

        add(hitButton);
        revalidate();  //(!!!!)
    }

    @Override
    public void actionPerformed(ActionEvent evt) {

        drawGUI(false);
    }
}