I want to override toString() method for a FileFilter object. I have this piece of code
JFileChooser saveFile = new JFileChooser();
saveFile.setAcceptAllFileFilterUsed(false);
saveFile.setMultiSelectionEnabled(false);
saveFile.setFileFilter(new FileNameExtensionFilter("PNG", ".png"));
String type = saveFile.getFileFilter().toString();
System.out.println(type);
Which prints out something along the lines of javax.swing.filechooser.FileNameExtensionFilter@39cc65b1[description=PNG extensions=[.png]]
. My goal is to create an overridden toString method, so I would get only the .png
part.
I KNOW that there are more efficient ways to do this exact task, and I know the basic string functions to get the part I need, but my goal is to do it with an overridden method.
my goal is to do it with an overridden method.
This is not possible, for a number of reasons described below. The only way to do it is through composition, not through inheritance.
You can override a method only in classes that you own. Since you do not own the FileNameExtensionFilter
, an implementation of FileFilter
returned by JFileChooser
, there is no way for you to override its toString
method.
Moreover, FileNameExtensionFilter
is a final
class , so you cannot override any of its methods.
The only approach available in this situation is to create your own FileFilter
wrapping FileNameExtensionFilter
, and pass it the filter that you get from JFileChooser
. You would own this class, so you could override its toString
as needed:
class FileFilterWrapper {
private final FileFilter innerFilter;
public FileFilterWrapper(FileFilter innerFilter) {
this.innerFilter = innerFilter;
}
@Override
public String toString(){
// Use innerFilter properties to produce the desired String
return ...
}
}
If you literally just want to do it right here you could do an anonymous inner class for it:
JFileChooser saveFile = new JFileChooser() {
@Override
public String toString() {
return ".png";
}
}
I can't recommend that approach though, it would be better to implement your own subclass of JFileChooser
and define a new String getFileExtension()
method inside that.
To do that, you need to use a subclass of JFileChooser. If that's the only method you want to override, its quite simple.
public class MyFileChooser extends JFileChooser{
public MyFileChooser(){
super();
}
@Override
public String toString(){
//your string conversion code here
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.