[英]Image not displaying in JTable (Java Swing)
Hi I have created the following code.您好,我创建了以下代码。 The problem is the image is not displaying in the JTable column.问题是图像未显示在 JTable 列中。
I extend the DefaultTableModel and override the method getColumnClass.我扩展了 DefaultTableModel 并覆盖了方法 getColumnClass。 It was suggested this was one way to do it.有人建议这是一种方法。 Any clues?有什么线索吗? the code is below.代码如下。
//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
}
This is the correct way to do it, but your jpg isn't being found correctly.这是执行此操作的正确方法,但未正确找到您的 jpg。 Change your code to look it up as a resource URL and it should find it correctly.更改您的代码以将其查找为资源 URL,它应该可以正确找到它。 The following change worked perfectly on my machine:以下更改在我的机器上完美运行:
jTable1.setModel(new imageTableModel(
new Object [][] {
{new ImageIcon(getClass().getClassLoader().getResource("simply.jpg")), "pp"},
},
new String [] {
"image", "name"
}
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.