-
Notifications
You must be signed in to change notification settings - Fork 1
/
JFilePicker.java
80 lines (62 loc) · 2.01 KB
/
JFilePicker.java
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
77
78
79
80
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class JFilePicker extends JPanel {
private String textFieldLabel;
private String buttonLabel;
private JLabel label;
private JTextField textField;
private JButton button;
private JFileChooser fileChooser;
private int mode;
public static final int MODE_OPEN = 1;
public static final int MODE_SAVE = 2;
public JFilePicker(String textFieldLabel, String buttonLabel) {
this.textFieldLabel = textFieldLabel;
this.buttonLabel = buttonLabel;
fileChooser = new JFileChooser();
setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
// creates the GUI
label = new JLabel(textFieldLabel);
textField = new JTextField(30);
button = new JButton(buttonLabel);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
buttonActionPerformed(evt);
}
});
add(label);
add(textField);
add(button);
}
private void buttonActionPerformed(ActionEvent evt) {
if (mode == MODE_OPEN) {
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
} else if (mode == MODE_SAVE) {
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
}
}
public void addFileTypeFilter(String extension, String description) {
FileTypeFilter filter = new FileTypeFilter(extension, description);
fileChooser.addChoosableFileFilter(filter);
}
public void setMode(int mode) {
this.mode = mode;
}
public String getSelectedFilePath() {
return textField.getText();
}
public JFileChooser getFileChooser() {
return this.fileChooser;
}
}