1

How to add an image to a custom JTable row button, I have a JTable with a JButton in the fourth column and I want to put an image into fifth column using that button "Upload".

**Note: Button working as a file uploader.

Here is my image

Image

Here is the code :

NewFrame.java

package test4;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.filechooser.FileSystemView;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;


public class NewJFrame extends javax.swing.JFrame {


    public NewJFrame() {
        initComponents();
        tablemodel();
    }
void tablemodel(){
    Color choices[] = { Color.red, Color.yellow, Color.green, Color.white, Color.orange };
    ComboTableCellRenderer renderer = new ComboTableCellRenderer();
    JComboBox comboBox = new JComboBox(choices);
    comboBox.setRenderer(renderer);

    TableCellEditor editor = new DefaultCellEditor(comboBox);

    TableModel model = new ColorTableModel();
    jTable1.setModel(model);
    TableColumn column = jTable1.getColumnModel().getColumn(5);
    column.setCellRenderer(renderer);
    column.setCellEditor(editor);
    TableColumn column1 = jTable1.getColumnModel().getColumn(3);
    column1.setCellRenderer(new ButtonRenderer());
     column1.setCellEditor(
        new ButtonEditor(new JCheckBox()));
jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
jTable1.getColumnModel().getColumn(0).setPreferredWidth(27);
jTable1.getColumnModel().getColumn(1).setPreferredWidth(120);
jTable1.getColumnModel().getColumn(2).setPreferredWidth(100);
jTable1.getColumnModel().getColumn(3).setPreferredWidth(90);
jTable1.getColumnModel().getColumn(4).setPreferredWidth(90);

}
    /** 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 Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4", "Title 5", "Title 6"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(25, 160, 730, 275));

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-795)/2, (screenSize.height-651)/2, 795, 651);
    }// </editor-fold>

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration

}
class ButtonRenderer extends JButton implements TableCellRenderer {

  public ButtonRenderer() {
    setOpaque(true);

  }

  public Component getTableCellRendererComponent(JTable table, Object value,
      boolean isSelected, boolean hasFocus, int row, int column) {
      value="Upload";

      if (isSelected) {
      setForeground(table.getSelectionForeground());
      setBackground(table.getSelectionBackground());
    } else {
      setForeground(table.getForeground());
      setBackground(UIManager.getColor("Button.background"));
     // setText("dsda1");
    }
    setText((value == null) ? "" : value.toString());
    return this;
  }
}

/**
 * @version 1.0 11/09/98
 */

class ButtonEditor extends DefaultCellEditor {
  protected JButton button;

  private String label;

  private boolean isPushed;

  public ButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    button = new JButton();
  //  button.setText("dsda2");
    button.setOpaque(true);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        fireEditingStopped();
      }
    });
  }

  public Component getTableCellEditorComponent(JTable table, Object value,
      boolean isSelected, int row, int column) {

    if (isSelected) {
      button.setForeground(table.getSelectionForeground());
      button.setBackground(table.getSelectionBackground());


    } else {
      button.setForeground(table.getForeground());
      button.setBackground(table.getBackground());

    }
   label = (value == null) ? "" : value.toString();
    //label="DDD";
    button.setText("Upload");

    isPushed = true;
    return button;
  }

  public Object getCellEditorValue() {
    if (isPushed) {
      //
      JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());

        int returnValue = jfc.showOpenDialog(null);
        // int returnValue = jfc.showSaveDialog(null);

        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File selectedFile = jfc.getSelectedFile();
            System.out.println(selectedFile.getAbsolutePath());
        }

    //  JOptionPane.showMessageDialog(button, label + ": Ouch!");
       System.out.println(label + "Uploaded Successfully!!");
    }
    isPushed = false;
    return new String(label);
  }

  public boolean stopCellEditing() {
    isPushed = false;
    return super.stopCellEditing();
  }

  protected void fireEditingStopped() {
    super.fireEditingStopped();
  }
}

