有谁知道如何刷新我的JFrame
以便我可以展示我的新JButton
?
private void displayGrid()
{
Case arrayGrid [][] = Grid.returnArray();
for(int i = 0; i < Settings.returnYGrid(); i++)
{
for(int j = 0; j < Settings.returnXGrid(); j++)
{
Case caase = arrayGrid [i][j];
panel.add(caase.getButton());
}
}
这是我在创建JFrame
时使用的方法。然后,我想使用相同的方法刷新我的JFrame
,因为Case
中的某些arrayGrid
已发生变化,根本没有发生任何事情......
我尝试设置revalidate()
,repaint()
,也没有。
答案 0 :(得分:3)
尝试在方法结尾处添加对revalidate
和repaint
的调用...
private void displayGrid()
{
Case arrayGrid [][] = Grid.returnArray();
for(int i = 0; i < Settings.returnYGrid(); i++)
{
for(int j = 0; j < Settings.returnXGrid(); j++)
{
Case caase = arrayGrid [i][j];
panel.add(caase.getButton());
}
}
panel.revalidate();
panel.repaint();
}
更新了工作示例
public class TestFrame02 {
public static void main(String[] args) {
new TestFrame02();
}
public TestFrame02() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JPanel panel = new JPanel(new GridLayout(0, 4));
JButton update = new JButton("Update");
update.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (int index = 0; index < 20; index++) {
panel.add(new JLabel(Integer.toString(index)));
}
panel.revalidate();
panel.repaint();
}
});
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(panel);
frame.add(update, BorderLayout.SOUTH);
frame.setSize(100, 100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}