嗨,我在点击刷新按钮后重新绘制 JPanel 时遇到了很多麻烦,在我的真实应用程序中,我有代表模型文件列表的 Jlabels,每次点击刷新按钮时,Jpanel 中显示的 Jlabels 列表必须是相应地更新,我在做这件事时遇到了很多麻烦,所以在这里我做了一个简单的干净和可编译的例子,我希望在点击刷新按钮后,JPanel 被清理(只是为了让事情变得简单)。因此,我确保在 EDT 中调用了更新,我在 chnaged Jpanel (panConf) 上手动进行了无效,并将重新验证调用到最高的 comp,即 JFrame。没有任何效果,所以我添加了重绘,但它也没有奏效。请问你能帮帮我吗 ?
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class PanRepaint extends JFrame {
private JPanel pan1;
private JPanel mainPanel;
private JPanel panConf;
private JFrame dis;
public PanRepaint() {
JLabel label1 = new JLabel("ZAZAZA");
JLabel label2 = new JLabel("Label 2");
JButton btn = new JButton("Update");
dis = this;
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
panConf = new JPanel();
panConf.invalidate();
//dis.invalidate();
dis.validate();
dis.repaint();
}
});
}
});
panConf = new JPanel();
pan1 = new JPanel();
mainPanel = new JPanel();
panConf.add(label1);
panConf.add(label2);
pan1.add(btn);
mainPanel.add(panConf);
mainPanel.add(pan1);
setContentPane(mainPanel);
this.setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
PanRepaint pr = new PanRepaint();
}
}