JTable cell add Image
hi,
pls let me know how to add image in JTable particular cell. I am trying to add image in a particular column each row at runtime ( developing database application), those images are in remote location and also directory files. I am trying to use below code. but it is now showing image instead it is giving message like "sun.awt.image.ToolkitImage@1b1aa65"
============my code is ===========
Image image = java.awt.Toolkit.getDefaultToolki().getDefaultToolkit().getImage(file);
dataValues[rowNum][6] =image;
================================
awaiting solution.
I am trying to add image in a particular column each row Override the getColumnClass() method of the JTable to return the class of data in each column and it will choose the appropiate renderer. I've posted examples. I think I called the class "Table Icon" (one word). Search the forum and you should find it.
Similar Messages
-
How to display images in a Jtable cell-Urgent
Hay all,
Can anybody tell me that can we display images to JTable' cell,If yes the how do we do that(with some code snippet)? Its very urgent .Plz reply as soon as possible.Here is an example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
class SimpleTableExample extends JFrame
private JPanel topPanel;
private JTable table;
private JScrollPane scrollPane;
public SimpleTableExample()
setTitle( "Table With Image" );
setSize( 300, 200 );
setBackground( Color.gray );
topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
// Create columns names
String columnNames[] = { "Col1", "Col2", "Col3" };
// Create some data
Object data[][] =
{ (ImageIcon) new ImageIcon("User.Gif"), (String) "100", (String)"101" },
{ (String)"102", (String)"103", (String)"104" },
{ (String)"105", (String)"106", (String)"107" },
{ (String)"108", (String)"109", (String)"110" },
// Create a new table instance
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable( model )
public Class getColumnClass(int column)
return getValueAt(0, column).getClass();
}; // Add the table to a scrolling pane
scrollPane = new JScrollPane( table );
topPanel.add( scrollPane, BorderLayout.CENTER );
public static void main( String args[] )
SimpleTableExample mainFrame = new SimpleTableExample();
mainFrame.setVisible( true );
} -
How to add image in jtable header using 'Default table model'
Hi,
I created a table using "DefaultTableModel".
im able to add images in table cells but not in 'table header'.
i added inages in table by overriding "getColumnClass" of the DefaultTableModel.
But what to do for headers?
please help.
Thanks in advance.The 'Java 5 tutorial' is really an outstanding oneI should note the the current tutorial on the Sun website has bee updated for Java 6. It contains updates to reflect the changes made in JDK6. Once of the changes is that sorting of tables is now supported directly which is why I needed to give you the link to the old tutorial.
http://java.sun.com/docs/books/tutorial/uiswing/TOC.html -
Hi All,
Based on condition how can i add image to Table cell.Hi,
Its very simple and straightforward.
All you need to do is:
1...Create a context(value attribute) of type string.
2...I am assuming that you have created a table, and mapped its columns with a node.
3...In the <i>TableCellEditor</i> of your desired column, map the above context with the <i>imagesource</i> property.
4...In the code, set the value of this context to the image name(eg: abc.gif), on satisfying of a condition.
5...However, keep in mind to set the context value to some default blank image in the doinit() of the view, else, you will get a null pointer exception.
I hope this solves your problem.
Keep posting if you have any further queries.
Regards,
Hanoz -
How to add JTable's backgroung image
Hi all
I want to add image toJTable's background
I am having no idea how to do it
Please tell me easiest way of doing thatI have no idea whether this will work with a JTable, but you could put your JTable (and other components sharing the top-level container) on the "glass" layer, and make it transparent (and the glass pane visible), and put your background image behind it. It seems to work with other types of JComponents.
-
How can I put ImageIcon object in a JTable cell?
yes, I'mm trying :
ImageIcon icon = new ImageIcon("something.gif")
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
Object[] newRow = new Object[5];
newRow[1] = "I don't";
newRow[2] = "know, what";
newRow[3] = "I am doing"
newRow[4] = "wrong"
newRow[0] = icon;
model.addRow(newRow);
but icon doesn't show -
Hi
I am facing one problem. there is some data should be displayed in Jtable cell.
The thing is that the whole data shall be visible in the cell.. for this I am writing one renderer.. but I could not find the desire solution.. please check it out
class Item_Details extends JFrame {
ApsJTable itemTable = null;
ApsJTable imageTable = null;
ArrayList data = new ArrayList();
String[] columns = new String[2];
ArrayList data1 = new ArrayList();
String[] columns1 = new String[2];
ItemTableModel itemTableModel = null;
ItemTableModel itemTableModel1 = null;
public Item_Details()
super("Item Details");
this.setSize(600,100);
this.setVisible(true);
init();
private void init(){
////////////// Get data for first Table Model ////////////////////////////
data = getRowData();
columns = getColData();
System.out.println(columns[0]);
itemTableModel = new ItemTableModel(data,columns);
/////////////Get Data for Second Table Model //////////////////////////////
try{
data1 = getRowData1();
}catch(Exception e){}
columns1 = getColumns1();
itemTableModel1 = new ItemTableModel(data1,columns1);
///////////// Set Data In Both Table Model //////////////////////////////////
itemTable = new ApsJTable(itemTableModel);
imageTable = new ApsJTable(itemTableModel1);
this.itemTable.setShowGrid(false);
this.imageTable.setShowGrid(false);
this.itemTable.setColumnSelectionAllowed(false);
this.imageTable.setColumnSelectionAllowed(false);
System.out.println(itemTable.getColumnCount());
this.imageTable.setRowHeight(getImageHeight()+3);
JScrollPane tableScrollPane = new JScrollPane(this.imageTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tableScrollPane.setRowHeaderView(this.itemTable);
tableScrollPane.getRowHeader().setPreferredSize(new Dimension(800, 0));
itemTable.getTableHeader().setReorderingAllowed(false);
itemTable.setColumnSelectionAllowed(false);
//itemTable.setRowHeight(25);
itemTable.setCellSelectionEnabled(false);
itemTable.setFocusable(false);
imageTable.getTableHeader().setReorderingAllowed(false);
imageTable.setFocusable(false);
imageTable.setCellSelectionEnabled(false);
//tableScrollPane.setOpaque(false);
itemTable.setAutoCreateColumnsFromModel(false);
int columnCount = itemTable.getColumnCount();
for(int k=0;k<columnCount;k++)
/* TableCellRenderer renderer = null;
TableCellEditor editor = null;
renderer = new TextAreaCellRenderer(); // NEW
editor = new TextAreaCellEditor();
TableColumn column = new TableColumn(k,itemTable.getColumnModel().getColumn(k).getWidth(),renderer, editor);
itemTable.addColumn(column);*/
itemTable.getColumnModel().getColumn(k).setCellRenderer(new MultiLineCellRenderer());
//itemTable.getColumnModel().getColumn(k).setCellEditor(new TextAreaCellEditor());
////////////---------------------- Here background color is being set--------------//////////////////
this.imageTable.getParent().setBackground(Color.WHITE);
this.itemTable.getParent().setBackground(Color.WHITE);
tableScrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER,this.itemTable.getTableHeader());
getContentPane().add(tableScrollPane,BorderLayout.CENTER);
getContentPane().setVisible(true);
public static void main(String[] str){
com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode", "2005/05/28#[email protected]#1v2pej6#1986ew");
try {
javax.swing.LookAndFeel alloyLnF = new com.incors.plaf.alloy.AlloyLookAndFeel();
javax.swing.UIManager.setLookAndFeel(alloyLnF);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Item_Details ID = new Item_Details();
ID.setVisible(true);
public ArrayList getRowData()
ArrayList rowData=new ArrayList();
Hashtable item = new Hashtable();
item.put(new Long(0),new String("Item No:"));
item.put(new Long(1),new String("RED-1050"));
rowData.add(0,item);
item = new Hashtable();
item.put(new Long(0),new String("Description:"));
item.put(new Long(1),new String("SYSTEM 18 mbh COOLING 13 mbh HEATING 230/208 v POWER AIRE "));
rowData.add(1,item);
item = new Hashtable();
item.put(new Long(0),new String("Stage:"));
item.put(new Long(1),new String("Draft"));
rowData.add(2,item);
item = new Hashtable();
item.put(new Long(0),new String("Price: "));
item.put(new Long(1),new String(" 999.00"));
rowData.add(3,item);
item = new Hashtable();
item.put(new Long(0),new String("Features:"));
item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
rowData.add(4,item);
/*item.put(new Long(0),new String("Family Sequence"));
item.put(new Long(1),new String("8.00"));
rowData.add(5,item);
item.put(new Long(0),new String("Family Sequence"));
item.put(new Long(1),new String("8.00"));
rowData.add(6,item);
item.put(new Long(0),new String("Family Sequence"));
item.put(new Long(1),new String("8.00"));
rowData.add(7,item);
return rowData;
public String[] getColData()
String[] colData = new String[]{"Attribute","Value"};
return colData;
public ArrayList getRowData1()throws MalformedURLException{
ArrayList rowData = new ArrayList();
Hashtable item = new Hashtable();
String str = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
URL url = new URL(str);
ImageIcon ic = new ImageIcon(url);
ImageIcon scaledImage = new ImageIcon(ic.getImage().getScaledInstance(getImageHeight(), -1,Image.SCALE_SMOOTH));
item.put(new Long(0), scaledImage);
rowData.add(0,item);
String str1 = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
URL url1 = new URL(str1);
ImageIcon ic1 = new ImageIcon(url1);
ImageIcon scaledImage1 = new ImageIcon(ic1.getImage().getScaledInstance(120, -1,Image.SCALE_DEFAULT));
item.put(new Long(0),scaledImage1);
rowData.add(1,item);
return rowData;
public String[] getColumns1(){
String[] colData = new String[]{"Image"};
return colData;
public int getImageHeight(){
ImageIcon ic = new ImageIcon("c:\\image\\ImageNotFound.gif");
return ic.getIconHeight();
class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
public MultiLineCellRenderer() {
setLineWrap(true);
setWrapStyleWord(true);
JScrollPane m_scroll = new JScrollPane(this,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
setOpaque(true);
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
/*if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
// setFont(table.getFont());
/* if (hasFocus) {
setBorder( UIManager.getBorder("Table.focusCellHighlightBorder") );
if (table.isCellEditable(row, column)) {
setForeground( UIManager.getColor("Table.focusCellForeground") );
setBackground( UIManager.getColor("Table.focusCellBackground") );
} else {
setBorder(new EmptyBorder(1, 2, 1, 2));
int width = table.getColumnModel().getColumn(column).getWidth();
//setSize(width, 1000);
int rowHeight = getPreferredSize().height;
if (table.getRowHeight(row) != rowHeight)
table.setRowHeight(row, rowHeight);
setText((value == null) ? "" : value.toString());
return this;
}what wrong with this code..
ThanksIn summary, you have one or more columns for which the data must be wholly visible - correct? If you need all the columns to show the whole of their data, you are goinf to have to expand the table, otherwise you can expand a column with something like
myTable.getColumnModel().getColumn(whichever).setPreferredWidth(whatever); -
Problem in JTable cell renderer
Hi
One problem in JTable cell. Actually I am using two tables while I am writing renderer for word raping in first table .. but it is affected in last column only remain is not being effected�. Please chaek it out what is exact I am missing�
Thanks
package com.apsiva.tryrowmerge;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.Hashtable;
import java.net.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
class Item_Details extends JFrame {
ApsJTable itemTable = null;
ApsJTable imageTable = null;
ArrayList data = new ArrayList();
String[] columns = new String[2];
ArrayList data1 = new ArrayList();
String[] columns1 = new String[2];
ItemTableModel itemTableModel = null;
ItemTableModel itemTableModel1 = null;
public Item_Details()
super("Item Details");
this.setSize(600,100);
this.setBackground(Color.WHITE);
this.setVisible(true);
init();
private void init(){
////////////// Get data for first Table Model ////////////////////////////
data = getRowData();
columns = getColData();
System.out.println(columns[0]);
itemTableModel = new ItemTableModel(data,columns);
/////////////Get Data for Second Table Model //////////////////////////////
try{
data1 = getRowData1();
}catch(Exception e){}
columns1 = getColumns1();
itemTableModel1 = new ItemTableModel(data1,columns1);
///////////// Set Data In Both Table Model //////////////////////////////////
itemTable = new ApsJTable(itemTableModel);
imageTable = new ApsJTable(itemTableModel1);
this.itemTable.setShowGrid(false);
this.imageTable.setShowGrid(false);
this.itemTable.setColumnSelectionAllowed(false);
this.imageTable.setColumnSelectionAllowed(false);
System.out.println(itemTable.getColumnCount());
this.imageTable.setRowHeight(getImageHeight()+3);
JScrollPane tableScrollPane = new JScrollPane(this.imageTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tableScrollPane.setRowHeaderView(this.itemTable);
//itemTable.getColumnModel().getColumn(0).setMaxWidth(200);
itemTable.getColumnModel().getColumn(0).setPreferredWidth(200);
itemTable.getColumnModel().getColumn(1).setPreferredWidth(600);
tableScrollPane.getRowHeader().setPreferredSize(new Dimension(800, 0));
itemTable.getTableHeader().setResizingAllowed(false);
itemTable.getTableHeader().setReorderingAllowed(false);
itemTable.setColumnSelectionAllowed(false);
//itemTable.setRowHeight(25);
itemTable.setCellSelectionEnabled(false);
itemTable.setFocusable(false);
imageTable.getTableHeader().setReorderingAllowed(false);
imageTable.setFocusable(false);
imageTable.setCellSelectionEnabled(false);
//tableScrollPane.setOpaque(false);
itemTable.setAutoCreateColumnsFromModel(false);
int columnCount = itemTable.getColumnCount();
for(int k=0;k<columnCount;k++)
TableCellRenderer renderer = null;
TableCellEditor editor = null;
renderer = new TextAreaCellRenderer(); // NEW
// editor = new TextAreaCellEditor();
// TableColumn column = new TableColumn(k,itemTable.getColumnModel().getColumn(k).getWidth(),renderer, editor);
System.out.println(k);
itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);
//itemTable.getColumnModel().getColumn(k).setCellEditor(editor);
/*itemTable.getColumnModel().getColumn(1).setCellRenderer(new TextAreaCellRenderer());
itemTable.getColumnModel().getColumn(1).setCellEditor(new TextAreaCellEditor());*/
// itemTable.setShowGrid(false);
//itemTable.addColumn(column);
//itemTable.getColumnModel().getColumn(k).setCellRenderer(new MultiLineCellRenderer());
//itemTable.getColumnModel().getColumn(k).setCellEditor(new TextAreaCellEditor());
////////////---------------------- Here background color is being set--------------//////////////////
this.imageTable.getParent().setBackground(Color.WHITE);
this.itemTable.getParent().setBackground(Color.WHITE);
tableScrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER,this.itemTable.getTableHeader());
getContentPane().add(tableScrollPane,BorderLayout.CENTER);
getContentPane().setVisible(true);
public static void main(String[] str){
com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode", "2005/05/28#[email protected]#1v2pej6#1986ew");
try {
javax.swing.LookAndFeel alloyLnF = new com.incors.plaf.alloy.AlloyLookAndFeel();
javax.swing.UIManager.setLookAndFeel(alloyLnF);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Item_Details ID = new Item_Details();
ID.setVisible(true);
public ArrayList getRowData()
ArrayList rowData=new ArrayList();
Hashtable item = new Hashtable();
item.put(new Long(0),new String("Item No:aaaaaaa aaaaaaaa aaaaaaaaa aaaaaa"));
item.put(new Long(1),new String("RED-1050"));
rowData.add(0,item);
item = new Hashtable();
item.put(new Long(0),new String("Description:rt r trtrt rttrytrr tytry trytry tr tr rty thyjyhjhnhnhgg hhjhgjh"));
item.put(new Long(1),new String("SYSTEM 18 mbh COOLING 13 mbh HEATING 230/208 v POWER AIRE "));
rowData.add(1,item);
item = new Hashtable();
item.put(new Long(0),new String("Stage:"));
item.put(new Long(1),new String("Draft"));
rowData.add(2,item);
item = new Hashtable();
item.put(new Long(0),new String("Price: "));
item.put(new Long(1),new String("999.00"));
rowData.add(3,item);
item = new Hashtable();
item.put(new Long(0),new String("Features:"));
item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
rowData.add(4,item);
item = new Hashtable();
item.put(new Long(0),new String("Features:"));
item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
rowData.add(5,item);
item = new Hashtable();
item.put(new Long(0),new String("Features:"));
item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
rowData.add(6,item);
/*item.put(new Long(0),new String("Family Sequence"));
item.put(new Long(1),new String("8.00"));
rowData.add(5,item);
item.put(new Long(0),new String("Family Sequence"));
item.put(new Long(1),new String("8.00"));
rowData.add(6,item);
item.put(new Long(0),new String("Family Sequence"));
item.put(new Long(1),new String("8.00"));
rowData.add(7,item);
return rowData;
public String[] getColData()
String[] colData = new String[]{"Attribute","Value"};
return colData;
public ArrayList getRowData1()throws MalformedURLException{
ArrayList rowData = new ArrayList();
Hashtable item = new Hashtable();
String str = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
URL url = new URL(str);
ImageIcon ic = new ImageIcon(url);
ImageIcon scaledImage = new ImageIcon(ic.getImage().getScaledInstance(getImageHeight(), -1,Image.SCALE_SMOOTH));
item.put(new Long(0), scaledImage);
rowData.add(0,item);
String str1 = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
URL url1 = new URL(str1);
ImageIcon ic1 = new ImageIcon(url1);
ImageIcon scaledImage1 = new ImageIcon(ic1.getImage().getScaledInstance(120, -1,Image.SCALE_DEFAULT));
item.put(new Long(0),scaledImage1);
rowData.add(1,item);
return rowData;
public String[] getColumns1(){
String[] colData = new String[]{"Image"};
return colData;
public int getImageHeight(){
ImageIcon ic = new ImageIcon("c:\\image\\ImageNotFound.gif");
return ic.getIconHeight();
class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
public TextAreaCellRenderer() {
setEditable(false);
setLineWrap(true);
setWrapStyleWord(true);
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int nRow, int nCol)
if (value instanceof String)
setText((String)value);
// Adjust row's height
int width = table.getColumnModel().getColumn(nCol).getWidth();
setSize(width, 1000);
int rowHeight = getPreferredSize().height;
if (table.getRowHeight(nRow) != rowHeight)
table.setRowHeight(nRow, rowHeight);
this.setBackground(Color.WHITE);
return this;I think Problem is between these code only
for(int k=0;k<columnCount;k++)
TableCellRenderer renderer = null;
TableCellEditor editor = null;
renderer = new TextAreaCellRenderer();
itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);or in this renderer
class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
public TextAreaCellRenderer() {
setEditable(false);
setLineWrap(true);
setWrapStyleWord(true);
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int nRow, int nCol)
if (value instanceof String)
setText((String)value);
// Adjust row's height
int width = table.getColumnModel().getColumn(nCol).getWidth();
setSize(width, 1000);
int rowHeight = getPreferredSize().height;
if (table.getRowHeight(nRow) != rowHeight)
table.setRowHeight(nRow, rowHeight);
this.setBackground(Color.WHITE);
return this;
} -
JTextField/JTable-cell Button
Is there any known efficient methods of creating the JTextField or JTable-cell Button as like in Forte's Component Inspector window where you click on the property value field and the value is displayed just left of a small button labelled "..." ie: [some text field with value][...] also referred to as the "ellipsis" buttons, or will most answers to this question simply describe the layout of a JField-JButton combination? The action from clicking on the [...] button aligned right of the JTextField simply invokes or displays a larger input interface in which upon completion of the entered data, returns the input to the related JTextField.
Thanks to anybody for any help with this, and perhaps in return, I may be able to answer any non-gui java questions, or some not so unfamilliar GUI questions.Hello StanislavL and Lutianxiong,
I remember asking this question some time ago, and the time has come again for me to seek this functionality. I have finally achieved the functionality and thought I would post the answer for anybody else. I had not realized that I had recieved a solution/reply to my original question as I come here to post the answer, and in fact, my solution does appear to be very similiar to your reply, StanislavL. As for you, Lutianxiong and other seekers of this info, here is my solution with a JFileChooser style input for the 3rd column which only shows gif,jpg and png files:
<code>
------------- TableCellFileInput.java -------------------
public class TableCellFileInput extends javax.swing.JPanel {
private String extensions[];
public TableCellFileInput(String fileExtensions[]) {
extensions = fileExtensions;
self = this;
initComponents();
private void initComponents() {
valueField = new javax.swing.JTextField();
fileButton = new javax.swing.JButton();
setLayout(new java.awt.BorderLayout());
valueField.setText("jTextField1");
add(valueField, java.awt.BorderLayout.CENTER);
fileButton.setText("...");
fileButton.setMargin(new java.awt.Insets(0, 2, 0, 2));
fileButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fileButtonActionPerformed(evt);
add(fileButton, java.awt.BorderLayout.EAST);
private void fileButtonActionPerformed(java.awt.event.ActionEvent evt) {
String filePath = valueField.getText();
if(filePath != null && filePath.length() > 0) {
filePath = new java.io.File(filePath).getParent();
javax.swing.JFileChooser chooser
= new javax.swing.JFileChooser(filePath);
chooser.setFileFilter(new ImageFilter());
int returnVal = chooser.showOpenDialog(this);
if(returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
valueField.setText(chooser.getSelectedFile().getAbsolutePath());
class ImageFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(java.io.File f) {
if(f.isDirectory()) return true;
String fName = f.getName();
if(extensions != null) {
for(int i=0;i<extensions.length;i++) {
if(fName.endsWith(extensions[ i ])) return true;
return false;
public String getDescription() {
return DESCRIPTION;
class CustomCellEditor extends javax.swing.AbstractCellEditor
implements javax.swing.table.TableCellEditor {
public Object getCellEditorValue() {
return valueField.getText();
public java.awt.Component getTableCellEditorComponent(javax.swing.JTable table, Object value, boolean isSelected, int row, int column) {
System.out.println("fileEditor");
if(value == null) valueField.setText("");
else valueField.setText(value.toString());
return self;
public void setColumn(javax.swing.table.TableColumn column) {
column.setCellEditor(new CustomCellEditor());
private javax.swing.JButton fileButton;
private javax.swing.JTextField valueField;
private static final String DESCRIPTION = "Image File Filter";
private java.awt.Component self;
------------- TestTable .java -------------------
public class TestTable extends javax.swing.JFrame {
public TestTable() {
editorField = new javax.swing.JTextField();
String fileExts[] = {"gif","jpg","png"};
fileEditorField = new TableCellFileInput(fileExts);
initComponents();
javax.swing.table.TableColumn column
= jTable1.getColumn("Title 3");
fileEditorField.setColumn(column);
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, "cats"},
{null, null, null, "dogs"},
{null, null, null, "mice"},
{null, null, null, "birds"}
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
Class[] types = new Class [] {
java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.String.class
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
jScrollPane1.setViewportView(jTable1);
getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-400)/2, (screenSize.height-300)/2, 400, 300);
private void exitForm(java.awt.event.WindowEvent evt) {
System.exit(0);
public static void main(String args[]) {
new TestTable().show();
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField editorField;
private TableCellFileInput fileEditorField;
</code> -
Hello -
I'm rather new to Java, so please excuse me if this is a simple question. For a project I am working on, I am attempting to deal with placing two icons in a single JTable cell. For the life of me I have no idea if this is even feasible, let alone how I would implement it. Originally I thought about attempting to overload the JLabel class (as this is what the JTable cell is based upon, if I'm not mistaken?) and allowing two icons to be placed per label.
Am I on the right track? Is this even possible? Any suggestions?
Thanks much.Please read the forum for JTable.
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
You will know that you canuse any component as CellRenderer, this component can have whatever you want (say 2 icons and 5 comboboxes)
here is short example that shows 2 icons in JTable
import java.awt.*;
import java.awt.image.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TwoIcons extends JFrame {
public static void main(String[] args){
createIcons();
SwingUtilities.invokeLater
new Runnable()
public void run() {
new TwoIcons();
public TwoIcons(){
super("Test");
DefaultTableModel tm = new DefaultTableModel(
new Object[][]{
{new IconPair("cross", "cross"), "just a string"},
{new IconPair("circle", "cross"),"just another string"},
{new IconPair("String", "circle"),"yet another string"}
}, new String[]{"Two Icons","String"}){
public Class getColumnClass(int columnIndex){
if(columnIndex==0){
return IconPair.class;
else
return super.getColumnClass(columnIndex);
JTable table = new JTable(tm);
final Color bg = table.getBackground();
table.setDefaultRenderer(IconPair.class, new TableCellRenderer(){
RendererPanel renderer = new RendererPanel(bg);
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
renderer.setIcons((IconPair)value);
return renderer;
JScrollPane scp = new JScrollPane(table);
add(scp);
setSize(400,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
class RendererPanel extends JPanel{
JLabel tf1,tf2;
RendererPanel(Color bg){
setLayout(new BoxLayout(this,BoxLayout.LINE_AXIS) );
tf1=new JLabel();
tf2=new JLabel();
add(tf1);
add(Box.createRigidArea(new Dimension(5,0)));
add(tf2);
setBackground(bg);
public void setIcons(IconPair value) {
tf1.setIcon(value.i1);
tf2.setIcon(value.i2);
//uncomment next 2 lines if you want text as well
// tf1.setText(value.s1);
// tf2.setText(value.s2);
class IconPair {
public Icon i1,i2;
public String s1,s2;
IconPair(String s1, String s2){
this.i1=icons.get(s1);
this.i2=icons.get(s2);
this.s1=s1;
this.s2=s2;
static Map<String,Icon> icons = new HashMap<String,Icon>();
public static void createIcons(){
Image img = new BufferedImage(10,10, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2=(Graphics2D)(img.getGraphics());
g2.setColor(Color.RED);
g2.drawLine(0,0,10,10);
g2.drawLine(0,10,10,0);
icons.put("cross",new ImageIcon(img));
img = new BufferedImage(10,10, BufferedImage.TYPE_INT_ARGB);
g2=(Graphics2D)(img.getGraphics());
g2.setColor(Color.GREEN);
g2.drawOval(1,1,8,8);
icons.put("circle",new ImageIcon(img));
} -
HI,
Here trying to populate the ImageIcon using JLabel in Jtable cell. For that I used DefaultCellRenderer. For implement the mouseListener to label I used the DefaultCellEditor. I am facing one problem here. After editing the label I selected the second row of the table, the first row image is not displaying. Can any one help on this issue?
public class LabelCellEditor extends DefaultCellEditor {
public LabelCellEditor(final JCheckBox checkBox) {
super(checkBox);
public Component getTableCellEditorComponent(final JTable table, final Object value,
final boolean isSelected, final int row, final int column) {
Color background = null;
background = ColorManager.SELECTED_ROW_BGCOLOR;
labelVal = (JLabel) value;
labelVal.setOpaque(true);
labelVal.setFont(FontManager.TABLE_DATA_FONT);
labelVal.setBackground(background);
labelPanel = new JPanel();
labelPanel.setOpaque(true);
labelPanel.setBackground(background);
labelPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
labelPanel.setBorder(new EmptyBorder(5, 0, 0, 0));
labelPanel.add(labelVal);
return this.labelPanel;
public Object getCellEditorValue() {
return this.labelPanel;
public class LabelCellRenderer extends DefaultTableCellRenderer {
public LabelCellRenderer(final int alignment) {
//setHorizontalAlignment(alignment);
this.align = alignment;
public Component getTableCellRendererComponent(final JTable table, final Object value,
final boolean isSelected, final boolean hasFocus, final int row, final int column) {
if (value != null) {
if (value instanceof JLabel) {
labelVal = (JLabel) value;
labelVal.setOpaque(true);
labelVal.setFont(FontManager.TABLE_DATA_FONT);
labelVal.setBackground(background);
labelVal.setHorizontalAlignment(this.align);
labelVal.setBorder(new EmptyBorder(0, LRPADD, 0, LRPADD));
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(background);
panel.setLayout(new FlowLayout(FlowLayout.LEFT));
panel.setBorder(new EmptyBorder(5, 0, 0, 0));
panel.add(labelVal);
return panel;
return this;
}With more than 30 postings you should know by now how to use the "Code" tags when posting code so the code reatains its original formatting and is therefore more readable.
There is no need to create a custom editor, here is a simple example. -
Shading part of a JTable Cell dependent upon the value of the cell
Hi
Was hoping some one woudl be able to provide some help with this. I'm trying to create a renderer that will "shade" part of a JTable cell's background depending upon the value in the cell as a percentage (E.g. if the cell contains 0.25 then a quarter of the cell background will be shaded)
What I've got so far is a renderer which will draw a rectangle whose width is the relevant percentage of the cell's width. (i.e. the width of the column) based on something similar I found in the forum but the part I'm struggling with is getting it to draw this rectangle in any cell other than the first cell. I've tried using .getCellRect(...) to get the x and y position of the cell to draw the rectangle but I still can't make it work.
The code for my renderer as it stands is:
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
public class PercentageRepresentationRenderer extends JLabel implements TableCellRenderer{
double percentageValue;
double rectWidth;
double rectHeight;
JTable table;
int row;
int column;
int x;
int y;
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof Number)
this.table = table;
this.row = row;
this.column = column;
Number numValue = (Number)value;
percentageValue = numValue.doubleValue();
rectHeight = table.getRowHeight(row);
rectWidth = percentageValue * table.getColumnModel().getColumn(column).getWidth();
return this;
public void paintComponent(Graphics g) {
x = table.getCellRect(row, column, false).x;
y = table.getCellRect(row, column, false).y;
setOpaque(false);
Graphics2D g2d = (Graphics2D)g;
g2d.fillRect(x,y, new Double(rectWidth).intValue(), new Double(rectHeight).intValue());
super.paintComponent(g);
}and the following code produces a runnable example:
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class PercentageTestTable extends JFrame {
public PercentageTestTable()
Object[] columnNames = new Object[]{"A","B"};
Object[][] tableData = new Object[][]{{0.25,0.5},{0.75,1.0}};
DefaultTableModel testModel = new DefaultTableModel(tableData,columnNames);
JTable test = new JTable(testModel);
test.setDefaultRenderer(Object.class, new PercentageRepresentationRenderer());
JScrollPane scroll = new JScrollPane();
scroll.getViewport().add(test);
add(scroll);
public static void main(String[] args)
PercentageTestTable testTable = new PercentageTestTable();
testTable.pack();
testTable.setVisible(true);
testTable.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}If anyone could help or point me in the right direction, I'd appreciate it.
RuanaeThis is an example I published some while ago -
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class Fred120 extends JPanel
static final Object[][] tableData =
{1, new Double(10.0)},
{2, new Double(20.0)},
{3, new Double(50.0)},
{4, new Double(10.0)},
{5, new Double(95.0)},
{6, new Double(60.0)},
static final Object[] headers =
"One",
"Two",
public Fred120() throws Exception
super(new BorderLayout());
final DefaultTableModel model = new DefaultTableModel(tableData, headers);
final JTable table = new JTable(model);
table.getColumnModel().getColumn(1).setCellRenderer( new LocalCellRenderer(120.0));
add(table);
add(table.getTableHeader(), BorderLayout.NORTH);
public class LocalCellRenderer extends DefaultTableCellRenderer
private double v = 0.0;
private double maxV;
private final JPanel renderer = new JPanel(new GridLayout(1,0))
public void paintComponent(Graphics g)
super.paintComponent(g);
g.setColor(Color.CYAN);
int w = (int)(getWidth() * v / maxV + 0.5);
int h = getHeight();
g.fillRect(0, 0, w, h);
g.drawRect(0, 0, w, h);
private LocalCellRenderer(double maxV)
this.maxV = maxV;
renderer.add(this);
renderer.setOpaque(true);
renderer.setBackground(Color.YELLOW);
renderer.setBorder(null);
setOpaque(false);
setHorizontalAlignment(JLabel.CENTER);
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
final JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
if (value instanceof Double)
v = ((Double)value).doubleValue();
return renderer;
public static void main(String[] args) throws Exception
final JFrame frame = new JFrame("Fred120");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new Fred120());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} -
Problem in event handling of combo box in JTable cell
Hi,
I have a combo box as an editor for a column cells in JTable. I have a event listener for this combo box. When ever I click on the JTable cell whose editor is combo box,
I get the following exception,
Exception occurred during event dispatching:
java.lang.NullPointerException
at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.setDispatchComponent(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mousePressed(Unknown Source)
at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Can any one tell me how to over come this problem.
Thanks,
RaghuHere's an example of the model I used in my JTable. I've placed 2 comboBoxes with no problems.
Hope this helps.
public class FileModel5 extends AbstractTableModel
public boolean isEditable = false;
protected static int NUM_COLUMNS = 3;
// initialize number of rows to start out with ...
protected static int START_NUM_ROWS = 0;
protected int nextEmptyRow = 0;
protected int numRows = 0;
static final public String file = "File";
static final public String mailName = "Mail Id";
static final public String postName = "Post Office Id";
static final public String columnNames[] = {"File", "Mail Id", "Post Office Id"};
// List of data
protected Vector data = null;
public FileModel5()
data = new Vector();
public boolean isCellEditable(int rowIndex, int columnIndex)
// The 2nd & 3rd column or Value field is editable
if(isEditable)
if(columnIndex > 0)
return true;
return false;
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
public Class getColumnClass(int c)
return getValueAt(0, c).getClass();
* Retrieves number of columns
public synchronized int getColumnCount()
return NUM_COLUMNS;
* Get a column name
public String getColumnName(int col)
return columnNames[col];
* Retrieves number of records
public synchronized int getRowCount()
if (numRows < START_NUM_ROWS)
return START_NUM_ROWS;
else
return numRows;
* Returns cell information of a record at location row,column
public synchronized Object getValueAt(int row, int column)
try
FileRecord5 p = (FileRecord5)data.elementAt(row);
switch (column)
case 0:
return (String)p.file;
case 1:
return (String)p.mailName;
case 2:
return (String)p.postName;
catch (Exception e)
return "";
public void setValueAt(Object aValue, int row, int column)
FileRecord5 arow = (FileRecord5)data.elementAt(row);
arow.setElementAt((String)aValue, column);
fireTableCellUpdated(row, column);
* Returns information of an entire record at location row
public synchronized FileRecord5 getRecordAt(int row) throws Exception
try
return (FileRecord5)data.elementAt(row);
catch (Exception e)
throw new Exception("Record not found");
* Used to add or update a record
* @param tableRecord
public synchronized void updateRecord(FileRecord5 tableRecord)
String file = tableRecord.file;
FileRecord5 p = null;
int index = -1;
boolean found = false;
boolean addedRow = false;
int i = 0;
while (!found && (i < nextEmptyRow))
p = (FileRecord5)data.elementAt(i);
if (p.file.equals(file))
found = true;
index = i;
} else
i++;
if (found)
{ //update
data.setElementAt(tableRecord, index);
else
if (numRows <= nextEmptyRow)
//add a row
numRows++;
addedRow = true;
index = nextEmptyRow;
data.addElement(tableRecord);
//Notify listeners that the data changed.
if (addedRow)
nextEmptyRow++;
fireTableRowsInserted(index, index);
else
fireTableRowsUpdated(index, index);
* Used to delete a record
public synchronized void deleteRecord(String file)
FileRecord5 p = null;
int index = -1;
boolean found = false;
int i = 0;
while (!found && (i < nextEmptyRow))
p = (FileRecord5)data.elementAt(i);
if (p.file.equals(file))
found = true;
index = i;
} else
i++;
if (found)
data.removeElementAt(i);
nextEmptyRow--;
numRows--;
fireTableRowsDeleted(START_NUM_ROWS, numRows);
* Clears all records
public synchronized void clear()
int oldNumRows = numRows;
numRows = START_NUM_ROWS;
data.removeAllElements();
nextEmptyRow = 0;
if (oldNumRows > START_NUM_ROWS)
fireTableRowsDeleted(START_NUM_ROWS, oldNumRows - 1);
fireTableRowsUpdated(0, START_NUM_ROWS - 1);
* Loads the values into the combo box within the table for mail id
public void setUpMailColumn(JTable mapTable, ArrayList mailList)
TableColumn col = mapTable.getColumnModel().getColumn(1);
javax.swing.JComboBox comboMail = new javax.swing.JComboBox();
int s = mailList.size();
for(int i=0; i<s; i++)
comboMail.addItem(mailList.get(i));
col.setCellEditor(new DefaultCellEditor(comboMail));
//Set up tool tips.
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for mail Id list");
col.setCellRenderer(renderer);
//Set up tool tip for the mailName column header.
TableCellRenderer headerRenderer = col.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer)
((DefaultTableCellRenderer)headerRenderer).setToolTipText(
"Click the Mail Id to see a list of choices");
* Loads the values into the combo box within the table for post office id
public void setUpPostColumn(JTable mapTable, ArrayList postList)
TableColumn col = mapTable.getColumnModel().getColumn(2);
javax.swing.JComboBox combo = new javax.swing.JComboBox();
int s = postList.size();
for(int i=0; i<s; i++)
combo.addItem(postList.get(i));
col.setCellEditor(new DefaultCellEditor(combo));
//Set up tool tips.
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for post office Id list");
col.setCellRenderer(renderer);
//Set up tool tip for the mailName column header.
TableCellRenderer headerRenderer = col.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer)
((DefaultTableCellRenderer)headerRenderer).setToolTipText(
"Click the Post Office Id to see a list of choices");
} -
Hi,
I have just started coding in Swings and would like to find out ways by which I can add JtextField in a JTable cell. Is there any?
Thanks in Advance.
CheenaThere sure is. The thing you're looking for is the cells TableCellEditor. Check out this tutorial, it will explain how to use CellEditors, you should have no diffculties adapting the example to your needs (otherwise just post again :-)
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html -
Multiple JButtons inside JTable cell - Dispatch mouse clicks
Hi.
I know this subject has already some discussions on the forum, but I can't seem to find anything that solves my problem.
In my application, every JTable cell is a JPanel, that using a GridLayout, places vertically several JPanel's witch using an Overlay layout contains a JLabel and a JButton.
As you can see, its a fairly complex cell...
Unfortunately, because I use several JButtons in several locations inside a JTable cell, sometimes I can't get the mouse clicks to make through.
This is my Table custom renderer:
public class TimeTableRenderer implements TableCellRenderer {
Border unselectedBorder = null;
Border selectedBorder = null;
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
if (value instanceof BlocoGrid) {
if (isSelected) {
if (selectedBorder == null)
selectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getSelectionBackground());
((BlocoGrid) value).setBorder(selectedBorder);
} else {
if (unselectedBorder == null)
unselectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getBackground());
((BlocoGrid) value).setBorder(unselectedBorder);
return (Component) value;
}and this is my custom editor (so clicks can get passed on):
public class TimeTableEditor extends AbstractCellEditor implements TableCellEditor {
private TimeTableRenderer render = null;
public TimeTableEditor() {
render = new TimeTableRenderer();
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
if (value instanceof BlocoGrid) {
if (((BlocoGrid) value).barras.size() > 0) {
return render.getTableCellRendererComponent(table, value, isSelected, true, row, column);
return null;
public Object getCellEditorValue() {
return null;
}As you can see, both the renderer and editor return the same component that cames from the JTable model (all table values (components) only get instantiated once, so the same component is passed on to the renderer and editor).
Is this the most correct way to get clicks to the cell component?
Please check the screenshot below to see how the JButtons get placed inside the cell:
http://img141.imageshack.us/my.php?image=calendarxo9.jpg
If you need more info, please say so.
Thanks.My mistake... It worked fine. The cell span code was malfunctioning. Thanks anyway.
Maybe you are looking for
-
Difference in configuration of taxinj and taxinn
hello all, can anyone explain in detail what is the diffrence in customization od TAXINN and TAXINJ? i have serch lots of thread in SDN but no one shows the difference in between from customization point of view. your help will be highly apperciated.
-
So I am attempting to grant access for JExport. Please help. MAXL> grant codeBase "file:\\Hyperion\AnalyticServices\java\udf\ExportCDF.jar" { permission java.security.AllPermission}; I am receiving this message: ERROR - 1242021 - (1) Syntax error nea
-
The ipod is diabled when connected to the itunes
the ipod is disabled
-
Youtube video's does not play at facebook startpage
Hi, I have windows 7 and use Internet explorer 11. When I start to play a youtube video on facebook startpage, It start to play normal. But when I want to change the sound, or scroll in the movie. It stop playing, and it crashes. IE11 doesn't respond
-
Whenever I try to import videos, an error tab appears, saying "Could not complete your request because DynamicLink is not available"