ComboTableCellRenderer.java

package test4;


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;

import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

class ComboTableCellRenderer implements ListCellRenderer, TableCellRenderer {
  DefaultListCellRenderer listRenderer = new DefaultListCellRenderer();

  DefaultTableCellRenderer tableRenderer = new DefaultTableCellRenderer();

  private void configureRenderer(JLabel renderer, Object value) {
    if ((value != null) && (value instanceof Color)) {
      if (value.equals(Color.red)) {
            renderer.setText("0");
        } else if(value.equals(Color.orange)) {
            renderer.setText("10");
        }
      else if(value.equals(Color.yellow)) {
            renderer.setText("20");
        }
      else if(value.equals(Color.green)) {
            renderer.setText("30");
        }
      else if(value.equals(Color.white)) {
            renderer.setText("N/A");
        }
      renderer.setBackground((Color)value);
    } else {
      renderer.setText((String) value);
    }
  }

  public Component getListCellRendererComponent(JList list, Object value, int index,
      boolean isSelected, boolean cellHasFocus) {
    listRenderer = (DefaultListCellRenderer) listRenderer.getListCellRendererComponent(list, value,
        index, isSelected, cellHasFocus);
    configureRenderer(listRenderer, value);
    return listRenderer;
  }

  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
      boolean hasFocus, int row, int column) {
    tableRenderer = (DefaultTableCellRenderer) tableRenderer.getTableCellRendererComponent(table,
        value, isSelected, hasFocus, row, column);
    configureRenderer(tableRenderer, value);
    return tableRenderer;
  }
}

class ColorTableModel extends AbstractTableModel {

  Object rowData[][] = {
      { "1","","","","", Color.red, "30" },
      { "2","","","","", Color.red, "30" },
      { "3","","","","", Color.red, "30" },
      { "4","","","","", Color.red, "30" },
      { "5","","","","", Color.red, "30" }, };

  String columnNames[] = { "Index","Item","Reason","Image","Image 1","Marks","Allocated Marks" };

  public int getColumnCount() {
    return columnNames.length;
  }

  public String getColumnName(int column) {
    return columnNames[column];
  }

  public int getRowCount() {
    return rowData.length;
  }

  public Object getValueAt(int row, int column) {
    return rowData[row][column];
  }

  public Class getColumnClass(int column) {
    return (getValueAt(0, column).getClass());
  }

  public void setValueAt(Object value, int row, int column) {
    rowData[row][column] = value;
  }

  public boolean isCellEditable(int row, int column) {
    return (column != 0);
  }
}
1
  • The easiest way is to put a JLabel into the 5th column, and then add the image to the JLabel when the upload button is clicked. Commented Aug 1, 2018 at 3:55

1 Answer 1

0

Finally, I found the answer.

PS : Full code typed in a one class.

This is the output image; enter image description here

This is the code:

Table.java

package test5;

import com.toedter.calendar.JDateChooser;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractCellEditor;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.filechooser.FileSystemView;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

/**
 *
 * @author Praneeth Thisal
 */
public class Table extends JFrame

{
    static javax.swing.JScrollPane jScrollPane1;
  static javax.swing.JTable jTable1;
    static String orijinalpath="C:\\Users\\Praneeth Thisal\\Pictures\\JavaImages\\";
static String source;
static JFrame frame = new JFrame("Test");
    public Table() {
        Table1();
        tablemodel();
        loadframe();
    }

