Pregunta

I'm writing a "simple" Java program that lets the user change desktop wallpaper. It basically fills a JList with Files from a directory of the users choise and the user double-clicks to set one of the files as the wallpaper. Simple!

I'd like some more attributes though (boolean isFavorite, for example) to give the program more functionality, but I'm not sure how to do this...

I tried making my own class Wallpaper which extended File, but when trying to fill my JList with Wallpapers instead I got all sorts of class casting errors when switching between Files and Wallpapers. So I ended up overriding more and more of the File methods until I got into such a deep web of mysterious errors that I didn't know how to get out of.

I got the idea of filling my JList with files from Andrew who does so in his answer here: JList that contains the list of Files in a directory

Mine looks like this,

File wallFile = new File(System.getProperty("user.home"));

//Create the file array
File[] fileArray =  wallFile.listFiles(new TextFileFilter());

//Put File objects in the list
JList<File> fileList = new JList<File>(fileArray);

Since I know I'm not making anything unique here I know there should be "approved of" ways to do this, so would anyone please enlighten me about the best way of changing from the built-in File to a custom Wallpaper?

¿Fue útil?

Solución

The listFiles() method will use the default File class, not your extended WallPaper class. Therefore you will get an error if you try to cast one of those objects to a WallPaper. Instead, do this:

String [] nameArray = wallFile.list(new TextFileFilter());
File [] fileArray = new File [nameArray.length];
for (int i=0;i<nameArray.length;i++)
   fileArray[i] = new WallPaper(new File(wallFile, nameArray[i]).getAbsolutePath());//provided you have a WallPaper constructor that accepts an absolute path
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top