User Tools

Site Tools


swing:file_browser

File Browser

Παραθέτουμε ένα παράδειγμα εφαρμογής swing (παρουσιάστηκε στην τάξη στις 30/5 και 1/6) που υλοποιεί ένα file browser για τον υπολογιστή σας με την βοήθεια ενός javax.swing.JList. Δείτε την υλοποίηση του κώδικα παρακάτω και κατεβάστε το πακέτο έτοιμο προς μεταγλώττιση και εκτέλεση από εδώ.

FileBrowser.java
package ce325.swing;
 
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
 
public class FileBrowser extends JPanel {
 
  JTextField text;
  JButton nextBtn, backBtn, upBtn, homeBtn;
  JList<File> list;
  ArrayList<File> history;
  boolean showHiddenFiles = true;
 
  public FileBrowser() {
    setLayout( new BorderLayout() );
    JPanel north = new JPanel();
    add(north, BorderLayout.NORTH);
 
    backBtn = new JButton(new ImageIcon("images/back.png"));
    backBtn.setActionCommand("back");
    BackBtnListener backBtnListener = new BackBtnListener();
    backBtn.addActionListener( backBtnListener );
    backBtn.setMargin( new Insets(0,0,0,0) );
 
    upBtn = new JButton(new ImageIcon("images/up.png"));
    upBtn.setActionCommand("up");
    UpBtnListener upBtnListener = new UpBtnListener();
    upBtn.addActionListener( upBtnListener );
    upBtn.setMargin( new Insets(0,0,0,0) );
 
    homeBtn = new JButton(new ImageIcon("images/home.png"));
    homeBtn.addActionListener( new HomeBtnListener() );
    homeBtn.setMargin(new Insets(0,0,0,0));
 
    nextBtn = new JButton(new ImageIcon("images/next.png"));
    nextBtn.setActionCommand("next");
    NextBtnListener nextBtnListener = new NextBtnListener();
    nextBtn.addActionListener( nextBtnListener );
    nextBtn.setMargin( new Insets(0,0,0,0) );
 
    history = new ArrayList<>();
    history.add( new File(System.getProperty("user.home")) );
 
    text = new JTextField( System.getProperty("user.home"), 40);
    text.addActionListener( nextBtnListener );
    text.setFont( new Font("Default", Font.BOLD, 18) );
 
    north.setLayout( new FlowLayout(FlowLayout.LEFT) );
    north.add(backBtn);
    north.add(upBtn);
    north.add(homeBtn);
    north.add(text);
    north.add(nextBtn);
 
    list = new JList<File>( listFiles(System.getProperty("user.home")) );
    list.setVisibleRowCount(20);
    list.addMouseListener( new ListMouseListener() );
    MyCellRenderer renderer = new MyCellRenderer();
    list.setCellRenderer( renderer );
    JScrollPane scrollpane = new JScrollPane(list);
    add(scrollpane, BorderLayout.SOUTH);    
  }
 