    void loadframe(){


    }
     void Table1()
    {
       jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(null);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                { "1","","","","", Color.red, "30" },
      { "2","","","","", Color.red, "30" },
      { "3","","","","", Color.red, "30" },
      { "4","","","","", Color.red, "30" },
      { "5","","","","", Color.red, "30" },
      { "6","","","","", Color.red, "30" },
      { "7","","","","", Color.red, "30" },
            },
            new String [] {
                "Index","Item","Reason","Image","Image 1","Marks","Allocated Marks"
            }
        ));
        jScrollPane1.setViewportView(jTable1);
        jTable1.setRowHeight(80);

        getContentPane().add(jScrollPane1);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-795)/2, (screenSize.height-651)/2, 795, 651);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JScrollPane(jTable1), BorderLayout.CENTER);
        //frame.add(toolBar, BorderLayout.NORTH);
        frame.pack();
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.setVisible(true);
            }
        });


    }
void tablemodel(){
 Color choices[] = { Color.red, Color.yellow, Color.green, Color.white, Color.orange };
    ComboTableCellRenderer renderer = new ComboTableCellRenderer();
    JComboBox comboBox = new JComboBox(choices);
    comboBox.setRenderer(renderer);

    TableCellEditor editor = new DefaultCellEditor(comboBox);

//    TableModel model = new DefaultTableModel();
//    jTable1.getModel(model);
    TableColumn column = jTable1.getColumnModel().getColumn(5);
    column.setCellRenderer(renderer);
    column.setCellEditor(editor);
    TableColumn column1 = jTable1.getColumnModel().getColumn(3);
    column1.setCellRenderer(new ButtonRenderer());
//    TableColumn column2 = jTable1.getColumnModel().getColumn(4);
//    column2.setCellRenderer(new ImageRenderer());


     column1.setCellEditor(
        new ButtonEditor(new JCheckBox()));
jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
jTable1.getColumnModel().getColumn(0).setPreferredWidth(27);
jTable1.getColumnModel().getColumn(1).setPreferredWidth(120);
jTable1.getColumnModel().getColumn(2).setPreferredWidth(100);
jTable1.getColumnModel().getColumn(3).setPreferredWidth(90);
jTable1.getColumnModel().getColumn(4).setPreferredWidth(90);



}
    class ComboTableCellRenderer implements ListCellRenderer, TableCellRenderer {
  DefaultListCellRenderer listRenderer = new DefaultListCellRenderer();

  DefaultTableCellRenderer tableRenderer = new DefaultTableCellRenderer();

  private void configureRenderer(JLabel renderer, Object value) {
    if ((value != null) && (value instanceof Color)) {
      if (value.equals(Color.red)) {
            renderer.setText("0");
        } else if(value.equals(Color.orange)) {
            renderer.setText("10");
        }
      else if(value.equals(Color.yellow)) {
            renderer.setText("20");
        }
      else if(value.equals(Color.green)) {
            renderer.setText("30");
        }
      else if(value.equals(Color.white)) {
            renderer.setText("N/A");
        }
      renderer.setBackground((Color)value);
    } else {
//     renderer.setText((String) value);
    }
  }

  public Component getListCellRendererComponent(JList list, Object value, int index,
      boolean isSelected, boolean cellHasFocus) {
    listRenderer = (DefaultListCellRenderer) listRenderer.getListCellRendererComponent(list, value,
        index, isSelected, cellHasFocus);
    configureRenderer(listRenderer, value);
    return listRenderer;
  }

  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
      boolean hasFocus, int row, int column) {
    tableRenderer = (DefaultTableCellRenderer) tableRenderer.getTableCellRendererComponent(table,
        value, isSelected, hasFocus, row, column);
    configureRenderer(tableRenderer, value);
    return tableRenderer;
  }
}
//    class ImageRenderer extends DefaultTableCellRenderer  {
//  JLabel lbl = new JLabel();
//int row=jTable1.getSelectedRow();
//  ImageIcon icon = new ImageIcon(new ImageIcon(Table.orijinalpath+row+" Test.jpg").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
//
//  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
//      boolean hasFocus, int row, int column) {
////    lbl.setText((String) value);
//    lbl.setIcon(icon);
//    return lbl;
//  }
//}

class ButtonRenderer extends JButton implements TableCellRenderer {

