キャストを修正して警告を削除する方法を教えてください
[unchecked] unchecked cast
required: T
found: java.lang.Object
SSCCEから
import java.awt.*;
import javax.swing.*;
public class JComboBoxWithWildCard {
private JDialog dlg = new JDialog();
private final Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
public JComboBoxWithWildCard() {
JComboBox comboWithCustomRenderer = new FlexiComboBox<String>(
"1 one", "2 two", "3 three", "4 four", "5 five", "6 six",
"7 seven", "8 eight", "9 nine", "10 ten", "11 eleven") {
private static final long serialVersionUID = 1L;
@Override
public String getCaption(String item) {
return item;
}
@Override
public Icon getItemIcon(String item) {
return errorIcon;
}
};
comboWithCustomRenderer.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXX");
comboWithCustomRenderer.setMaximumRowCount(6);
dlg.add(comboWithCustomRenderer);
dlg.pack();
dlg.setLocationRelativeTo(null);
dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dlg.setVisible(true);
}
public static void main(String[] a_args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JComboBoxWithWildCard pd = new JComboBoxWithWildCard();
}
});
}
}
abstract class FlexiComboBox<T> extends JComboBox {
private static final long serialVersionUID = 1L;
public FlexiComboBox(T... items) {
super(items);
}
@Override
public void updateUI() {
setRenderer(new DefaultListCellRenderer() {
private static final long serialVersionUID = 1L;
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
Component result = super.getListCellRendererComponent(list,
getCaption((T) value), index, isSelected, cellHasFocus);
Color color = getItemColor((T) value);
if (color != null) {
result.setBackground(color);
}
if (result instanceof JLabel) {
((JLabel) result).setIcon(getItemIcon((T) value));
}
return result;
}
});
super.updateUI();
}
public abstract String getCaption(T item);
public Color getItemColor(T item) {
return null;
}
public Icon getItemIcon(T item) {
return null;
}
}
編集:
警告はコード行から来ました
1.(コードライン 70.th)
Component result = super.getListCellRendererComponent(list,
getCaption((T) value), index, isSelected, cellHasFocus);
2.(コードライン71番目)
Color color = getItemColor((T) value);
3.(コードライン 76.th)
((JLabel) result).setIcon(getItemIcon((T) value));