嗨,我创建了以下代码。问题是图像未显示在JTable列中。
我扩展DefaultTableModel并重写方法getColumnClass。有人建议这是做到这一点的一种方法。有什么线索吗?代码如下。
//package javaapplication12;
import javax.swing.*;
public class NewJFrame2 extends javax.swing.JFrame {
/** Creates new form NewJFrame */
public NewJFrame2() {
initComponents();
}
public class imageTableModel extends javax.swing.table.DefaultTableModel
{
imageTableModel(Object[][] data, Object[] columnNames)
{
super(data,columnNames);
}
@Override
public Class getColumnClass(int column)
{
if (column == 0)
{
return ImageIcon.class;
}
return Object.class;
// other code; default to Object.class
}
}
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new imageTableModel(
new Object [][] {
{new ImageIcon("simply.jpg"), "pp"},
},
new String [] {
"image", "name"
}
));
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(19, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(19, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame2().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
最佳答案
这是正确的方法,但是找不到jpg。更改您的代码以将其查找为资源URL,它应该可以正确找到它。以下更改在我的计算机上运行完美:
jTable1.setModel(new imageTableModel(
new Object [][] {
{new ImageIcon(getClass().getClassLoader().getResource("simply.jpg")), "pp"},
},
new String [] {
"image", "name"
}
));