filebot/source/net/sourceforge/tuned/ui/SimpleLabelProvider.java
Reinhard Pointner 0c674849d8 * refactored and simplified transfer api
* use more GlazedLists stuff (EventList, AutoCompleteSupport) and remove obsolete classes (SimpleListModel, TextCompletion)
* don't use SearchResultCache in EpisodeListClient (was only done for better ui interactions)
* removed caching from ResourceManager
* some improvements based on FindBugs warnings
* use args4j for improved argument parsing
* updated ant build script
* more general MessageBus/Handler (use Object as message type instead of string)
* ChecksumComputationService is not a singleton anymore
* TemporaryFolder is always recreated if it is deleted by the user, or another instance shutting down
* Notifications flicker less when one window is removed and the others are layouted
* lots of other refactoring
2008-07-30 22:37:01 +00:00

91 lines
2.1 KiB
Java

package net.sourceforge.tuned.ui;
import java.lang.reflect.Method;
import java.util.Arrays;
import javax.swing.Icon;
import net.sourceforge.tuned.ExceptionUtil;
/**
* <code>LabelProvider</code> based on reflection.
*/
public class SimpleLabelProvider<T> implements LabelProvider<T> {
private final Method getIconMethod;
private final Method getTextMethod;
/**
* Factory method for {@link #SimpleLabelProvider(Class)}.
*
* @return new <code>LabelProvider</code>
*/
public static <T> SimpleLabelProvider<T> forClass(Class<T> type) {
return new SimpleLabelProvider<T>(type);
}
/**
* Create a new LabelProvider which will use the <code>getText</code>, <code>getName</code>
* or <code>toString</code> method for text and the <code>getIcon</code> method for the
* icon.
*
* @param type a class that has one of the text methods and the icon method
*/
public SimpleLabelProvider(Class<T> type) {
getTextMethod = findAnyMethod(type, "getText", "getName", "toString");
getIconMethod = findAnyMethod(type, "getIcon");
}
/**
* Create a new LabelProvider which will use a specified method of a given class
*
* @param type a class with the specified method
* @param getText a method name such as <code>getText</code>
* @param getIcon a method name such as <code>getIcon</code>
*/
public SimpleLabelProvider(Class<T> type, String getText, String getIcon) {
getTextMethod = findAnyMethod(type, getText);
getIconMethod = findAnyMethod(type, getIcon);
}
private Method findAnyMethod(Class<T> type, String... names) {
for (String name : names) {
try {
return type.getMethod(name);
} catch (NoSuchMethodException e) {
// try next method name
}
}
throw new IllegalArgumentException("Method not found: " + Arrays.toString(names));
}
@Override
public String getText(T value) {
try {
return (String) getTextMethod.invoke(value);
} catch (Exception e) {
throw ExceptionUtil.asRuntimeException(e);
}
}
@Override
public Icon getIcon(T value) {
try {
return (Icon) getIconMethod.invoke(value);
} catch (Exception e) {
throw ExceptionUtil.asRuntimeException(e);
}
}
}