Image in a JTable (2)

Thanks for the code, it does compile but it does not display the image.
Maybe if you give a look at the whole code it will be easier.
You said to use MyTableRenderer() but maybe you meant MyCellRenderer().
What do you think ?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.io.*;
import java.beans.*;
import javax.imageio.*;
public class yearPlannerBean extends JFrame implements ListSelectionListener,ActionListener,Serializable
private String dayNames[] = {"Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"};
private String engMonths[] = {"January","February","March","April","May","June","July","August","September","October","November","December"};
private String spaMonths[] = {"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"};
private String spadays[]={"S�bado", "Domingo", "Lunes", "Martes", "Mi�rcoles", "Jueves", "Viernes"};
private String itaMonths[] = {"Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"};
private String itadays[]={"Sabato","Domenica","Lunedi","Martedi","Mercoledi","Giovedi","Venerdi"};
private Object fieldValues[][];
private String panelTitle;
private JPanel container;
private JPanel languages;
private JPanel choice;
private JTable planner;
private String days[];
private JScrollPane scrollPane;
private int month;
private int noOfDays;
private int year;
private Zellar zell;
private PropertyChangeSupport support;
private Image icon;
private next bbnext;
private previous bbpre;
private JLabel lan;
private JLabel curry;
private JTextField curye;
private JList linlist;
public yearPlannerBean()
panelTitle = ("Year Planner");
setTitle(panelTitle);
setSize(300,300);
month = 0;
noOfDays = 0;
year = 2003;
zell = new Zellar(1,month,year);
container = new JPanel();
container.setLayout(new BorderLayout());
languages = new JPanel();
choice= new JPanel();
lan= new JLabel("Select Language: ");
String[] words={"English","Italian","Spanish"};
JList linlist= new JList(words);
JScrollPane sc =new JScrollPane(linlist);
linlist.addListSelectionListener(this);
planner = new JTable(getFieldValues(),setColumnNames());
planner.setRowHeight(100);
planner.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
planner.setRowSelectionAllowed(true);
planner.setColumnSelectionAllowed(true);
//myTable.setDefaultRenderer(Object.class, new MyTableRenderer());
planner.setDefaultRenderer(Object.class,new MyCellRenderer());
scrollPane = new JScrollPane(planner);
bbnext= new next();
bbpre=new previous();
bbnext.addActionListener(this);
bbpre.addActionListener(this);
getContentPane().setLayout(new BorderLayout());
container.add(scrollPane,BorderLayout.CENTER);
curry= new JLabel("Current Year");
curye= new JTextField(5);
curye.setText(Integer.toString(year));
choice.add(bbpre);
choice.add(bbnext);
languages.add(curry);
languages.add(curye);
languages.add(lan);
languages.add(linlist);
container.add(choice,BorderLayout.SOUTH);
container.add(languages,BorderLayout.NORTH);
setContentPane(container);
pack();
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
}//End constructor
public String[] setColumnNames()
days = new String[38];
int count = 0;
int index = 0;
for (index = 0; index < 38; index++)
if (index == 0)
days[index] = "";
else
days[index] = dayNames[count];
if (count != 6)
count++;
else
count = 0;
return days;
}//End getColumnNames
public Object[][] getFieldValues()
int countY = 0;
int countX = 0;
String firstDay = "";
int dayInt;
int dayCount = 0;
int tempCount = 0;
fieldValues = new Object[12][38];
for (countX = 0; countX < 38; countX++)
for (countY = 0; countY < 12; countY++)
monthToInt(engMonths[countY]);
firstDay = zell.getFirstDay(month,year);
dayInt = dayToInt(firstDay);
for (month = 1; month < 12; month++)
tempCount = 1;
for (dayCount = dayInt; dayCount < (noOfDays+dayInt); dayCount++)
if (countX == 0)
fieldValues[countY][countX] = engMonths[countY];
else
//fieldValues.setCellRenderer(new acellrenderer());
fieldValues[countY][dayCount]="" + tempCount;//setIcon(new ImageIcon(icon));
tempCount++;
return fieldValues;
}//End getFieldValues
public void monthToInt(String monthIn)
boolean temp = false;
if (monthIn == "January")
month = 1;
noOfDays = 31;
else
if (monthIn == "February")
month = 2;
if ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)))
noOfDays = 29;
else
noOfDays = 28;
else
if (monthIn == "March")
month = 3;
noOfDays = 31;
else
if (monthIn == "April")
month = 4;
noOfDays = 30;
else
if (monthIn == "May")
month = 5;
noOfDays = 31;
else
if (monthIn == "June")
month = 6;
noOfDays = 30;
else
if (monthIn == "July")
month = 7;
noOfDays = 31;
else
if (monthIn == "August")
month = 8;
noOfDays = 31;
else
if (monthIn == "September")
month = 9;
noOfDays = 30;
else
if (monthIn == "October")
month = 10;
noOfDays = 31;
else
if (monthIn == "November")
month = 11;
noOfDays = 30;
else
if (monthIn == "December")
month = 12;
noOfDays = 31;
}//End monthToInt
public int dayToInt(String dayIn)
int dayOut = 0;
if (dayIn == "Saturday")
dayOut = 1;
else
if (dayIn == "Sunday")
dayOut = 2;
else
if (dayIn == "Monday")
dayOut = 3;
else
if (dayIn == "Tuesday")
dayOut = 4;
else
if (dayIn == "Wednesday")
dayOut = 5;
else
if (dayIn == "Thursday")
dayOut = 6;
else
if (dayIn == "Friday")
dayOut = 7;
return dayOut;
}//End dayToInt
/*class acellrenderer extends DefaultTableCellRenderer
public acellrenderer()
super();
public Component getTableCellRendererComponent (JTable planner)
Component component=super.getTableCellRenderer();
String filepa;
filepa="caley.GIF";
ImageIcon nn;
component.setIcon(new ImageIcon(filepa));
return component;
static class MyCellRenderer extends DefaultTableCellRenderer
{ final Icon icon = new ImageIcon("caley.gif");
public MyCellRenderer ()
super();
public void setValue(Object value)
if(value == null)
{ setText("");
setIcon(icon);
else
setText(String.valueOf(value));
public void actionPerformed(ActionEvent event)
Object source=event.getSource();
int a;
if (source==bbnext)
// button next pressed
a=Integer.parseInt(curye.getText());
curye.setText(Integer.toString(a+1));
else
if (source==bbpre)
// button previous pressed
a=Integer.parseInt(curye.getText());
curye.setText(Integer.toString(a-1));
private int getindex(String astring)
int index=-1;
if(astring.toUpperCase().equals("ENGLISH"))
index=0;
else
if (astring.toUpperCase().equals("ITALIAN"))
index=1;
else
index=2;
return index;
public void valueChanged(ListSelectionEvent event)
JList source=(JList)event.getSource();
Object asel;
int index;
if (source==linlist)
asel=linlist.getSelectedValue();
index=getindex((String)asel);
if (index==0)
// set header in English;
else
if (index==1)
// set header in Italian;
else
if (index==2)
// set header in Spanish;
public static void main(String args[])
yearPlannerBean test = new yearPlannerBean();
test.setVisible(true);
}//End Main
}//End class

There are too many unresolved classes in your code for me to use it. Here is a simple example of putting an icon in a table.import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class Test extends JFrame {
  public Test() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = getContentPane();
    String[] head = {"One","Two","Three"};
    String[][] data = {{"R1-C1","R1-C2","R1-C3"},
                       {"R1-C1","R1-C2","R1-C3"},
                       {"R1-C1","R1-C2","R1-C3"}};
    JTable jt = new JTable(data,head);
    content.add(new JScrollPane(jt), BorderLayout.CENTER);
    jt.setDefaultRenderer(Object.class,
                          new MyCellRenderer(new ImageIcon("C:\\duke\\t1.gif")));
    setSize(200, 200);
    show();
  public static void main(String args[]) { new Test(); }
class MyCellRenderer extends JLabel implements TableCellRenderer {
  Icon icon;
  public MyCellRenderer(Icon icon) { this.icon = icon; }
  public Component getTableCellRendererComponent(
                            JTable table, Object color,
                            boolean isSelected, boolean hasFocus,
                            int row, int column) {
    if ((row+column)%3==0) setIcon(null);
    else setIcon(icon);
    return this;
}

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 );
    }

  • Image in a JTable

    Hello, i am trying to display an image.gif in a JTable using cellrenderer but i always get an error message. Everybodys help its always accepted.
    I did paste just a few parts of the code since its very long. In the cellrenderer class i have scored out those 3 lines.
    In all the books that i have read ( quite a few there is not a single full coded program that shows how to insert a picture in a cell of the table).
    What i am trying to do is, when creating the table insert all pictures in all cells and then with a loop insert the relevant data.
    In other words the picture should appear only in cells containing no data.
         planner = new JTable(getFieldValues(),setColumnNames());
              planner.setRowHeight(30);
              planner.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              planner.setRowSelectionAllowed(true);
              planner.setColumnSelectionAllowed(true);
              planner.setDefaultRenderer(ImageIcon.class,new cellrenderer());
         class cellrenderer implements TableCellRenderer
              public Component getTableCellRendererComponent (JTable planner, Object xw, boolean isSelected,boolean hasFocus, int row, int column)
                   String cd;
                   cd="xx.gif";
                   //xw= new ImageIcon(cd);
                   //panel.setBackground(ImageIcon(xw));
                   //setImage(new ImageIcon(cd));
                   return panel;
                   JPanel panel=new JPanel();

    Thanks for the code, it does compile but it does not display the image.
    Maybe if you give a look at the whole code it will be easier.
    You said to use MyTableRenderer() but maybe you meant MyCellRenderer().
    What do you think ?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.io.*;
    import java.beans.*;
    import javax.imageio.*;
    public class yearPlannerBean extends JFrame implements ListSelectionListener,ActionListener,Serializable
         private String dayNames[] = {"Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"};
         private String engMonths[] = {"January","February","March","April","May","June","July","August","September","October","November","December"};
         private String spaMonths[] = {"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"};
         private String spadays[]={"S�bado", "Domingo", "Lunes", "Martes", "Mi�rcoles", "Jueves", "Viernes"};
         private String itaMonths[] = {"Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"};
         private String itadays[]={"Sabato","Domenica","Lunedi","Martedi","Mercoledi","Giovedi","Venerdi"};
         private Object fieldValues[][];
         private String panelTitle;
         private JPanel container;
         private JPanel languages;
         private JPanel choice;
         private JTable planner;
         private String days[];
         private JScrollPane scrollPane;
         private int month;
         private int noOfDays;
         private int year;
         private Zellar zell;
         private PropertyChangeSupport support;
         private Image icon;
         private next bbnext;
         private previous bbpre;
         private JLabel lan;
         private JLabel curry;
         private JTextField curye;
         private JList linlist;
         public yearPlannerBean()
              panelTitle = ("Year Planner");
              setTitle(panelTitle);
              setSize(300,300);
              month = 0;
              noOfDays = 0;
              year = 2003;
              zell = new Zellar(1,month,year);
              container = new JPanel();
              container.setLayout(new BorderLayout());
              languages = new JPanel();
              choice= new JPanel();
              lan= new JLabel("Select Language: ");
              String[] words={"English","Italian","Spanish"};
              JList linlist= new JList(words);
              JScrollPane sc =new JScrollPane(linlist);
              linlist.addListSelectionListener(this);
              planner = new JTable(getFieldValues(),setColumnNames());
              planner.setRowHeight(100);
              planner.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              planner.setRowSelectionAllowed(true);
              planner.setColumnSelectionAllowed(true);
              //myTable.setDefaultRenderer(Object.class, new MyTableRenderer());
              planner.setDefaultRenderer(Object.class,new MyCellRenderer());
              scrollPane = new JScrollPane(planner);
              bbnext= new next();
              bbpre=new previous();
              bbnext.addActionListener(this);
              bbpre.addActionListener(this);
              getContentPane().setLayout(new BorderLayout());
              container.add(scrollPane,BorderLayout.CENTER);
              curry= new JLabel("Current Year");
              curye= new JTextField(5);
              curye.setText(Integer.toString(year));
              choice.add(bbpre);
              choice.add(bbnext);
              languages.add(curry);
              languages.add(curye);
              languages.add(lan);
              languages.add(linlist);
              container.add(choice,BorderLayout.SOUTH);
              container.add(languages,BorderLayout.NORTH);
              setContentPane(container);
              pack();
              addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent e)
                        System.exit(0);
         }//End constructor
         public String[] setColumnNames()
              days = new String[38];
              int count = 0;
              int index = 0;
              for (index = 0; index < 38; index++)
                   if (index == 0)
                        days[index] = "";
                   else
                        days[index] = dayNames[count];
                        if (count != 6)
                             count++;
                        else
                             count = 0;
              return days;
         }//End getColumnNames
         public Object[][] getFieldValues()
              int countY = 0;
              int countX = 0;
              String firstDay = "";
              int dayInt;
              int dayCount = 0;
              int tempCount = 0;
              fieldValues = new Object[12][38];
              for (countX = 0; countX < 38; countX++)
                   for (countY = 0; countY < 12; countY++)
                        monthToInt(engMonths[countY]);
                        firstDay = zell.getFirstDay(month,year);
                        dayInt = dayToInt(firstDay);
                        for (month = 1; month < 12; month++)
                             tempCount = 1;
                             for (dayCount = dayInt; dayCount < (noOfDays+dayInt); dayCount++)
                                  if (countX == 0)
                                       fieldValues[countY][countX] = engMonths[countY];
                                  else
                                       //fieldValues.setCellRenderer(new acellrenderer());
                                       fieldValues[countY][dayCount]="" + tempCount;//setIcon(new ImageIcon(icon));
                                  tempCount++;
              return fieldValues;
         }//End getFieldValues
         public void monthToInt(String monthIn)
              boolean temp = false;
              if (monthIn == "January")
                   month = 1;
                   noOfDays = 31;
              else
                   if (monthIn == "February")
                        month = 2;
                        if ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)))
                             noOfDays = 29;
                        else
                             noOfDays = 28;
                   else
                        if (monthIn == "March")
                             month = 3;
                             noOfDays = 31;
                        else
                             if (monthIn == "April")
                                  month = 4;
                                  noOfDays = 30;
                             else
                                  if (monthIn == "May")
                                       month = 5;
                                       noOfDays = 31;
                                  else
                                       if (monthIn == "June")
                                            month = 6;
                                            noOfDays = 30;
                                       else
                                            if (monthIn == "July")
                                                 month = 7;
                                                 noOfDays = 31;
                                            else
                                                 if (monthIn == "August")
                                                      month = 8;
                                                      noOfDays = 31;
                                                 else
                                                      if (monthIn == "September")
                                                           month = 9;
                                                           noOfDays = 30;
                                                      else
                                                           if (monthIn == "October")
                                                                month = 10;
                                                                noOfDays = 31;
                                                           else
                                                                if (monthIn == "November")
                                                                     month = 11;
                                                                     noOfDays = 30;
                                                                else
                                                                     if (monthIn == "December")
                                                                          month = 12;
                                                                          noOfDays = 31;
         }//End monthToInt
         public int dayToInt(String dayIn)
              int dayOut = 0;
              if (dayIn == "Saturday")
                   dayOut = 1;
              else
                   if (dayIn == "Sunday")
                        dayOut = 2;
                   else
                        if (dayIn == "Monday")
                             dayOut = 3;
                        else
                             if (dayIn == "Tuesday")
                                  dayOut = 4;
                             else
                                  if (dayIn == "Wednesday")
                                       dayOut = 5;
                                  else
                                       if (dayIn == "Thursday")
                                            dayOut = 6;
                                       else
                                            if (dayIn == "Friday")
                                                 dayOut = 7;
              return dayOut;
         }//End dayToInt
         /*class acellrenderer extends DefaultTableCellRenderer
              public acellrenderer()
                   super();
              public Component getTableCellRendererComponent (JTable planner)
                   Component component=super.getTableCellRenderer();
                   String filepa;
                   filepa="caley.GIF";
                   ImageIcon nn;
                   component.setIcon(new ImageIcon(filepa));
                   return component;
    static class MyCellRenderer extends DefaultTableCellRenderer
    {    final Icon icon = new ImageIcon("caley.gif");
         public MyCellRenderer ()
              super();
         public void setValue(Object value)
         if(value == null)
              {             setText("");
              setIcon(icon);
              else
                   setText(String.valueOf(value));
    public void actionPerformed(ActionEvent event)
         Object source=event.getSource();
         int a;
         if (source==bbnext)
         // button next pressed
         a=Integer.parseInt(curye.getText());
         curye.setText(Integer.toString(a+1));
         else
              if (source==bbpre)
                   // button previous pressed
                   a=Integer.parseInt(curye.getText());
                   curye.setText(Integer.toString(a-1));
    private int getindex(String astring)
         int index=-1;
         if(astring.toUpperCase().equals("ENGLISH"))
              index=0;
              else
              if (astring.toUpperCase().equals("ITALIAN"))
              index=1;
              else
              index=2;
              return index;
         public void valueChanged(ListSelectionEvent event)
              JList source=(JList)event.getSource();
              Object asel;
              int index;
              if (source==linlist)
                   asel=linlist.getSelectedValue();
                   index=getindex((String)asel);
                   if (index==0)
                        // set header in English;
                        else
                             if (index==1)
                             // set header in Italian;
                             else
                                  if (index==2)
                                  // set header in Spanish;
         public static void main(String args[])
              yearPlannerBean test = new yearPlannerBean();
              test.setVisible(true);
         }//End Main
    }//End class

  • Image in a JTable cell

    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

  • Drag and Drop Image into JTable

    I was wondering if anyone can tell me if it is possible to have an image dragged and dropped into a JTable where the single image snaps to multiple columns and rows?
    Thank you.

    Can anyone point me in the right direction for doing the following:
    Drag and drop an image into a JTable where the single image snaps to multiple columns and rows.
    Thanks.

  • Adding  images in  JTable !

    Hello all !
    I have a database with a table which contains information about an image and the PATH for it. I want display the database table in a JTable but I don't know how i can display the Image in a Jtable if I had the path of it in a database.

    f.getContentPane().add(new JScrollPane(new JTable(adaptor){
    public Class getColumnClass(int column)
    return getValueAt(0, column).getClass();
    i have the path inside the column six not the first sorry!
    sorry for this message It's late and i am very tired
    i have i9n database a filed whish contains :
    new ImageIcon ("c:\x\x\xyz.jpg")
    and i tried to change the renderer whith
    f.getContentPane().add(new JScrollPane(new JTable(adaptor){
    public Class getColumnClass(int column)
    return getValueAt(0, column).getClass();
    i don't know where is mistake?
    Message was edited by:
    aurelian_cl

  • Images in JTable

    Hi,
    The Problem:
    Instead of the Image i see the image's filename.
    The Question:
    Which is the simplest way to display an Image in a JTable?

    Hi.. mathuoa
    You can set the row height as:
    table.setRowHeight(300);
    Here's the abstract table model implementaion e.g.
    * Implementation of abstract table model for displaying Image(s) in table
    * Cell grid.
    * @version 1.0 10 Sep 2002
    * @author Md. Ash-Shakur Rahaman (mailto: [email protected])
    class GridImageTableModel extends AbstractTableModel{
    /** Number of rows */
    static int rows;
    /** Number of columns*/
    static int cols;
    /** table data */
    public static Object[][] rowData;
    /**column names */
    String[] colNames;
    * Constructor
    * @param     rd     row data as 2D Object array
    * @param     cn     column names as 1D String array
    public GridImageTableModel(Object[][] rd, String[] cn){
    this.rowData = rd;
    this.colNames = cn;
    * gets the number of rows available of the table
    * @param     nothing no parameter is required
    * @return rows     returns the rows count as int
    public int getRowCount(){
    this.rows = rowData.length;
    return rows;
    * gets the number of columns available of the table
    * @param     nothing     no parameter is required
    * @return cols     returns the column count as int
    public int getColumnCount(){
    this.cols = colNames.length;
    return cols;
    * gets the data at particular row & column
    * @param     row     at which row
    * @param     col     at which column
    * @return rowData the data as 2D Object array
    public Object getValueAt(int row, int col){
    return rowData[row][col];
    * gets the class name of a particular column
    * @param     c     column number for which the class names is to be determined
    * @return     class     returns the class name of the column
    public Class getColumnClass(int c){
    return getValueAt(0,c).getClass();
    * gets the column cell editable or non editable
    * @param row     which row
    * @param col     which column
    * @return editable true if editable;
    * false otherwise     
    public boolean isCellEditable(int row, int col){
    return true;
    * sets the value at particular row-column
    * @param value     value to be inserted
    * @param row     at which row
    * @param col     at which column
    * @return nothing
    public void setValueAt(Object value, int row, int col){
    rowData[row][col] = value;
    fireTableCellUpdated(row,col);
    * Implementation of Default table column model for displaying Image(s) in table
    * Cell grid.
    * @version 1.0 10 Sep 2002
    * @author Md. Ash-Shakur Rahaman (mailto: [email protected])
    class GridImageTableColModel extends DefaultTableColumnModel{
    /**column names*/
    String [] colNames;
    /**column counter*/
    static int counter=0;
    * GridImageTableColModel constructor with column names
    * @param cn coumn names as 1D String array
    public GridImageTableColModel(String[] cn){
    this.colNames = cn;
    * adds column to the table
    * @param tc table column
    * @return nothing
    public void addColumn(TableColumn tc){
    // if counter is equal to the number of column then reset counter to zero
    if (counter == 1) counter=0;
    tc.setHeaderValue(DataStoreUnit.grdimgColumnNames[counter]);
    tc.setResizable(false);
    super.addColumn(tc);
    counter+=1;
    Use this as follwoung manner:
    //Grid Image Table Implementation
    final static String[] grdimgColumnNames = {"Image(s)"};
    // Initial data to be displayed in the table
    final Object[][] grdimgData = {{""}};
    //Grid Image Table Model: Table to display the data
    TableModel grdimgTableModel = new GridImageTableModel(grdimgData,grdimgColumnNames);
    //Grid text Table Header
    JTableHeader grdimgTableHeader = new JTableHeader();
    // Grid image Column Model
    TableColumnModel grdimgTableColumnModel = new GridImageTableColModel(grdimgColumnNames);
    // Grid Image Table
    JTable grdimgtable = new JTable(grdimgTableModel);
    JScrollPane jspGridImageTable = new JScrollPane();
    int tab = grdimgtable.AUTO_RESIZE_ALL_COLUMNS;
    grdimgTableHeader.setResizingAllowed(false);
    grdimgTableHeader.setBackground(new Color(0, 0, 239));
    grdimgTableHeader.setForeground(Color.white);
    grdimgTableHeader.setFont(font);
    grdimgTableHeader.setColumnModel(grdimgTableColumnModel);
    grdimgtable.setTableHeader(grdimgTableHeader);
    grdimgtable.createDefaultColumnsFromModel();
    grdimgtable.sizeColumnsToFit(tab);
    grdimgTableHeader.setReorderingAllowed(false);
    grdimgtable.setRowHeight(300);
    /**render the first cell in the table*/     
    grdimgTableCellRender(grdimgtable.getColumnModel().getColumn(0));
    grdimgtable.setPreferredSize(new Dimension(32767,32767));
    jspGridImageTable.getViewport().add(grdimgtable, null);
    grdimgtable.setBorder(new LineBorder(Color.blue));
    I think now you can work...Go ahead..
    Rana

  • Place image in jtable

    Hello I want to place an image in a jtable.
    How can I do this because when I tried it I only saw the link to the file

    There are two things you need to to:
    a) use an Icon as your data for a column
    b) tell the table what type of data you are using for each column:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableIcon extends JFrame
         public TableIcon()
              ImageIcon aboutIcon = new ImageIcon("about16.gif");
              ImageIcon addIcon = new ImageIcon("add16.gif");
              ImageIcon copyIcon = new ImageIcon("copy16.gif");
              String[] columnNames = {"Picture", "Description"};
              Object[][] data =
                   {aboutIcon, "About"},
                   {addIcon, "Add"},
                   {copyIcon, "Copy"},
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              JTable table = new JTable( model )
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              //  Set the first column to use a combobox as its editor
              Object[] items = { aboutIcon, addIcon, copyIcon };
              JComboBox editor = new JComboBox( items );
              DefaultCellEditor dce = new DefaultCellEditor( editor );
              table.getColumnModel().getColumn(0).setCellEditor(dce);
         public static void main(String[] args)
              TableIcon frame = new TableIcon();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }

  • Thumnail and JTable

    Hello all
    In my database, I have a table of images (image file name with a blod field). I also have a JTable to display the name of these images. Now I need to display thumbnails for these images in this JTable.
    My question is: do I have to create a thumbnail image for each image to show in the JTable (that means I need a new field in the image table) OR I can use these images as thumbnails.
    Thanks
    suhu

    Hello all
    In my database, I have a table of images (image file
    name with a blod field). I also have a JTable to
    display the name of these images. Now I need to
    display thumbnails for these images in this JTable.
    My question is: do I have to create a thumbnail image
    for each image to show in the JTable (that means I
    need a new field in the image table) OR I can use
    these images as thumbnails.
    Thanks
    suhuWhat you need to do is write a new TableCellRenderer to display the image.
    You can then use the original images and just scale them on the fly...
    Read through the JTable tutorial for information on writing custom renderers
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editrender

  • Create an Image from a Component

    Can anybody tell me how to create an Image from a Component?
    I intend to create an Image from a JTable now but I want to have a more generic solution of course to be able to create an Image from any Java / Swing component (Applet, JList, JButton, ...).
    Thank you,
    Dirk

    2 ways:
    1) java.awt.Toolkit.createScreenCapture(Rectangle bounds)
    2) This:
         public static BufferedImage grabByPaint(Component comp) {
              boolean visible = comp.isVisible();
              // if not visible, need to make visible to make sure sizes are correct. 
              if(!visible) {
                   comp.setVisible(true);
              Dimension size = comp.getSize();
              BufferedImage bi = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g2d = bi.createGraphics();
              comp.paintAll(g2d);
              if(!visible) {
                   comp.setVisible(false);
              g2d.dispose();
              return bi;
         }

  • How to change color of selected label from list of labels?

    My Problem is that I have a list of labels. RowHeaderRenderer is a row header renderer for Jtable which is rendering list items and (labels).getListTableHeader() is a method to get the list. When we click on the label this code is executed:
    getListTableHeader().addMouseListener(new MouseAdapter()
    public void mouseReleased(MouseEvent e)
    if (e.getClickCount() >= 1)
    int index = getListTableHeader().locationToIndex(e.getPoint());
    try
    if (((ae_AlertEventInfo)theAlerts.values().toArray()[index]).ackRequiredFlag)
    AcknowledgeEvent ackEvent = new AcknowledgeEvent(
    this, (ae_AlertEventInfo)theAlerts.values().toArray()[index]);
    fireAcknowledgeEvent(ackEvent);
    ((HeaderListModel)listModel).setElementAt(ACK, index);
    catch(Exception ex) {;}
    Upon mouse click color of the label should be changed. For some period of time ie. Upto completion of fireAcknowledgeEvent(ackEvent);
    This statement is calling this method:
    public void handleAcknowledgeEvent(final AcknowledgeEvent event)
    boolean ackOk = false;
    int seqId = ((ae_AlertEventInfo)event.getAlertInfo()).sequenceId;
    if (((ae_AlertEventInfo)event.getAlertInfo()).ackRequiredFlag)
    try
    // perform call to inform server about acknowledgement.
    ackOk = serviceAdapter.acknowledge(seqId,
    theLogicalPosition, theUserName);
    catch(AdapterException aex)
    Log.error(getClass(), "handleAcknowledgeEvent()",
    "Error while calling serviceAdapter.acknowledge()", aex);
    ExceptionHandler.handleException(aex);
    else
    // Acknowledge not required...
    ackOk = true;
    //theQueue.buttonAcknowledge.setEnabled(false);
    final AlertEventQueue myQueue = theQueue;
    if (ackOk)
    Object popupObj = null;
    synchronized (mutex)
    if( hasBeenDismissed ) { return; }
    // mark alert event as acknowledged (simply reset ack req flag)
    ae_AlertEventInfo info;
    Iterator i = theAlerts.values().iterator();
    while (i.hasNext())
    info = (ae_AlertEventInfo) i.next();
    if (info.sequenceId == seqId)
    // even if ack wasn't required, doesn't hurt to set it
    // to false again. But it is important to prevent the
    // audible from playing again.
    info.ackRequiredFlag = false;
    info.alreadyPlayed = true;
    // internally uses the vector index so
    // process the queue acknowledge update within
    // the synchronize block.
    final ae_AlertEventInfo myAlertEventInfo = event.getAlertInfo();
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    myQueue.acknowledge(myAlertEventInfo);
    myQueue.updateAcknowledgeButtonState();
    // here we should stop playing sound
    // if it is playing for this alert.
    int seqId1;
    if (theTonePlayer != null)
    seqId1 = theTonePlayer.getSequenceId();
    if (seqId1 == seqId)
    if (! theTonePlayer.isStopped())
    theTonePlayer.stopPlaying();
    theTonePlayer = null;
    // get reference to popup to be dismissed...
    // The dismiss must take place outside of
    // the mutex... otherwise threads potentially
    // hang (user hits "ok" and is waiting for the
    // mutex which is currently held by processing
    // for a "move to summary" transition message.
    // if the "dismiss" call in the transition
    // message were done within the mutex, it might
    // hang on the dispose method because the popup
    // is waiting for the mutex...
    // So call popup.dismiss() outside the mutex
    // in all cases.
    if(event.getSource() instanceof AlertEventPopup)
    popupObj = (AlertEventPopup)event.getSource();
    else
    popupObj = thePopups.get(event.getAlertInfo());
    thePopups.remove(event.getAlertInfo());
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    // search vector elements to determine icon color in main frame
    String color = getColor();
    fireUpdateEvent(new UpdateEvent(this, blinking, color));
    // Call dismiss outside of the mutex.
    if (popupObj !=null)
    if(popupObj instanceof AlertEventPopup)
    ((AlertEventPopup)popupObj).setModal(false);
    ((AlertEventPopup)popupObj).setVisible(false); // xyzzy
    ((AlertEventPopup)popupObj).dismiss();
    else
    // update feedback... ack failed
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    myQueue.setInformationMessage("Acknowledge failed to reach server... try again");
    return;
    Code for RowHeaderRenderer is:
    class RowHeaderRenderer extends JLabel implements ListCellRenderer
    JTable theTable = null;
    ImageIcon image = null;
    RowHeaderRenderer(JTable table)
    image = new ImageIcon(AlertEventQueue.class.getResource("images" + "/" + "alert.gif"));
    theTable = table;
    JTableHeader header = table.getTableHeader();
    setOpaque(true);
    setHorizontalAlignment(LEFT);
    setForeground(header.getForeground());
    setBackground(header.getBackground());
    setFont(header.getFont());
    public Component getListCellRendererComponent( JList list, Object value,
    int index, boolean isSelected, boolean cellHasFocus)
    int level = 0;
    try
    level = Integer.parseInt(value.toString());
    catch(Exception e)
    level = 0;
    if (((ae_AlertEventInfo)theAlerts.values().toArray()[index]).ackRequiredFlag)
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    this.setHorizontalAlignment(JLabel.CENTER);
    this.setVerticalAlignment(JLabel.CENTER);
    setIcon(image);
    else
    setBorder(BorderFactory.createLineBorder(Color.gray));
    setText("");
    setIcon(null);
    return this;
    I tried but when i am clicking a particular label, the color of all labels in the List is being changed. So can you please assist me in changing color of only the label that is selected and the color must disappear after completion of Upto completion of fireAcknowledgeEvent(ackEvent);

    im a bit confused with the post so hopefully this will help you, if not then let me know.
    I think the problem is that in your renderer your saying
    setBackground(header.getBackground());which is setting the backgound of the renderer rather than the selected item, please see an example below, I created a very simple program where it adds JLabels to a list and the renderer changes the colour of the selected item, please note the isSelected boolean.
    Object "value" is the currentObject its rendering, obviously you may need to test if its a JLabel before casting it but for this example I kept it simple.
    populating the list
    public void populateList(){
            DefaultListModel model = new DefaultListModel();
            for (int i=0;i<10;i++){
                JLabel newLabel = new JLabel(String.valueOf(i));
                newLabel.setOpaque(true);
                model.addElement(newLabel);           
            this.jListExample.setModel(model);
            this.jListExample.setCellRenderer(new RowHeaderRenderer());
        }the renderer
    class RowHeaderRenderer extends JLabel implements ListCellRenderer
        JTable theTable = null;
        public Component getListCellRendererComponent(JList list, Object value,
                                                      int index, boolean isSelected, boolean cellHasFocus){
            JLabel aLabel = (JLabel)value;
            if (isSelected){
                aLabel.setBackground(Color.RED);
            }else{
                aLabel.setBackground(Color.GRAY);
            return aLabel;       
    }

  • Imageicon in a JComboBox

    hi, i do a program to create "business case table", but i've a problem in the 2nd part of the table, because in my 2nd table i have a JComboBox with image, when i click the combobox the images are show, but when select some figure the cell don�t keep the image, only keep the text.
    Anyone can help me???
    Here is my principal class that create the principal screen and tables:
    /*                      Poseidon                                 */
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    * Summary description for Poseidon
    *2052102
    public class Poseidon extends JFrame
         // Variables declaration
         private JTabbedPane jTabbedPane1;
         private JPanel contentPane, paineltabela, painelgrafo, painelvariavel, paineltarefa;
         private JTable tabelavariavel,tabelatarefa, tabelateste;
         private JScrollPane scrollvariavel, scrolltarefa;
         private int totallinhas, alt, al, linhastarefa,cont, linhas, tamanholinhas,
                        controlalinhas, index, contastring;
         private String variavel;
         private JComboBox combobox;
         JMenuItem sair, abrir, guardar, miadtarefa, miadvariavel;
         JTable [] tabelasvar = new JTable[30];
         JFrame w;
         // End of variables declaration
         public Poseidon()
              super("Poseidon");
              initializeComponent();
              this.setVisible(true);
          * This method is called from within the constructor to initialize the form.
          * WARNING: Do NOT modify this code. The content of this method is always regenerated
          * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
          * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
          * to retrieve your design properly in future, before revising this method.
         private void initializeComponent()
              JMenuBar barra = new JMenuBar();
              setJMenuBar(barra);
              TratBarra trat = new TratBarra();
              tabelavariavel = new JTable();
              tabelatarefa = new JTable();
              tabelavariavel.getTableHeader().setReorderingAllowed(false);
              tabelavariavel.setModel(new DefaultTableModel());
              tabelavariavel.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
              tabelavariavel.setBackground(Color.cyan);
              tabelatarefa.getTableHeader().setReorderingAllowed(false);
              tabelatarefa.setModel(new DefaultTableModel());
              tabelatarefa.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              tabelatarefa.setBackground(Color.white);
              CaixaCombinacao combobox = new CaixaCombinacao();
              DefaultCellEditor editor = new DefaultCellEditor(combobox);
              tabelatarefa.setDefaultEditor(Object.class, editor);
              painelvariavel = new JPanel();
              painelvariavel.setLayout(new GridLayout(1, 0));
              painelvariavel.setBorder(new TitledBorder("Variaveis"));
              painelvariavel.setBounds(15, 35, 490, 650);
              painelvariavel.setVisible(false);
              this.add(painelvariavel);
              scrollvariavel = new JScrollPane();
              scrollvariavel.setViewportView(tabelavariavel);
              painelvariavel.add(scrollvariavel);
              paineltarefa = new JPanel();
              paineltarefa.setLayout(new GridLayout(1,0));
              paineltarefa.setBorder(new TitledBorder("Tarefas"));
              paineltarefa.setBounds(506, 35, 490,650);
              paineltarefa.setVisible(false);
              this.add(paineltarefa);
              scrolltarefa = new JScrollPane();
              scrolltarefa.setViewportView(tabelatarefa);
              paineltarefa.add(scrolltarefa);
              tamanholinhas = 1;
              linhas=1;
              cont=0;
              JMenu arquivo = new JMenu("Arquivo");
              JMenu mtabela = new JMenu("Tabela");
              arquivo.setMnemonic(KeyEvent.VK_A);
              mtabela.setMnemonic(KeyEvent.VK_T);
              miadvariavel = new JMenuItem("Adicionar Variavel");
              miadtarefa = new JMenuItem("Adicionar Tarefa");
              abrir = new JMenuItem("Abrir");
              guardar = new JMenuItem("Guardar");
              sair = new JMenuItem("Sair");
              sair.addActionListener(trat);
              miadvariavel.addActionListener(trat);
              miadtarefa.addActionListener(trat);
              mtabela.add(miadvariavel);
              miadvariavel.setMnemonic(KeyEvent.VK_V);
              mtabela.add(miadtarefa);
              miadtarefa.setMnemonic(KeyEvent.VK_F);
              arquivo.add(abrir);
              abrir.setMnemonic(KeyEvent.VK_B);
              arquivo.add(guardar);
              guardar.setMnemonic(KeyEvent.VK_G);
              arquivo.addSeparator();
              arquivo.add(sair);
              sair.setMnemonic(KeyEvent.VK_S);
              barra.add(arquivo);
              barra.add(mtabela);
              jTabbedPane1 = new JTabbedPane();
              contentPane = (JPanel)this.getContentPane();
              paineltabela = new JPanel();
              painelgrafo = new JPanel();
              // jTabbedPane1
              jTabbedPane1.addTab("Tabela", paineltabela);
              jTabbedPane1.addTab("Grafo", painelgrafo);
              jTabbedPane1.addChangeListener(new ChangeListener() {
                   public void stateChanged(ChangeEvent e)
                        painelvariavel.setVisible(false);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, jTabbedPane1, 11,10,990,690);
              // paineltabela
              paineltabela.setLayout(null);
              // painelgrafo
              painelgrafo.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
              // Poseidon
              this.setTitle("UMa Poseidon");
              this.setLocation(new Point(2, 1));
              this.setSize(new Dimension(558, 441));
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              this.setExtendedState(MAXIMIZED_BOTH);
         /** Add Component Without a Layout Manager (Absolute Positioning) */
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         // TODO: Add any appropriate code in the following Event Handling Methods
         private void jTabbedPane1_stateChanged(ChangeEvent e)
              System.out.println("\njTabbedPane1_stateChanged(ChangeEvent e) called.");
              // TODO: Add any handling code here
         // TODO: Add any method code to meet your needs in the following area
         private class TratBarra implements ActionListener{
              public void actionPerformed(ActionEvent e){
                   if(e.getSource() == sair){
                        int op = JOptionPane.showConfirmDialog(null, "Deseja mesmo fechar o aplicativo?","Sair", JOptionPane.YES_NO_OPTION);
                        if(op == JOptionPane.YES_OPTION){
                             System.exit(0);
                   if(e.getSource() == miadvariavel){
                        final JFrame w = new JFrame();
                        new AdVariavel(w);
                   if(e.getSource() == miadtarefa){
                        final JFrame w = new JFrame();
                        new AdTarefa(w);
    //============================= Testing ================================//
    //=                                                                    =//
    //= The following main method is just for testing this class you built.=//
    //= After testing,you may simply delete it.                            =//
    //======================================================================//
         public static void main(String[] args)
              Spash sp = new Spash(3000);
              sp.mostraTela();
              JFrame.setDefaultLookAndFeelDecorated(true);
              JDialog.setDefaultLookAndFeelDecorated(true);
              try
                   UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
              new Poseidon();
    //= End of Testing =
    private class AdVariavel extends JDialog
         // Variables declaration
         private JLabel jLabel1;
         private JTextField jTextField1;
         private JButton varOK;
         private JButton varCancel;
         private JPanel contentPane;
         private JTextField jTextField2;
         private JList listadominio;
         private JScrollPane jScrollPane1;
         private JButton varAdiciona;
         private JButton varRemove;
         private JPanel jPanel1;
         private DefaultListModel modelo1;
         // End of variables declaration
         public AdVariavel(Frame w)
              super(w);
              initializeComponent();
              // TODO: Add any constructor code after initializeComponent call
              this.setVisible(true);
          * This method is called from within the constructor to initialize the form.
          * WARNING: Do NOT modify this code. The content of this method is always regenerated
          * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
          * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
          * to retrieve your design properly in future, before revising this method.
         private void initializeComponent()
              modelo1 = new DefaultListModel();
              jLabel1 = new JLabel();
              jTextField1 = new JTextField();
              varOK = new JButton();
              varCancel = new JButton();
              contentPane = (JPanel)this.getContentPane();
              jTextField2 = new JTextField();
              listadominio = new JList(modelo1);
              jScrollPane1 = new JScrollPane();
              varAdiciona = new JButton();
              varRemove = new JButton();
              jPanel1 = new JPanel();
              // jLabel1
              jLabel1.setText("Nome da vari�vel:");
              // jTextField1
              jTextField1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jTextField1_actionPerformed(e);
              // varOK
              varOK.setText("OK");
              varOK.setMnemonic(KeyEvent.VK_O);
              varOK.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        varOK_actionPerformed(e);
              // varCancel
              varCancel.setText("Cancelar");
              varCancel.setMnemonic(KeyEvent.VK_C);
              varCancel.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        varCancel_actionPerformed(e);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, jLabel1, 12,12,105,18);
              addComponent(contentPane, jTextField1, 118,10,137,22);
              addComponent(contentPane, varOK, 170,227,83,28);
              addComponent(contentPane, varCancel, 257,227,85,28);
              addComponent(contentPane, jPanel1, 12,42,332,180);
              // jTextField2
              jTextField2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jTextField2_actionPerformed(e);
              // listadominio
              listadominio.addListSelectionListener(new ListSelectionListener() {
                   public void valueChanged(ListSelectionEvent e)
                        listadominio_valueChanged(e);
              // jScrollPane1
              jScrollPane1.setViewportView(listadominio);
              // varAdiciona
              varAdiciona.setText("Adicionar");
              varAdiciona.setMnemonic(KeyEvent.VK_A);
              varAdiciona.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        varAdiciona_actionPerformed(e);
              // varRemove
              varRemove.setText("Remover");
              varRemove.setMnemonic(KeyEvent.VK_R);
              varRemove.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        varRemove_actionPerformed(e);
              // jPanel1
              jPanel1.setLayout(null);
              jPanel1.setBorder(new TitledBorder("Dominio:"));
              addComponent(jPanel1, jTextField2, 17,22,130,22);
              addComponent(jPanel1, jScrollPane1, 165,21,154,144);
              addComponent(jPanel1, varAdiciona, 56,50,89,28);
              addComponent(jPanel1, varRemove, 57,84,88,28);
              // AdTarefas
              this.setTitle("Adicionar Variavel");
              this.setLocation(new Point(1, 0));
              this.setSize(new Dimension(367, 296));
              this.setLocationRelativeTo(null);
              this.setResizable(false);
         /** Add Component Without a Layout Manager (Absolute Positioning) */
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         // TODO: Add any appropriate code in the following Event Handling Methods
         private void jTextField1_actionPerformed(ActionEvent e)
              System.out.println("\njTextField1_actionPerformed(ActionEvent e) called.");
              // TODO: Add any handling code here
         private void varOK_actionPerformed(ActionEvent e)
              System.out.println("\nvarOK_actionPerformed(ActionEvent e) called.");
              if (jTextField1 == null){
                   return;
              if (jTextField1.getText().length()<1){
                   JOptionPane.showMessageDialog(null,"N�o introduziu nenhuma variavel","AVISO", 1 );
                   jTextField1.requestFocus();
                   return;
              else {
                   if (modelo1.getSize() == 0){
                        JOptionPane.showMessageDialog(null,"N�o introduziu nenhum dominio","AVISO", 1 );
                        return;
                   else{
                        painelvariavel.add(scrollvariavel);
                        index = 0;
                        variavel = jTextField1.getText();
                        contastring = variavel.length();
                        System.out.println(contastring);
                        DefaultTableModel dtm = (DefaultTableModel)tabelavariavel.getModel();
                        tabelavariavel.getTableHeader().setBackground(Color.yellow);
                        dtm.addColumn(variavel, new Object[]{});
                        al = modelo1.getSize();
                        totallinhas = al;
                        for(int i = 0;i < modelo1.getSize();i++){
                             listadominio.setSelectedIndex(index) ;
                             Object dominio = listadominio.getSelectedValue();
                             dtm.addRow(new Object[]{dominio});
                             index ++;
                        tabelasvar[cont] = tabelavariavel;
                        cont++;
                        System.out.println(cont);
                        for(int i=0;i<cont;i++){
                             tabelateste = tabelasvar;
                             linhas = tabelateste.getRowCount();
                             if (linhas >= tamanholinhas){
                                  tamanholinhas = linhas;
                        for (int i=0;i<cont;i++){
                             tabelateste = tabelasvar[i];
                             System.out.println(linhas);
                             linhas = tabelateste.getRowCount();
                             tabelateste.setRowHeight((tamanholinhas/linhas)*20);
                             tabelasvar[i] = tabelateste;
                             System.out.println(tabelateste);
                   tabelavariavel = new JTable();
              scrollvariavel = new JScrollPane();
              painelvariavel.add(tabelavariavel);
              tabelavariavel.setBackground(Color.cyan);
         tabelavariavel.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
                   scrollvariavel.setViewportView(tabelavariavel);
                   painelvariavel.setVisible(true);
         tabelavariavel.getTableHeader().setReorderingAllowed(false);
         this.setVisible(false);
         miadtarefa.setEnabled(true);
         miadvariavel.setEnabled(true);
         DefaultTableModel dtm = (DefaultTableModel)tabelatarefa.getModel();
                   tabelatarefa.getTableHeader().setBackground(Color.yellow);
                   controlalinhas = tamanholinhas - linhastarefa;
                   for(int i = 0;i < controlalinhas;i++){
                             dtm.addRow(new Object[]{});
                             linhastarefa++;
                   tabelatarefa.setRowHeight((tamanholinhas/linhas)*20);
              // TODO: Add any handling code here
         private void varCancel_actionPerformed(ActionEvent e)
              System.out.println("\nvarCancel_actionPerformed(ActionEvent e) called.");
              this.setVisible(false);
         private void jTextField2_actionPerformed(ActionEvent e)
              System.out.println("\njTextField2_actionPerformed(ActionEvent e) called.");
              // TODO: Add any handling code here
         private void listadominio_valueChanged(ListSelectionEvent e)
              System.out.println("\nlistadominio_valueChanged(ListSelectionEvent e) called.");
              if(!e.getValueIsAdjusting())
                   Object o = listadominio.getSelectedValue();
                   System.out.println(">>" + ((o==null)? "null" : o.toString()) + " is selected.");
                   // TODO: Add any handling code here for the particular object being selected
         private void varAdiciona_actionPerformed(ActionEvent e)
              System.out.println("\nvarAdiciona_actionPerformed(ActionEvent e) called.");
              if(jTextField2.getText().length()>=1){
                   modelo1.addElement(jTextField2.getText());
                   jTextField2.setText("");
                   jTextField2.requestFocus();
         private void varRemove_actionPerformed(ActionEvent e)
              System.out.println("\nvarRemove_actionPerformed(ActionEvent e) called.");
              int index = listadominio.getSelectedIndex();
              modelo1.remove(index);
         // TODO: Add any method code to meet your needs in the following area
    private class AdTarefa extends JDialog
         // Variables declaration
         private JLabel jLabel1;
         private JTextField jTextField1;
         private JButton tarOK;
         private JButton tarCancel;
         private JPanel contentPane;
         private JPanel jPanel1;
         // End of variables declaration
         public AdTarefa(Frame w)
              super(w);
              initializeComponent();
              // TODO: Add any constructor code after initializeComponent call
              this.setVisible(true);
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always regenerated
         * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
         * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
         * to retrieve your design properly in future, before revising this method.
         private void initializeComponent()
              jLabel1 = new JLabel();
              jTextField1 = new JTextField();
              tarOK = new JButton();
              tarCancel = new JButton();
              contentPane = (JPanel)this.getContentPane();
              // jLabel1
              jLabel1.setText("Nome da tarefa:");
              // jTextField1
              jTextField1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jTextField1_actionPerformed(e);
              // tarOK
              tarOK.setText("OK");
              tarOK.setMnemonic(KeyEvent.VK_O);
              tarOK.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        tarOK_actionPerformed(e);
              // tarCancel
              tarCancel.setText("Cancelar");
              tarCancel.setMnemonic(KeyEvent.VK_C);
              tarCancel.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        tarCancel_actionPerformed(e);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, jLabel1, 12,12,105,18);
              addComponent(contentPane, jTextField1, 118,10,120,22);
              addComponent(contentPane, tarOK, 10,50,83,28);
              addComponent(contentPane, tarCancel, 153,50,85,28);
              // AdTarefas
              this.setTitle("Adicionar Tarefa");
              this.setLocation(new Point(1, 0));
              this.setSize(new Dimension(250, 120));
              this.setLocationRelativeTo(null);
              this.setResizable(false);
         /** Add Component Without a Layout Manager (Absolute Positioning) */
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         // TODO: Add any appropriate code in the following Event Handling Methods
         private void jTextField1_actionPerformed(ActionEvent e)
              System.out.println("\njTextField1_actionPerformed(ActionEvent e) called.");
              // TODO: Add any handling code here
         private void tarOK_actionPerformed(ActionEvent e)
              System.out.println("\ntarOK_actionPerformed(ActionEvent e) called.");
              if (jTextField1 == null){
                   return;
              if (jTextField1.getText().length()<1){
                   JOptionPane.showMessageDialog(null,"N�o introduziu nenhuma tarefa","AVISO", 1 );
                   jTextField1.requestFocus();
                   return;
              else{
                   String variavel = jTextField1.getText();
                   DefaultTableModel dtm = (DefaultTableModel)tabelatarefa.getModel();
                   dtm.addColumn(variavel,new Object[]{});
                   controlalinhas = tamanholinhas - linhastarefa;
                   for(int i = 0;i < controlalinhas;i++){
                             dtm.addRow(new Object[]{});
                             linhastarefa++;
                   for(int i=0; i < tabelatarefa.getColumnCount(); i++){
                        tabelatarefa.getColumnModel().getColumn(i).setPreferredWidth(100);
                   tabelatarefa.getColumnModel().getColumn(i).setResizable(false);
                   tabelatarefa.getTableHeader().setBackground(Color.yellow);
                   tabelatarefa.setRowHeight((tamanholinhas/linhas)*20);
                   paineltarefa.setVisible(true);
         tabelatarefa.getTableHeader().setReorderingAllowed(true);
         this.setVisible(false);
         miadtarefa.setEnabled(true);
         miadvariavel.setEnabled(true);
         // TODO: Add any handling code here
         private void tarCancel_actionPerformed(ActionEvent e)
              System.out.println("\ntarCancel_actionPerformed(ActionEvent e) called.");
              this.setVisible(false);
    now the code to create the JComboBox is here:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class CaixaCombinacao extends JComboBox{
         ImageIcon[] imagens;
        String[] op = {"x", "check"};
    public CaixaCombinacao(){
         imagens = new ImageIcon[op.length];
        Integer[] intArray = new Integer[op.length];
        for (int i = 0; i < op.length; i++) {
             intArray[i] = new Integer(i);
            imagens[i] = createImageIcon("imagens/" + op[i] + ".gif");
            this.addItem(imagens);
    if (imagens[i] != null) {
    imagens[i].setDescription(op[i]);
         JComboBox lista = new JComboBox(intArray);
         ComboBoxRenderer renderer= new ComboBoxRenderer();
         lista.setRenderer(renderer);
    protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = CaixaCombinacao.class.getResource(path);
    if (imgURL != null) {
         return new ImageIcon(imgURL);
    return null;
    class ComboBoxRenderer extends JLabel
    implements ListCellRenderer {
    public ComboBoxRenderer() {
    setOpaque(true);
    setHorizontalAlignment(CENTER);
    setVerticalAlignment(CENTER);
    public Component getListCellRendererComponent(
    JList list,
    Object value,
    int index,
    boolean isSelected,
    boolean cellHasFocus) {
                   int selectedIndex = ((Integer)value).intValue();
                   if (isSelected) {
    setBackground(list.getSelectionBackground());
    setForeground(list.getSelectionForeground());
    } else {
    setBackground(list.getBackground());
    setForeground(list.getForeground());
                   ImageIcon icon = imagens[selectedIndex];
                   String opc = op[selectedIndex];
    setIcon(icon);
    return this;

    I'm sure 90% of the code posted here has nothing to do with displaying images in a JTable.
    Here is an example that shows how to display an icon in a table:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableIcon extends JFrame
         public TableIcon()
              String[] columnNames = {"Picture", "Description"};
              Object[][] data =
                   {new ImageIcon("copy16.gif"), "Copy"},
                   {new ImageIcon("add16.gif"), "Add"},
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              JTable table = new JTable( model )
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableIcon frame = new TableIcon();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }If this doesn't help then post a similiar demo program that shows the problems you are having, not your entire application.

  • I am new here (want to know some informations regarding java

    Hi all
    I am a student of information technology in Italy and unfortunatly I dont understand very well my professor of java.I want to know how I can insert the images in a Jtable ? and it would be better if someone could guide me providing source code. thanks
    cheers

    Yes, you can. What you do with a JTable is to produce a class implementing TableModel which returns a value for each cell, and that value can be a wide variety of object types including Image type.
    All the values in a column should have the same class, and the TableModel needs to supply that class.

  • How to display non-URL-based thumbnail images in JTable

    I'm trying to display thumbnail images as a tooltip popup for certain cells in a JTable. The thumbnail images are java image objects that have been retrieved dynamically as the result of a separate process--there is no associated URL. For this reason, I can't use the setToolTipText() method of the JTable.
    My attempts to JTable's createToolTip() method also failed as it seems the ToolTipManager never calls this method for a JTable.
    As a workaround, I've added a MouseMotionListener to the JTable that detects when the mouse is over the desired table cells. However, I'm not sure how to display the popup over the JTable. The only component that I can get to display over the JTable is a JPopupMenu, but I don't want to display a menu--just the image. Can anyone suggest a way to display a small popup image over the table?
    Thanks.

    Thank You Rodney. This explains why my createToolTip() method wasn't being called, but unfortunately I'm no closer to my goal of displaying a true custom tooltip using a non-URL image rather than a text string. If I make a call to setToolTipText(), at any point, the text argument becomes the tooltip and everything I have tried in createToolTip() has no effect. However, as you pointed out, if I don't call setToolTipText(), the table is not registered with the tooltip manager and createToolTip() is never even called.
    To help clarify, I have attached an SSCCE below. Please note that I use a URL image only for testing. In my actual application, the images are available only as Java objects--there are no URLs.
    import javax.swing.*;
    import java.awt.*;
    import java.net.URL;
    import java.net.MalformedURLException;
    public class Test {
        static Object[][] data = {
                {"Cell 0,0", "Cell 0,1"},
                {"Cell 1,0", "Cell 1,1"}};
        static String[] columnNames = {"Column 0", "Column 1"};
        static JFrame frame;
        static String testImageURLName = "http://l.yimg.com/k/omg/us/img/7c/0a/4009_4182164952.jpg";
        static JTable testTable = new JTable(data, columnNames) {
            public JToolTip createToolTip() {
                System.out.println("testTable.createToolTip() called");
                Image testImage = getTestImage();
                // this.setToolTipText("Table ToolTip Text");
                JLabel customTipLabel = new JLabel(new ImageIcon(testImage));
                customTipLabel.setToolTipText("Custom ToolTip Text");
                JToolTip parentTip = super.createToolTip();
                parentTip.setComponent(customTipLabel);
                return parentTip;
        // This image is loaded from a URL only for test purposes!!!
        // Ordinarily, the image object would come from the application
        // and no URL would be available.
        public static Image getTestImage() {
            try {
                URL iconURL = new URL(testImageURLName);
                ImageIcon icon = new ImageIcon(iconURL);
                return icon.getImage();
            catch (MalformedURLException ex) {
                JOptionPane.showMessageDialog(frame,
                        "Set variable \"testImageName\" to a valid file name");
                System.exit(1);
            return null;
        public static void main(String[] args) throws Exception {
            frame = new JFrame("Test Table");
            frame.setSize(300, 100);
            // Set tool tip text so that table is registered w/ tool tip manager
            testTable.setToolTipText("main tooltip");
            frame.getContentPane().add(testTable);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
    }

  • Image in header of print (JTable)

    Hello,
    I have a question about printing a JTable. I use the following code which works well but I want to extend my print with a image (a logo) in the header of every page. What is the best way to achieve this?
    My second question is how I can change the font size of the header?
    Thanks for your reply.
    Regards Stefan.
    MessageFormat header = new MessageFormat("Test");
    MessageFormat footer = new MessageFormat("Page - {0}");
    try {
        if (!myTable.print(JTable.PrintMode.FIT_WIDTH
    , header, footer, true, null, true)) {
            System.err.println("User cancelled printing");
    } catch (java.awt.print.PrinterException e) {
        System.err.format("Cannot print %s%n", e.getMessage());
    }     

    The API provided by the JTable class is described as simple, and indeed it is. To obtain more complex printing, you need to use the JTable.getPrintable method and do some extra work to get the results desired.
    There are also several third party codes you can try. Do a search on google to search what you find
    ICE

Maybe you are looking for

  • Inspection lot 04 cancellation

    Hello QM gurus ! In the material master data of my produced material, I have entered an inspection type 04. When I have done my GR on process order, inspection lot 04 has been created (status REL). Now I want to cancel this inspection lot and I don't

  • IPOD touch on external display monitor

    my ipod touch 4th generation is not working with the AV composite on external display or TV out.

  • Can't swipe between Finder pages using Magic Mouse

    I was able to do this yesterday but must have clicked something accidentally so I can no longer do this. Swipe function has been selected in magic mouse preferences. Please help.

  • Securing SOA 11g Web Services with OWSM AD authentication

    I have SOA 11g with Weblogic 10.3.5 installed and running a Web Service and a Client I want to protect with Active Directory auth and perhaps some other access rules. As I read, I can use OWSM policies to do that. Most guides I found concern OWSM 10g

  • SEM-BW 6.0 configuration guide?

    Dear all, I am running BI 7.0 for a while and just install FINBASIS 6.0 & SEM-BW 6.0 & all patches to implement SEM-CPM.   I have a SEM-CPM book and I can find some documentations to show how to build balanced scorecard online but I can NOT find conf