1

可能的重复:
什么时候需要在 swing 组件上调用 revalidate() 以使其刷新,什么时候不需要?

我正在用Java制作一个资源管理器程序,它的工作原理如下
我输入用户的路径,设置用户按下输入路径后的文本框并计算文件夹的列表并创建应该显示的相应标签在窗口上,
但应用程序不显示文件夹的新内容,如果我更改文本,那么它会指向一个新目录,所以当我按下回车键时,它必须显示加载的新目录的内容,但只有在调整大小后窗口是否显示框架的新内容

代码如下

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);  
          }

        }
      });
}   
}

怎么了?我怎样才能“刷新”窗口的内容?

4

1 回答 1

1

我认为你需要revalidate()面板。

更准确地说,您可以在动作监听器的末尾添加childPanel.revalidate();

      childPanel.setVisible(true);  
      }
    }
    childPanel.revalidate();
});
于 2012-05-21T18:56:58.420 回答