📄 e899. setting an accessory component in a jfilechooser dialog.txt
字号:
The accessory is an optional component that can be added to a file chooser dialog to show a preview image of the selected file. By default, a file chooser dialog does not have an accessory installed. This example demonstrates how to install an accessory component.
JFileChooser chooser = new JFileChooser();
// Create and set the accessory
chooser.setAccessory(new MyAccessory(chooser));
// Show the dialog; wait until dialog is closed
chooser.showOpenDialog(frame);
public class MyAccessory extends JComponent implements PropertyChangeListener {
public MyAccessory(JFileChooser chooser) {
// Listen for changes to the selected file
chooser.addPropertyChangeListener(this);
// Set a preferred size
setPreferredSize(new Dimension(50, 50));
}
// This listener listens for changes to the selected file
public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(
evt.getPropertyName())) {
JFileChooser chooser = (JFileChooser)evt.getSource();
// Get the new selected file
File newFile = (File)evt.getNewValue();
// Prepare the preview data based on the new selected file
// Repaint this component
repaint();
}
}
public void paint(Graphics g) {
// Paint a preview of the selected file
}
}
Related Examples
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -