JTable to image?

Hi all,
I have an application that uses a JTable to display various data from our database. My problem is that I now need to display this same information via the web as an image. This is the requirement and no way around it. I didn't want to have to get into dynamically drawing everything using Java 2D, etc. So...Is there anyway that I can create the JTable from a Servlet and return the "image" in some format? I'm looking for a quick and simple approach. Any help would be greatly appreciated.
Matt

A component is not realized until you call either pack or setVisible on it.
I've modified the demo to show this. Try it first with only the top and bottom buttons (ie,without the realize gui button) and next with the bottom two.
Although the table will have a preferred size the component that will paint itself into the new BufferedImage does not yet exist so requests (in the saveComponentAsImage method) for its width and height return zero.
If you replace the saveComponentAsImage method calls getWidth and getHeight with getPreferredSize().width and getPreferredSize().height you get a blank image, nobody home.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class TableToImage
    public static void main(String[] args)
        final JButton
            tableButton = new JButton("make table"),
            guiButton   = new JButton("realize gui"),
            saveButton  = new JButton("save");
        ActionListener l = new ActionListener()
            JTable table;
            public void actionPerformed(ActionEvent e)
                JButton button = (JButton)e.getSource();
                if(button == tableButton)
                    table = makeTable();
                if(button == guiButton)
                    realizeGUI(table);
                if(button == saveButton)
                    Dimension
                        size = table.getSize(),
                        preferredSize = table.getPreferredSize();
                    if(size.width == 0 || size.height == 0)
                        System.out.println("actual size: width = " + size.width + "\t" +
                                           "height = " + size.height + "\n" +
                                           "preferredSize: width = " +
                                            preferredSize.width + "\t" +
                                           "height = " + preferredSize.height);
                        return;             // avoid IllegalArgumentException
                    saveComponentAsImage(table);
        tableButton.addActionListener(l);
        guiButton.addActionListener(l);
        saveButton.addActionListener(l);
        JPanel northPanel = new JPanel();
        northPanel.add(tableButton);
        JPanel panel = new JPanel();
        panel.add(guiButton);
        JPanel southPanel = new JPanel();
        southPanel.add(saveButton);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(northPanel, "North");
        f.getContentPane().add(panel);
        f.getContentPane().add(southPanel, "South");
        f.setSize(200,140);
        f.setLocation(200,200);
        f.setVisible(true);
    private static JTable makeTable()
        int rows = 24, columns = 5;
        String[] headers = new String[columns];
        for(int i = 0; i < headers.length; i++)
            headers[i] = "header " + (i + 1);
        String[][] data = new String[rows][columns];
        for(int i = 0; i < rows; i++)
            for(int j = 0; j < columns; j++)
                data[i][j] = "item " + (i*columns + j + 1);
        JTable table = new JTable(data, headers);
        return table;
    private static void realizeGUI(JTable table)
        JFrame f = new JFrame();
        f.getContentPane().add(table);
        f.pack();
        f.dispose();
    private static void saveComponentAsImage(Component c)
        int w = c.getWidth();
        int h = c.getHeight();
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        c.paint(g2);
        g2.dispose();
        try
            ImageIO.write(image, "png", new File("tableImage.png"));
        catch(IOException ioe)
            System.out.println(ioe.getMessage());
}

Similar Messages

  • How to print JTable to image file?

    Hi ppl.
    I have JTable that i can print via Printable to printer very well.
    Now I have a task to pass this JTable to MS Word. I can pass to MS Word any image file. So all I need is to "print" my JTable to image. Is it possible to reroute printing process to image file?
    Or any other ideas how to sovle a problem?

    John Bo wrote:
    Hi ppl.That words is 'people'. By leaving out three letters, you do not appear cool, just lazy & foolish.
    I have JTable that i can print via Printable to printer very well.
    Now I have a task to pass this JTable to MS Word. I can pass to MS Word any image file. So all I need is to "print" my JTable to image. Is it possible to reroute printing process to image file?Create a <tt>BufferedImage</tt> the same size as the <tt>JTable</tt>. Call <tt>createGraphics()</tt> on the <tt>BufferedImage</tt>. Pass the <tt>Graphics</tt> object to <tt>JTable.painComponent(Graphics)</tt>. Create an image of the <tt>BufferedImage</tt> by calling <tt>ImageIO.write()</tt>.

  • Help needed on convert JTable to Image

    Hi, all
    I have made an application that can output a JTable with different colours in its every cells. Now I want to select the whole Table and put it as an Image to one of the Image Viewer Softwares(e.g. windows picture viewer).
    Is there anyone knows how to do that?
    Thanks in advance!
    Regards,
    swat.

    Now I want to select the whole Table and put it as an
    Image to one of the Image Viewer Softwares(e.g.
    windows picture viewer). If you don't have to do it programmatically, and you are working on windows, select the window with the table, Alt-PrtScr will copy just that window into the clipboard, and you can paste it into many different apps, including image views, word, so on.

  • Transform JTable in Image

    Hi,
    How can I tranform a JTable to a Image?Is it possible?
    I want to draw it in a PDF file

    you could make an image out of it by using the robot class like:
    import com.sun.image.codec.jpeg.*;
    public class ScreenCapture
    final BufferedImage screenShot;
    //  Method used to snap the shot
    public ScreenCapture()throws Exception{
    Robot robot = new Robot();
    final String tessst  = "test.jpg";
    screenShot = robot.createScreenCapture(new Rectangle(frame.x, frame.y, 359, 272));     
    saveImageAsJPEG(screenShot,10000000,tessst);
    //  Method used to save the image as a jpg file
    public static void saveImageAsJPEG(BufferedImage bi, float quality, String filename)
    try {      
      ByteArrayOutputStream boutstream = new ByteArrayOutputStream();   
      JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(boutstream);  
      JPEGEncodeParam enparam = JPEGCodec.getDefaultJPEGEncodeParam(bi); 
      enparam.setQuality(quality, true);  
      enc.encode(bi, enparam);
      FileOutputStream fimage = new FileOutputStream(new File(filename));
      boutstream.writeTo(fimage); 
      fimage.close();
      catch (Exception e) {
      System.out.println(e); }
    }

  • ComboBoxRenderer on JTable - incorrect image when pressed again

    I have a JTable with a combobox (with images) the user can select an image from a dropdown box. the renderer I'm using (and I guess this is where I'm wrong) is this:
    import java.awt.Component;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.ListCellRenderer;
    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)
            if (isSelected)
               setBackground(list.getSelectionBackground());
               setForeground(list.getSelectionForeground());
            else
               setBackground(list.getBackground());
               setForeground(list.getForeground());
            ImageIcon icon = (ImageIcon)value;
            try{
                 setText(icon.getDescription());             
            }catch(Exception e)
                 setText(""); //null
            setIcon(icon);
            return this;
    }The problem is this:
    I have 3 images (1,2,3). Say the user choose image 1 for row 1, image 2 for row 2...image 3 for row 3.
    If he wants to make a correction in row 1 (and change it to image 3) once he clicks the dropdown box he gets image 3 (?!) this is the last image he pressed. In other words, instead of getting the image he alrady pressed, he gets the last image he chose on the dropdown box.
    Any idea?

    No idea what you are talking about. Your question is about a JTable, but you code is about a JList.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.
    I suggest you also start responding to previous questions berfore posting new questions.

  • JTable with Images

    Hi,
    I have created a Table in which each cell is displayed with Images.I am not able to select a cell. Is it possible to select an Image in a cell?
    Please give me a suggestion.
    Regards
    senthil

    Since you know how to display the images, I take it that you have developped a custom TableCellRenderer.
    Pretty sure that you are able to select the cell as usual - just check the table.isSelected(...) - most probably the problem is that you don't see it ;-)I completely agree with the queen of Aegypt on the likely cause of your problem, except she probably meant you should check the value of the boolean isSelected argument that is passed to your renderer's getTableCellRendererComponent(...) method, and render the image differently if it is true.

  • Inserting Pics in a JTable

    I'd like to include an ID of the person within my table.
    Using DefaultTableModel and ImageIcon, how can I insert a picture?
    Is it even possible to enter a non-textual entry into a JTable?
    Here's what I did:
    JMenuItem insertPicture;
    JTable contactTable;
    DefaultTableModel details;
    else if(ae.getSource() == insertPicture)
      // Column and row details
      int row = contactTable.getSelectedRow();
      int column = contactTable.getSelectedColumn();
      // Using a string to store the picture's location details
      String fileName;
      FileDialog location = new FileDialog(ContactDetails.this,   
                "Choose picture", FileDialog.LOAD);
      // Displaying the FileDialog
      location.show();
      // Getting the image and inserting it in the JTable
      ImageIcon image = new ImageIcon(location.getDirectory()+
      location.getFile());
      details.setValueAt(image, row, column);
    }My problem is that within the row (to which the picture should be placed), I'm getting only the String description of the image's location. How can I correct this?
    Much thanks in advance!
    Reformer!

    import java.awt.*;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test {
        public static void main(String[] args) throws MalformedURLException {
            DefaultTableModel model = new DefaultTableModel(new String[]{"path","image"}, 0) {
                public Class getColumnClass(int columnIndex) {
                    return columnIndex==1? Icon.class : String.class;
                public boolean isCellEditable(int rowIndex, int columnIndex){
                    return false;
            URL[] urls = {
                new URL("http://today.java.net/jag/bio/JagHeadshot-small.jpg"),
                new URL("http://today.java.net/jag/bio/JAG2001small.jpg"),
                new URL("http://blogs.sun.com/roller/resources/jag/2005_09_14_03-44-21-438_n1.small.png")
            for(int i=0; i<urls.length; ++i)
                model.addRow(new Object[]{urls.toString(), new ImageIcon(urls[i])});
    JTable table = new JTable(model);
    table.setRowHeight(240);
    JScrollPane sp = new JScrollPane(table);
    sp.setPreferredSize(new Dimension(600,450));
    final JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(sp);
    f.pack();
    SwingUtilities.invokeLater(new Runnable(){
    public void run() {
    f.setLocationRelativeTo(null);
    f.setVisible(true);

  • JTable Custom Cell  Event handling

    Hi,
    I have a column in JTable as image which is rendered by using custom cell renderer. I want to handle action event for the cell...
    I tried adding actionPerformed event for the button using which the image is rendered but the event is not triggered....
    Can you please tell me how to proceed with this
    Thanks,
    S.Anand

    I'm assuming you want to know when the user has clicked on a particular cell in the table. If so, add a MouseListener to the table then implement a MouseListener or one of the Mouse...Adapter classes with the method:
    public void mouseClicked(MouseEvent e)
        Point p = e.getPoint();
        int row = table.rowAtPoint(p);
        int col = table.columnAtPoint(p);
        // now do something according to the cell that was clicked

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

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

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

  • 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

  • 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.

  • 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

  • Installed the Mac update, checked for faulty fonts, and ran the Font Test Script. PS still crashes

    Hi guys, Ive done everything suggested and my PS is still crashing. I will attatch my crash report to see if it helps with anything. I used Font Doctor and Font Book to check for bad fonts and removed the two that came up. Tried again and still nothi

  • Macbook Pro Trackpad wrongly left clicks

    When I click on the bottom right part of my trackpad it will left click instead of doing a normal right click.  I think it has something to do with the fact that that part of the trackpad is used the most. It does not do this on any other part of the

  • Open e-mail attachment

    I just recieved an e-mail with an mp4 video attached and it says that it is an "unsupported attachment". From what I understand the playbook should be able to open mp4s. Do I need an app for it or something? Thanks,

  • E-mailed attached images from I-photo are always highly compressed

    When I attach an image (e.g. 2.5mb) to an e-mail then send it, the recipient finds it has been reduced to approx 50kb and is pixellated. How can I avoid this happening.

  • TreeCellEditor with Checkbox

    hi i'm tryin to create a treecelleditor to check or uncheck my treenode. it works fine at all, but i want to activate the editor only then, when the user clicks into a specific region (the region where the checkbox is). i've tried this like following