  public ButtonRenderer() {
    setOpaque(true);

  }

  public Component getTableCellRendererComponent(JTable table, Object value,
      boolean isSelected, boolean hasFocus, int row, int column) {
      value="Upload";

      if (isSelected) {
      setForeground(table.getSelectionForeground());
      setBackground(table.getSelectionBackground());
    } else {
      setForeground(table.getForeground());
      setBackground(UIManager.getColor("Button.background"));
     // setText("dsda1");
    }
    setText((value == null) ? "" : value.toString());
    return this;
  }
}

/**
 * @version 1.0 11/09/98
 */

class ButtonEditor extends DefaultCellEditor {
  protected JButton button;

  private String label;

  private boolean isPushed;

  public ButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    button = new JButton();
    button.setOpaque(true);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        fireEditingStopped();
      }
    });
  }

  public Component getTableCellEditorComponent(JTable table, Object value,
      boolean isSelected, int row, int column) {

    if (isSelected) {
      button.setForeground(table.getSelectionForeground());
      button.setBackground(table.getSelectionBackground());


    } else {
      button.setForeground(table.getForeground());
      button.setBackground(table.getBackground());

    }
   label = (value == null) ? "" : value.toString();
    //label="DDD";
    button.setText("Upload");

    isPushed = true;
    return button;
  }

  public Object getCellEditorValue() {

    if (isPushed) {
      //
      JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());

        int returnValue = jfc.showOpenDialog(null);
        // int returnValue = jfc.showSaveDialog(null);

        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File selectedFile = jfc.getSelectedFile();
            System.out.println(selectedFile.getAbsolutePath());
                        Table.source=selectedFile.getAbsolutePath();
        }

    //  JOptionPane.showMessageDialog(button, label + ": Ouch!");
       System.out.println(label + "Uploaded Successfully!!");
    }
int row=jTable1.getSelectedRow();
     InputStream is = null;
    OutputStream os = null;
    try {
        String dest=Table.orijinalpath+row+" Test.jpg";
        is = new FileInputStream(Table.source);
        os = new FileOutputStream(dest);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
    }   catch (IOException ex) {
            Logger.getLogger(ButtonEditor.class.getName()).log(Level.SEVERE, null, ex);
        }   finally {
            try {
                is.close();
                os.close();
            } catch (IOException ex) {
                Logger.getLogger(ButtonEditor.class.getName()).log(Level.SEVERE, null, ex);
            }
    }
       // Table nf = new Table();
    //nf.setVisible(true);

//    TableColumn column2 = jTable1.getColumnModel().getColumn(4);
//    column2.setCellRenderer(new ImageRenderer());
int j = jTable1.getRowCount();
int k=jTable1.getSelectedRow();
             ImageIcon icon = new ImageIcon(Table.orijinalpath+row+" Test.jpg");
            jTable1.getColumnModel().getColumn(4).setCellRenderer(new ImageRenderer());
            DefaultTableModel Tmodel=(DefaultTableModel) jTable1.getModel();
            jTable1.setRowHeight(80);
            Tmodel.setValueAt(icon, k, 4);



    for(int i=0;i<j;i++){
    jTable1.setColumnSelectionInterval(4, i);
      }


    isPushed = false;
    return new String(label);



  }

  public boolean stopCellEditing() {
    isPushed = false;
    return super.stopCellEditing();
  }

  protected void fireEditingStopped() {
    super.fireEditingStopped();
  }


    }
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {

                new Table();
            }
        });
    }
}

        class ImageRenderer extends DefaultTableCellRenderer {
          JLabel lbl = new JLabel();
          public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              ImageIcon icon = new ImageIcon(new ImageIcon(value.toString()).getImage().getScaledInstance(80, 60, Image.SCALE_DEFAULT));

             // System.out.println(value);
               lbl.setIcon(icon);
            return lbl;
          }
        }

Hope you all help this. Thank you!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.