可能重复:
When does one need to call revalidate() on a swing component to make it refresh, and when not?
我正在用Java编写一个Explorer程序,它的工作原理如下 我输入来自用户的路径,用户按下后输入路径设置的文本框,并计算文件夹的列表,并创建相应的标签,这些标签应该显示在窗口上但是应用程序没有t显示文件夹的新内容,如果我更改文本然后它指向一个新目录,所以当我按回车键时,它必须显示加载的新目录的内容,但只有在调整窗口大小后才会显示新内容框架
代码如下
package explorer;
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Explorer extends JFrame{
File file;
Scanner scan;
String path;
String [] listOfFiles;
JTextField txtPath;
JLabel lblLocation;
JLabel child[];
JPanel childPanel;
JPanel masterPanel;
public Explorer(){
lblLocation = new JLabel("Location: ");
/*
* the declaration of panels
*/
masterPanel = new JPanel();
childPanel = new JPanel();
JPanel panel = new JPanel();
/*declaration of other components*/
txtPath = new JTextField("",20);
/*addition of components to panel for layout*/
panel.add(lblLocation);
panel.add(txtPath);
/*adding to master panel, for sophisticated layout*/
masterPanel.add(panel, BorderLayout.NORTH);
masterPanel.add(childPanel, BorderLayout.SOUTH);
getContentPane().add(masterPanel);
/*this place from where address is fetched like /home/revolution/Desktop etc on ubuntu*/
txtPath.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
childPanel.removeAll();
path = new String(txtPath.getText());//the absolute path
file = new File(path);
File childFiles[];
String name = path.substring(path.lastIndexOf('/')+1, path.length());//the name of the directory being displayed
setTitle(name);
if(!file.isDirectory()){
JOptionPane.showMessageDialog(null, "Error file is not a directory");
} else {
listOfFiles = file.list();
child = new JLabel[listOfFiles.length];// labels equal to the number fo files and with name of the coresponding file/folder
childFiles = new File[listOfFiles.length];//references to files
childPanel.setLayout(new GridLayout(listOfFiles.length/2,listOfFiles.length/2));//setting grid layout
for(int i=0; i<listOfFiles.length;i++){
childFiles[i] = new File(listOfFiles[i]);
child[i] = new JLabel(listOfFiles[i]);
child[i].setToolTipText(childFiles[i].isFile()?"File":"Folder");
childPanel.add(child[i]);
}
childPanel.setVisible(true);
}
}
});
}
}
有什么不对?我如何“刷新”窗口的内容?
答案 0 :(得分:1)
我认为您需要revalidate()
小组。
更准确地说,在您的动作侦听器结束时,您可以添加childPanel.revalidate();
childPanel.setVisible(true);
}
}
childPanel.revalidate();
});