1

我想我让 imageIcon 在每个单元格中以不同的方式显示,但是由于某种原因,当我编译它时,图像没有显示出来。它显示图像的名称,但图像本身不显示。这是一张图片。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;

}

4

1 回答 1

1

您可以在调用new ImageRenderer构造函数时传入图像的名称(阅读此内容)。

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));
    }
}
于 2012-07-18T17:26:13.873 回答