在列表填充器中使用其它方法,列表填充器方法,public class
分享于 点击 48331 次 点评:284
在列表填充器中使用其它方法,列表填充器方法,public class
public class GenericListCellRenderer extends DefaultListCellRenderer { protected String method; public GenericListCellRenderer(String method) { super(); this.method = method; } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel label = (JLabel)super.getListCellRendererComponent( list,value,index, isSelected, cellHasFocus); try { Method meth = value.getClass().getMethod(method,null); if(meth != null) { Object retval = meth.invoke(value,null); label.setText(""+retval); } } catch (Exception ex) { System.out.println("got an execption: " + ex); ex.printStackTrace(); label.setText(""+value); } return label;} public static void main(String[] args) { String[] data = { "Proton", "Neutron", "Electron" }; JList list = new JList(data); //GenericListCellRenderer renderer=new GenericListCellRenderer("toString");GenericListCellRenderer renderer=new GenericListCellRenderer("hashCode"); list.setCellRenderer(renderer); JFrame frame = new JFrame("Cell Renderer Hack"); frame.getContentPane().add(list); frame.pack(); frame.setVisible(true); }}//该片段来自于http://byrx.net
用户点评