quinta-feira, 18 de dezembro de 2008

Abrir diretório do Sistema Operacional com Swing

//Este exemplo mostra como selecionar diretório usando
//JFileChooser a partir de uma JFrame

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class ExemploJFileChooser extends JFrame {
public ExemploJFileChooser() {
super("Escolher um diretório usando JFileChooser");

Container c = getContentPane();
FlowLayout layout = new FlowLayout(FlowLayout.CENTER);
c.setLayout(layout);

JButton btn = new JButton("Escolher Arquivo");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();

// restringe a amostra a diretorios apenas
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

int res = fc.showOpenDialog(null);

if (res == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
JOptionPane.showMessageDialog(null,
"Voce escolheu o arquivo: " + file.getName());
} else
JOptionPane.showMessageDialog(null,
"Voce nao selecionou nenhum arquivo.");
}
});

c.add(btn);

setSize(400, 200);
setVisible(true);
}

public static void main(String[] args) {
ExemploJFileChooser app = new ExemploJFileChooser();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Nenhum comentário:

Postar um comentário