  JMenuBar createMenu() {
    JMenuBar menubar = new JMenuBar();
    JMenu file = new JMenu("File");
    JMenu options = new JMenu("Options");
    menubar.add(file);
    menubar.add(options);
    JMenuItem newBrowser = new JMenuItem("New..");
    file.add(newBrowser);
    final JCheckBoxMenuItem showHidden = new JCheckBoxMenuItem("Show hidden files/folders", showHiddenFiles);
    showHidden.addActionListener( new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        showHiddenFiles = showHidden.getState();
        updateListFromCurrentDir();
      }
    });
    options.add(showHidden);
    return menubar;
  }
 
  File[] listFiles(String path) {
    File file = new File(path);
    return listFiles(file);
  }
 
  File[] listFiles(File file) {
    if( file == null || !file.exists() )
      return null;
 
    File [] files = file.listFiles();
    if( !showHiddenFiles ) {
      ArrayList<File> listedFiles = new ArrayList<>();
      for(File f : files) {
        if( f==null || f.isHidden() ) 
          continue;
        listedFiles.add(f);
      }
      files = new File[listedFiles.size()];
      for(int i=0; i<listedFiles.size(); i++) {
        files[i] = listedFiles.get(i);
      }
    }
    java.util.Arrays.sort( files, new Comparator<File>() {
      public int compare(File f1, File f2) {
        if( f1.isDirectory() && f2.isDirectory() ) 
          return f1.compareTo(f2);
        if( !f1.isDirectory() && f2.isDirectory() ) 
          return 1;
        if( f1.isDirectory() && !f2.isDirectory() ) 
          return -1;
        if( !f1.isDirectory() && !f2.isDirectory() )
          return f1.compareTo(f2);
        return 0;
      }
    });
    return files; 
  }
 
  void updateListFromText(String text) {
    File f = new File(text);
    File lastInHistory = history.get( history.size()-1);
    if( f.exists() && f.isDirectory() && !f.getAbsolutePath().equals(lastInHistory.getAbsolutePath()) ) {
      history.add(f);
    }
    File[] dirContents = listFiles(f);
    if( dirContents == null )  {
      JOptionPane.showMessageDialog( FileBrowser.this, "The selected path: \""+ text +"\" is invalid!", "Invalid Path", JOptionPane.ERROR_MESSAGE ); 
      return;
    }        
    list.setListData(dirContents);
  }
 
  void updateListFromCurrentDir() {
    File lastInHistory = history.get( history.size()-1);
    File[] dirContents = listFiles(lastInHistory);
    list.setListData(dirContents);
  }
 
  class NextBtnListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      updateListFromText(text.getText());
    }
  }
 
  class BackBtnListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      if( history.size() < 2 )
        return;
      history.remove( history.size() -1 );
      File f = history.get( history.size() -1 );
      File[] dirContents = listFiles(f);
      text.setText(f.getAbsolutePath());
      list.setListData(dirContents);
    }
  }
 
  class UpBtnListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      File f = history.get(history.size()-1);
      File parent = f.getParentFile();
      if( parent==null || !parent.exists() )
        return;
      history.add(parent);
      text.setText( parent.getAbsolutePath() );
      File []dirContents = listFiles(parent);
      list.setListData(dirContents);
    }
  }
 
  class HomeBtnListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      String updatedText = System.getProperty("user.home");
      File[] updatedFiles = listFiles(updatedText);
 
      history.add( new File(updatedText) );
      text.setText(updatedText);
      list.setListData(updatedFiles);
    }
  }
 
  class ListMouseListener extends MouseAdapter {
    public void mouseClicked(MouseEvent e) {
      if( e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
        int index = list.locationToIndex(e.getPoint());
        File f = list.getModel().getElementAt(index);
        if( f.isDirectory() ) {
          File[] dirContents = listFiles(f);
          text.setText(f.getAbsolutePath());
          list.setListData(dirContents);
          history.add(f);
        }
        else {
          try {
            Desktop.getDesktop().open( f );
          }
          catch(IOException ex) {
            JOptionPane.showMessageDialog( FileBrowser.this, "Unable to open file: \""+ f.getName() +"\"!", "Error opening file", JOptionPane.ERROR_MESSAGE ); 
            return;
          }
        }
      }
    }
  }
 
  class MyCellRenderer implements ListCellRenderer<Object> {
     public MyCellRenderer() {
     }
 
     public Component getListCellRendererComponent(JList<?> list,
                                                   Object value,
                                                   int index,
                                                   boolean isSelected,
                                                   boolean cellHasFocus) {
       ImageIcon icon;
       File f = (File)value;
       if( f.isDirectory() ) {
         icon = new ImageIcon("images/dir.png");         
       }
       else {
         icon = new ImageIcon("images/file.png");
       }
       Image image = icon.getImage().getScaledInstance(25, 25, Image.SCALE_DEFAULT);
       icon = new ImageIcon(image);
       JLabel label = new JLabel(f.getName(), icon, JLabel.LEFT );
       label.setOpaque(true);
       return label;
     }
   }
 
  public static void main(String []args) {
    JFrame myFrame = new JFrame("CE325 File Browser");
    FileBrowser browser = new FileBrowser();
 
    myFrame.setJMenuBar( browser.createMenu() );
    myFrame.setContentPane(browser);
    myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
    myFrame.setVisible(true);
    myFrame.pack();
  }
}
swing/file_browser.txt · Last modified: 2016/06/02 12:01 (external edit)