我正在尝试使框架中有两个面板。一个显示 4 张卡片,另一个显示一个按钮。单击按钮时,将再次随机选择四张卡。当我初始化程序或单击刷新时,卡片没有显示。 谁能解释我做错了什么以及我需要做什么来解决这个问题?
这是我的代码
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class MyFrame extends JFrame{
public MyFrame(){
super("Random Cards");
CardPanel cardPanel = new CardPanel();
JPanel buttonPanel = new JPanel();
JButton jbtRefresh = new JButton("Refresh");
buttonPanel.add(jbtRefresh);
add(cardPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
jbtRefresh.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
cardPanel.refresh();
}
});
}
public static void main(String[] args){
MyFrame f = new MyFrame();
f.setDefaultCloseOperation(MyFrame.EXIT_ON_CLOSE);
f.setSize(500, 300);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public class CardPanel extends JPanel{
JLabel l1;
JLabel l2;
JLabel l3;
JLabel l4;
void CardPanel(){
refresh();
}
void refresh(){
l1 = new JLabel(new ImageIcon("image/card/" + (int)(1 + Math.random() * 54) + ".png"));
l2 = new JLabel(new ImageIcon("image/card/" + (int)(1 + Math.random() * 54) + ".png"));
l3 = new JLabel(new ImageIcon("image/card/" + (int)(1 + Math.random() * 54) + ".png"));
l4 = new JLabel(new ImageIcon("image/card/" + (int)(1 + Math.random() * 54) + ".png"));
removeAll();
add(l1);
add(l2);
add(l3);
add(l4);
repaint();
}
}
}
最佳答案
简短回答
调用refresh
时,在repaint
之前调用revalidate
...
更长、更合适的答案
考虑使用 CardLayout
代替。请参阅How to Use CardLayout了解更多详情
还有...
- 确保您仅在事件调度线程的上下文中创建/修改 UI,请参阅 Initial Threads了解更多详情。
- 您可能会考虑创建一个
Card
类,该类从JPanel
等扩展而来,负责显示特定的卡片。这样,您可以简单地计算所需的随机卡值并不断更新预先存在的实例,而不是每次都创建新实例。一般来说,它会运行得更快,效率更高
挑剔:您应该避免直接从 JFrame
等顶级容器扩展您的 UI,它们往往会将您锁定在单个用例中,并使将来难以重用或扩展。无论如何,您并没有真正向框架添加任何新功能
关于java - JPanel 组件在尝试刷新后消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28057415/