Different imageIcon in different cells in JTable

大城市里の小女人 提交于 2019-12-20 04:29:04

问题


I think I got the imageIcon to show up differently in each cell but for some reason when I compile it, the images don't show up. It displays the name of the image but the image itself doesn't show up. Here is an image. http://i49.tinypic.com/r9ibrn.jpg

public class movies extends JFrame {

    public movies() {
    initComponents();

 }      

private void initComponents() {

    panel = new JPanel();
    logo = new JLabel();
    pane = new JScrollPane();


    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setBackground(new Color(255, 255, 204));
    setResizable(false);

    panel.setBackground(new Color(51, 51, 51));
    panel.setPreferredSize(new Dimension(290, 75));

    logo.setIcon(new ImageIcon(getClass().getResource("logo.png"))); 
    logo.setName("logo");
    logo.setRequestFocusEnabled(false);
    logo.setVerifyInputWhenFocusTarget(false);
    logo.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));


    ImageIcon icon1 = new ImageIcon("1.jpg");
    ImageIcon icon2 = new ImageIcon("2.jpg");
    ImageIcon icon3 = new ImageIcon("3.jpg");

    String[] columnNames = {"Section 1", "Section 2"};
    Object[][] data =
    {
        {icon1 + " Music", icon2 + " News"},
        {icon2 + " Movies"},
        {icon3 + " Games"},
    };

    DefaultTableModel model = new DefaultTableModel(data, columnNames);
    JTable table = new JTable( model )

    {
            public Class getColumnClass(int column)
        {
            return getValueAt(0, column).getClass();
        }
    };


    table.setPreferredScrollableViewportSize(table.getPreferredSize());

    table.setBackground(new Color(255, 255, 204));
    JScrollPane scrollPane = new JScrollPane( table );
    getContentPane().add( scrollPane );

    table.setRowHeight(50);
    pane.setViewportView(table);
    table.getColumnModel().getColumn(0).setResizable(false);
    table.getColumnModel().getColumn(1).setResizable(false);
}


public static void main(String args[]) {


        public void run() {
            new movies().setVisible(true);

        }
    });
}

private JLabel logo;
private JScrollPane pane;
private JPanel panel;

}


回答1:


You can pass in the name of the image when you call the new ImageRenderer constructor (read this).

public class Movies extends javax.swing.JFrame {
    public Movies() {
        initComponents();
        table.getColumnModel().getColumn(1).setCellRenderer(new ImageRenderer("1.jpg"));
        table.getColumnModel().getColumn(0).setCellRenderer(new ImageRenderer("2.jpg"));
    }
}

class ImageRenderer extends DefaultTableCellRenderer {
    ImageIcon icon = null;    

    ImageRenderer(String iconName) {
        icon = new ImageIcon(getClass().getResource(iconName));
    }
}


来源:https://stackoverflow.com/questions/11527477/different-imageicon-in-different-cells-in-jtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!