我试图用"刷新"按钮刷新一个图标面板,但无法确定在事件处理程序中放入什么来执行此任务。我只需要执行一次任务的代码(如下)。有人能帮我吗?
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class FourRandomCards extends JFrame {
JButton jbtRefresh = new JButton("Refresh");
CardsPanel cardsPanel = new CardsPanel();
public FourRandomCards() {
add(cardsPanel, BorderLayout.CENTER);
add(jbtRefresh, BorderLayout.SOUTH);
//=============================================================
/** can't figure out what to put in event-handler **/
jbtRefresh.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
}
});
//=============================================================
}
public static void main(String[] args) {
JFrame frame = new FourRandomCards();
frame.setTitle("Four Random Cards");
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private class CardsPanel extends JPanel {
public CardsPanel() {
for (int i = 0; i < 4; i++) {
int card = (int)(Math.random() * 54 + 1);
ImageIcon cardIcon = new ImageIcon
("image/card/" + card + ".png");
JLabel jlblCard = new JLabel(cardIcon);
add(jlblCard);
}
}
}
}
基本上,您需要删除所有现有组件并重新添加它们。这意味着您需要一些能够满足此要求的方法。
因为您使用的是局部变量,所以您将无法访问cardsPanel
变量,除非您将其设为final
或使用类实例变量。。。
public class FourRandomCards extends JFrame {
JButton jbtRefresh = new JButton("Refresh");
final CardsPanel cardsPanel = new CardsPanel();
public FourRandomCards() {
add(cardsPanel, BorderLayout.CENTER);
add(jbtRefresh, BorderLayout.SOUTH);
//=============================================================
/** can't figure out what to put in event-handler **/
jbtRefresh.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cardsPanel.refresh();
}
});
//=============================================================
}
public static void main(String[] args) {
JFrame frame = new FourRandomCards();
frame.setTitle("Four Random Cards");
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private class CardsPanel extends JPanel {
public CardsPanel() {
refresh();
}
public void refresh() {
removeAll();
for (int i = 0; i < 4; i++) {
int card = (int)(Math.random() * 54 + 1);
ImageIcon cardIcon = new ImageIcon
("image/card/" + card + ".png");
JLabel jlblCard = new JLabel(cardIcon);
add(jlblCard);
}
revalidate();
repaint();
}
}
}