package net.sourceforge.tuned.ui;
import java.lang.reflect.Method;
import javax.swing.Icon;
import net.sourceforge.tuned.ExceptionUtil;
/**
* LabelProvider
based on reflection.
*/
public class SimpleLabelProvider implements LabelProvider {
private final Method getIconMethod;
private final Method getNameMethod;
/**
* Same as new SimpleLabelProvider<T>(T.class)
.
*
* @return new LabelProvider
*/
public static SimpleLabelProvider forClass(Class type) {
return new SimpleLabelProvider(type);
}
/**
* Create a new LabelProvider which will use the getName
and
* getIcon
method of the given class.
*
* @param type a class that has a getName
and a getIcon
method
*/
public SimpleLabelProvider(Class type) {
this(type, "getName", "getIcon");
}
/**
* Create a new LabelProvider which will use a specified method of a given class
*
* @param type a class with the specified method
* @param getName a method name such as getName
* @param getIcon a method name such as getIcon
*/
public SimpleLabelProvider(Class type, String getName, String getIcon) {
try {
getNameMethod = type.getMethod(getName);
getIconMethod = type.getMethod(getIcon);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public String getText(T value) {
try {
return (String) getNameMethod.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);
}
}
}