我正在创建一个二十一点游戏,每次用户点击一个按钮时都需要刷新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);
}
}
答案 0 :(得分:2)
您需要在revalidate();
方法结束时致电repaint();
和drawGUI();
。这应该可以解决问题。
之前在SO上已经回答了这个问题,请参阅:Java Swing revalidate and repaint
答案 1 :(得分:2)
这个(工作)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);
}
}