1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileFilter;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
public class ExempleBrowseFile extends JPanel {
private JTextField textField;
private JButton button;
public ExempleBrowseFile(boolean fieldLocked) {
super(new GridBagLayout());
textField = new JTextField();
add(textField, new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.BASELINE_TRAILING, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
button = new JButton("Parcourir");
add(button, new GridBagConstraints(1, 0, 1, 1, 0, 0, GridBagConstraints.BASELINE_LEADING, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0));
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
browseFile();
}
});
if ( fieldLocked ) {
textField.setEditable(false);
}
}
private void browseFile() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Choisir le fichier...");
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setMultiSelectionEnabled(false);
if ( !textField.getText().isEmpty() ) {
fileChooser.setSelectedFile(new File(textField.getText()));
}
// il y a plein d'autres méthodes pour customiser le composant (filtre sur les fichiers par exemple) : voir doc.
if ( fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION ) {
textField.setText( fileChooser.getSelectedFile().getAbsolutePath().toString() );
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Démo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add( new ExempleBrowseFile(false) );
frame.setSize(400,100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
} |
Partager