gpt4 book ai didi

java - Repaint() 方法不会重新绘制需要的内容

转载 作者:行者123 更新时间:2023-12-01 18:22:23 27 4
gpt4 key购买 nike

这就是我的任务。

我必须生成 4 张随机卡。之后,当按下“刷新”按钮时,卡片应再次随机化。我已经像这样实现了 repaint() 方法,但它不会改变卡片的显示方式。

public class FourCards extends JFrame {

JLabel slot1 = new JLabel(getImage());
JLabel slot2 = new JLabel(getImage());
JLabel slot3 = new JLabel(getImage());
JLabel slot4 = new JLabel(getImage());

public FourCards() {

JPanel CardsPanel = new JPanel(new GridLayout(1,4,5,5));
add(CardsPanel);

CardsPanel.add(slot1);
CardsPanel.add(slot2);
CardsPanel.add(slot3);
CardsPanel.add(slot4);

JButton jbtRefresh = new JButton("Refresh");

JPanel ButtonPanel = new JPanel();
this.add(ButtonPanel, BorderLayout.SOUTH);
ButtonPanel.add(jbtRefresh);

jbtRefresh.addActionListener(new ButtonListener());

}

public ImageIcon getImage() {

ImageIcon temp = new ImageIcon("C:/resized/" + (int)(Math.random() * 52) + ".png");
return temp;

}

public void update() {

slot1 = new JLabel(getImage());
slot2 = new JLabel(getImage());
slot3 = new JLabel(getImage());
slot4 = new JLabel(getImage());

}

public static void main(String[] args) {

FourCards frame = new FourCards();
frame.setTitle("Random 4 cards");
frame.setSize(600,280);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

}

class ButtonListener implements ActionListener {

@Override
public void actionPerformed(ActionEvent e) {

update(); // get new images
repaint();

}

}

}

最佳答案

当你这样做时

slot1 = new JLabel(getImage());
slot2 = new JLabel(getImage());
slot3 = new JLabel(getImage());
slot4 = new JLabel(getImage());

您没有更改 GUI。您正在更新 slotX 变量的值。您还应该替换 GUI 树中的实际组件。

尝试将 CardsPanel 设为成员变量,然后执行

CardsPanel.removeAll();
CardsPanel.add(new JLabel(getImage()));
CardsPanel.add(new JLabel(getImage()));
CardsPanel.add(new JLabel(getImage()));
CardsPanel.add(new JLabel(getImage()));

关于java - Repaint() 方法不会重新绘制需要的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27346629/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com