JTable with JComboBox

Hi friends,
I am adding JComboBox in JTable its working properly
But data is not adding dynamically to JComboBox
I am Sending my Code plz give me reply
I am Struggleing from 1 week on wards
package com.dnt.autopopulation;
import javax.swing.*;
import java.awt.*;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import java.awt.event.*;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.event.TableModelEvent;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.text.SimpleDateFormat;
import java.util.Vector;
import javax.swing.border.*;
import com.dnt.eaip.Connectmagr;
import com.dnt.eaip.*;
import com.dnt.util.*;
import javax.swing.plaf.ButtonUI;
import com.dnt.admin.EndStartDateCheck;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
public class AutoPopRollBack extends JPanel {
boolean selection = false;
public static final int HAND_CURSOR = 12;
Cursor cursor = new Cursor(HAND_CURSOR);
int selectedRow = -1;
ImageIcon headertop1 = new ImageIcon("./images/k2topbar.gif");
JLabel HeaderLabe = new JLabel(headertop1);
Border border1 = new EtchedBorder(EtchedBorder.RAISED, Color.white, Color.blue);
Border border2 = BorderFactory.createBevelBorder(BevelBorder.RAISED,
new Color(154, 254, 211), new Color(108, 178, 148),
new Color(37, 60, 50), new Color(53, 87, 72));
DefaultTableModel dm = new DefaultTableModel();
Vector searchlist = new Vector();
Vector rows = new Vector();
Vector returnList;
Connectmagr objConnectmagr = new Connectmagr();
JFrame frame = new JFrame();
JLabel headlab = new JLabel();
JCalendarComboBox EndDateTxt;
JLabel HawbLab = new JLabel();
JTextField HawbTxt = new JTextField();
JLabel AgentLab = new JLabel();
JLabel StartDateLab = new JLabel();
JCalendarComboBox StartDateTxt;
JComboBox AgentLBox = new JComboBox();
JLabel EnddateLab = new JLabel();
JPanel ReviewJobsPane = new JPanel();
JButton SearchBtn = new JButton();
ButtonUI ui = new com.sun.java.swing.plaf.motif.MotifButtonUI();
ArrayList AgentList = new ArrayList();
JComboBox DocTypeLBox = new JComboBox();
JLabel doctypelab = new JLabel();
JPanel displayPanel = new JPanel();
ButtonGroup group1;
JRadioButton rb;
JTable table;
public ArrayList jobList = new ArrayList();
public AutoPopRollBack(JFrame frame, ArrayList agentArrayList) {
this.frame = frame;
this.AgentList = agentArrayList;
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
public void jbInit() throws Exception {
Calendar cal = Calendar.getInstance();
Locale loc = new Locale("");
SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");
EndDateTxt = new JCalendarComboBox(cal, loc, dateformat);
StartDateTxt = new JCalendarComboBox(cal, loc, dateformat);
HeaderLabe.setBackground(new Color(250, 233, 216));
HeaderLabe.setBounds(new Rectangle(0, 0, 830, 33));
this.setLayout(null);
this.setBackground(SystemColor.control);
headlab.setBackground(new Color(250, 233, 216));
headlab.setFont(new java.awt.Font("Verdana", 1, 12));
headlab.setForeground(Color.blue);
headlab.setHorizontalAlignment(SwingConstants.CENTER);
headlab.setText(" :: Auto Population Rollback");
headlab.setBounds(new Rectangle(39, 2, 247, 25));
EndDateTxt.setBounds(new Rectangle(474, 36, 116, 18));
EndDateTxt.setBackground(Color.white);
EndDateTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
EndDateTxt.setForeground(Color.blue);
EndDateTxt.setBorder(null);
HawbLab.setFont(new java.awt.Font("Dialog", 0, 13));
HawbLab.setForeground(Color.blue);
HawbLab.setHorizontalAlignment(SwingConstants.RIGHT);
HawbLab.setText("Job No/Airway Bill No:");
HawbLab.setBounds(new Rectangle(326, 14, 146, 18));
HawbTxt.setBounds(new Rectangle(474, 14, 125, 18));
HawbTxt.setText("");
HawbTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
HawbTxt.setForeground(Color.blue);
HawbTxt.setBorder(border1);
AgentLab.setFont(new java.awt.Font("Dialog", 0, 13));
AgentLab.setForeground(Color.blue);
AgentLab.setHorizontalAlignment(SwingConstants.RIGHT);
AgentLab.setText("<html>Agent:<font size=\'4\' color=\"#993333\">*</font></html>");
AgentLab.setBounds(new Rectangle(31, 14, 97, 18));
StartDateLab.setFont(new java.awt.Font("Dialog", 0, 13));
StartDateLab.setForeground(Color.blue);
StartDateLab.setHorizontalAlignment(SwingConstants.RIGHT);
StartDateLab.setText("Start Date:");
StartDateLab.setBounds(new Rectangle(23, 36, 105, 18));
StartDateTxt.setBounds(new Rectangle(129, 36, 116, 18));
StartDateTxt.setBackground(Color.white);
StartDateTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
StartDateTxt.setForeground(Color.blue);
StartDateTxt.setBorder(null);
AgentLBox.setBackground(Color.white);
AgentLBox.setFont(new java.awt.Font("Verdana", 0, 13));
AgentLBox.setForeground(Color.blue);
AgentLBox.setBounds(new Rectangle(129, 14, 178, 18));
AgentLBox.setFont(new java.awt.Font("Times New Roman", 1, 10));
EnddateLab.setFont(new java.awt.Font("Dialog", 0, 13));
EnddateLab.setForeground(Color.blue);
EnddateLab.setHorizontalAlignment(SwingConstants.RIGHT);
EnddateLab.setText("End Date:");
EnddateLab.setBounds(new Rectangle(391, 36, 81, 18));
ReviewJobsPane.setBackground(new Color(240, 233, 216));
ReviewJobsPane.setBorder(BorderFactory.createLineBorder(Color.black));
ReviewJobsPane.setBounds(new Rectangle(69, 47, 705, 96));
ReviewJobsPane.setLayout(null);
SearchBtn.setUI(ui);
SearchBtn.setCursor(cursor);
SearchBtn.setBackground(new Color(76, 125, 104));
SearchBtn.setBounds(new Rectangle(377, 153, 89, 19));
SearchBtn.setFont(new java.awt.Font("Tahoma", 1, 10));
SearchBtn.setForeground(Color.white);
SearchBtn.setBorder(border2);
SearchBtn.setOpaque(true);
SearchBtn.setFocusPainted(false);
SearchBtn.setText("Search");
SearchBtn.addActionListener(new AutoPopRollBack_SearchBtn_actionAdapter(this));
for (int i = 0; i < AgentList.size(); i++)
AgentLBox.addItem( (String) AgentList.get(i));
DocTypeLBox.setFont(new java.awt.Font("Verdana", 0, 13));
DocTypeLBox.setForeground(Color.blue);
DocTypeLBox.setMinimumSize(new Dimension(22, 19));
DocTypeLBox.setBounds(new Rectangle(129, 58, 179, 18));
DocTypeLBox.setFont(new java.awt.Font("Times New Roman", 1, 10));
DocTypeLBox.addItem("New Jobs");
DocTypeLBox.addItem("Draft jobs");
DocTypeLBox.addItem("Finished jobs");
doctypelab.setBounds(new Rectangle(7, 58, 121, 18));
doctypelab.setText("<html>Document Type:<font size=\'4\' color=\"#993333\">*</font></html>");
doctypelab.setHorizontalAlignment(SwingConstants.RIGHT);
doctypelab.setForeground(Color.blue);
doctypelab.setFont(new java.awt.Font("Dialog", 0, 13));
displayPanel.setBorder(BorderFactory.createLineBorder(Color.black));
displayPanel.setBounds(new Rectangle(69, 182, 705, 315));
this.add(headlab, null);
this.add(HeaderLabe, null);
this.add(ReviewJobsPane, null);
ReviewJobsPane.add(HawbLab, null);
ReviewJobsPane.add(AgentLab, null);
ReviewJobsPane.add(AgentLBox, null);
ReviewJobsPane.add(StartDateLab, null);
ReviewJobsPane.add(StartDateTxt, null);
ReviewJobsPane.add(HawbTxt, null);
ReviewJobsPane.add(EnddateLab, null);
ReviewJobsPane.add(EndDateTxt, null);
ReviewJobsPane.add(DocTypeLBox, null);
ReviewJobsPane.add(doctypelab, null);
this.add(SearchBtn, null);
this.add(displayPanel, null);
//this.add(scrollPaneView, null);
// scrollPaneView.getViewport().add(displayPanel, null);
this.setVisible(true);
void FieldEditable(boolean str) {
StartDateTxt.setEnabled(str);
EndDateTxt.setEnabled(str);
public static void main(String args[]) {
JFrame frame = new JFrame();
ArrayList agentlist = new ArrayList();
agentlist.add(0, "BF0651");
agentlist.add(1, "PF0010");
AutoPopRollBack objAutoPopRollBack = new AutoPopRollBack(frame, agentlist);
frame.getContentPane().add(objAutoPopRollBack);
frame.setBounds(new Rectangle(0, 0, 820, 593));
frame.setVisible(true);
void SearchBtn_actionPerformed(ActionEvent e) {
displayPanel.setVisible(false);
Vector data=new Vector();
rows.removeAllElements();
boolean flag = true;
String che = new EndStartDateCheck().crossCheck(StartDateTxt.getCalendar(), EndDateTxt.getCalendar());
try {
if(HawbTxt.getText().equalsIgnoreCase("")){
if (StartDateTxt._spinner.getText().equalsIgnoreCase("")) {
JOptionPane.showMessageDialog(this, "Please Select Start Date",
"Warning", JOptionPane.WARNING_MESSAGE);
flag = false;
else if (!che.equalsIgnoreCase("")) {
JOptionPane.showMessageDialog(frame, che, "Message Window", JOptionPane.INFORMATION_MESSAGE);
flag = false;
}else{
FieldEditable(true);
if (flag) {
try {
displayPanel.removeAll();
} catch (Exception ex) {
rows.removeAllElements();
data.removeAllElements();
SearchBtn.setEnabled(true);
searchlist.add(0, AgentLBox.getSelectedItem().toString().trim());
if (!HawbTxt.getText().trim().equalsIgnoreCase(""))
searchlist.add(1, HawbTxt.getText().toString().trim());
else
searchlist.add(1, "");
searchlist.add(2, new Integer(DocTypeLBox.getSelectedIndex() + 1));
String startDate = new ConvertDate().convertddMM_To_MMdd(StartDateTxt._spinner.getText());
String endDate = new ConvertDate().convertddMM_To_MMdd(EndDateTxt._spinner.getText());
Vector columns = new Vector();
columns.add(0, "");
columns.add(1, "JOB No");
columns.add(2, "Status");
columns.add(3, "Current Form Type");
columns.add(4, "New Form Type");
System.out.println("Before calling Data Base");
jobList = objConnectmagr.AutoRollBackSearch(searchlist, startDate, endDate, "AutoPopRollBack");
if (jobList.size() > 0) {
for (int i = 0; i < jobList.size(); i++) {
ArrayList temp = new ArrayList();
temp = (ArrayList) jobList.get(i);
Vector col = new Vector();
col.add(0, new Boolean(false));
col.add(1, temp.get(0).toString().trim());
col.add(2, temp.get(1).toString().trim());
col.add(3, temp.get(2).toString().trim());
Vector tempstr=new Vector();
String [] tem=temp.get(3).toString().trim().split("\\|");
tempstr.removeAllElements();
for(int k=0;k<tem.length;k++)
tempstr.add(k,tem[k]);
col.add(4, new JComboBox(tempstr));
data.add(col);
dm.setDataVector(data, columns);
table = new JTable(dm) {
public void tableChanged(TableModelEvent e) {
super.tableChanged(e);
public boolean isCellEditable(int rowIndex, int vColIndex) {
return true;
JScrollPane scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
table.setColumnSelectionAllowed(false);
table.setRowSelectionAllowed(false);
table.setCellSelectionEnabled(false);
table.setBackground(SystemColor.inactiveCaptionText);
table.setRowHeight(20);
JTableHeader head = table.getTableHeader();
head.setSize(850, 75);
table.setTableHeader(head);
table.getTableHeader().setFont(new Font("Verdana", Font.BOLD, 11));
table.getTableHeader().setBackground(new Color(130, 170, 150));
table.getTableHeader().setForeground(Color.BLUE);
table.getTableHeader().setReorderingAllowed(false);
table.getTableHeader().setResizingAllowed(false);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFont(new java.awt.Font("MS Sans Serif", 0, 13));
table.setForeground(new Color(125, 25, 0));
TableColumn col = table.getColumnModel().getColumn(0);
col.setMinWidth(75);
col.setMaxWidth(75);
TableColumn col1 = table.getColumnModel().getColumn(1);
col1.setMinWidth(150);
col1.setMaxWidth(150);
TableColumn col2 = table.getColumnModel().getColumn(2);
col2.setMinWidth(150);
col2.setMaxWidth(150);
TableColumn col3 = table.getColumnModel().getColumn(3);
col3.setMinWidth(150);
col3.setMaxWidth(150);
TableColumn col4 = table.getColumnModel().getColumn(4);
col4.setMinWidth(160);
col4.setMaxWidth(160);
TableColumn tc = table.getColumnModel().getColumn(0);
tc.setCellEditor(table.getDefaultEditor(Boolean.class));
tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener()));
Vector tempstr=new Vector();
for(int j=0;j<jobList.size();j++){
ArrayList temlist=(ArrayList)jobList.get(j);
String [] tem=temlist.get(3).toString().trim().split("\\|");
tempstr.removeAllElements();
for(int k=0;k<tem.length;k++)
tempstr.add(k,tem[k]);
JComboBox portTypesCombo = new JComboBox(tempstr);
col4.setCellEditor(new DefaultCellEditor(portTypesCombo));
col4 = table.getColumnModel().getColumn(4);
col4.setCellEditor(new MyComboBoxEditor(tempstr));
// If the cell should appear like a combobox in its
// non-editing state, also set the combobox renderer
col4.setCellRenderer(new MyComboBoxRenderer(tempstr));
System.out.println(tempstr);
displayPanel.setLayout(new BorderLayout());
displayPanel.add(table.getTableHeader(), BorderLayout.PAGE_START);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
table.setEditingColumn(0);
int column = 0;
if (e.getClickCount() == 1) {
Point p = e.getPoint();
selectedRow = table.rowAtPoint(p);
column = table.columnAtPoint(p);
System.out.println(table.isCellEditable(selectedRow, column));
if (column != 0) {
selectedRow = -1;
returnList = new Vector();
returnList = (Vector) rows.get(selectedRow);
else if (column == 0) {
table.revalidate();
table.repaint();
scroll.getViewport().add(table);
displayPanel.add(scroll, BorderLayout.CENTER);
displayPanel.setVisible(true);
else {
JOptionPane.showMessageDialog(this, "No Data Available");
} catch (Exception e1) {
e1.printStackTrace();
class MyItemListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
Object source = e.getSource();
if (source instanceof AbstractButton == false)return;
boolean checked = e.getStateChange() == ItemEvent.SELECTED;
for (int x = 0, y = table.getRowCount(); x < y; x++) {
table.setValueAt(new Boolean(checked), x, 0);
class AutoPopRollBack_SearchBtn_actionAdapter implements java.awt.event.ActionListener {
AutoPopRollBack adaptee;
AutoPopRollBack_SearchBtn_actionAdapter(AutoPopRollBack adaptee) {
this.adaptee = adaptee;
public void actionPerformed(ActionEvent e) {
adaptee.SearchBtn_actionPerformed(e);
class RadioButtonRenderer implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (value == null)return null;
return (Component) value;
class RadioButtonEditor extends DefaultCellEditor implements ItemListener {
private JRadioButton button;
public RadioButtonEditor(JCheckBox checkBox) {
super(checkBox);
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row,
int column) {
if (value == null)return null;
button = (JRadioButton) value;
button.addItemListener(this);
return (Component) value;
public Object getCellEditorValue() {
button.removeItemListener(this);
return button;
public void itemStateChanged(ItemEvent e) {
super.fireEditingStopped();
class CheckCellRenderer extends JCheckBox implements TableCellRenderer {
protected static Border m_noFocusBorder;
public CheckCellRenderer() {
super();
m_noFocusBorder = new EmptyBorder(1, 2, 1, 2);
setOpaque(true);
setBorder(m_noFocusBorder);
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
if (value instanceof Boolean) {
Boolean b = (Boolean) value;
setSelected(b.booleanValue());
setBackground(isSelected && !hasFocus ?
table.getSelectionBackground() : table.getBackground());
setForeground(isSelected && !hasFocus ?
table.getSelectionForeground() : table.getForeground());
setFont(table.getFont());
setBorder(hasFocus ? UIManager.getBorder(
"Table.focusCellHighlightBorder") : m_noFocusBorder);
return this;
class CheckBoxHeader extends JCheckBox implements TableCellRenderer, MouseListener {
protected CheckBoxHeader rendererComponent;
protected int column;
protected boolean mousePressed = false;
public CheckBoxHeader(ItemListener itemListener) {
rendererComponent = this;
rendererComponent.addItemListener(itemListener);
public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (table != null) {
JTableHeader header = table.getTableHeader();
if (header != null) {
rendererComponent.setForeground(header.getForeground());
rendererComponent.setBackground(header.getBackground());
rendererComponent.setFont(new java.awt.Font("Verdana", 1, 10));
header.addMouseListener(rendererComponent);
setColumn(column);
rendererComponent.setText("Select All");
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
return rendererComponent;
protected void setColumn(int column) {
this.column = column;
public int getColumn() {
return column;
protected void handleClickEvent(MouseEvent e) {
if (mousePressed) {
mousePressed = false;
JTableHeader header = (JTableHeader) (e.getSource());
JTable tableView = header.getTable();
TableColumnModel columnModel = tableView.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = tableView.convertColumnIndexToModel(viewColumn);
if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) {
doClick();
public void mouseClicked(MouseEvent e) {
handleClickEvent(e);
( (JTableHeader) e.getSource()).repaint();
public void mousePressed(MouseEvent e) {
mousePressed = true;
public void mouseReleased(MouseEvent e) {
public void mouseEntered(MouseEvent e) {
public void mouseExited(MouseEvent e) {
class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
public MyComboBoxRenderer(Vector items) {
super(items);
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
else {
setForeground(table.getForeground());
setBackground(table.getBackground());
// Select the current value
setSelectedItem(value);
return this;
class MyComboBoxEditor extends DefaultCellEditor {
public MyComboBoxEditor(Vector items) {
super(new JComboBox(items));
and Bringing data from data base by using this method
if (i == 0) sqlString = "SELECT * FROM FLIGHTSEARCH WHERE AGENT_CODE='" + agentCode + "' and ISSUEDATE BETWEEN '" + startDate + "' and '" + endDate + "'";
else sqlString = "SELECT * FROM FLIGHTSEARCH WHERE AGENT_CODE='" + agentCode + "' and JOB_NO='" + JobNo + "%'";
st = con.createStatement();
System.out.println("---new jobs search-->" + sqlString);
rs = st.executeQuery(sqlString);
while (rs.next()) {
retVector = new ArrayList();
retVector.add(0, rs.getString("JOBNO"));
retVector.add(1, "New Job");
retVector.add(2, rs.getString("DOC_TYPE"));
String temp="";
if(retVector.get(2).toString().trim().equalsIgnoreCase("K1")){
temp="K8I|K8T";
}else if(retVector.get(2).toString().trim().equalsIgnoreCase("K2")){
temp="K8E";
}else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8I")){
// temp="K1|K8T";
}else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8T")){
temp="K1|K8I";
}else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8E")){
temp="K2";
retVector.add(3,temp);
retVector.add(3, rs.getString("AGENT_CODE"));
retVectorlist.add(retVector);
i am sending data To ComboBox like this
if(retVector.get(2).toString().trim().equalsIgnoreCase("K1")){
K8I and K8T
if K2 adding k8E and for other types as mentioned above
But for ComboBoxes it is showing same Items not changing
Please any body can help to me
Thanks and Regards
Ravichandra

If you want further help post a Short, Self Contained, Compilable and Executable, Example Program ([url http://homepage1.nifty.com/algafield/sscce.html]SSCCE) that demonstrates the problem.
And don't forget to use [url http://forum.java.sun.com/help.jspa?sec=formatting]code formatting when posting code.

Similar Messages

  • JTable with JComboBox/JSpinner problem

    The following code has a JTable with 2 columns.The lst column has JComboBoxes, the 2nd column has JSpinners.I want to set the spinner range of values based on the selection of JComboBox. The JComboBox selections are "small" and "large". For "small" the spinner should range from 0..49, for "large" from 50..99. When a selection is made, MyTable.itemStateChanged() is called, which in turn calls SpinnerEditor.setValueRange(). This sets an array with the desired values and then sets the model with this array. However, it sets the range not only for the row in which the combo box was clicked, but all rows.
    So in MyTable.setCellComponents(), there is this:
    spinnerEditor = new SpinnerEditor(this, defaultTableModel);
    modelColumn.setCellEditor(spinnerEditor);
    If the table has n rows, are n SpinnerEditors created, or just 1?
    If 1, do n need to be created and if so, how?
    public class MyTable extends JTable implements ItemListener {
         private DefaultTableModel defaultTableModel;
         private Vector<Object> columnNameVector;
         private JComboBox jComboBox;
         private SpinnerEditor spinnerEditor;
         private final int COMBO_BOX_COLUMN = 0;
         final static int SPINNER_COLUMN = 1;
         public static String SMALL = "Small";
         public String LARGE = "Large";
         private final String[] SMALL_LARGE = {
                   SMALL,
                   LARGE };
         public MyTable(String name, Object[][] variableNameArray, Object[] columnNameArray) {
              columnNameVector = new Vector<Object>();
              // need column names in order to make copy of table model
              for (Object object : columnNameArray) {
                   columnNameVector.add(object);
              defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
              this.setModel(defaultTableModel)     ;
              setCellComponents();
              setListeners();
         private void setCellComponents() {
              // combo box column -----------------------------------------------
              TableColumn modelColumn = this.getColumnModel().getColumn(COMBO_BOX_COLUMN);
              jComboBox = new JComboBox(SMALL_LARGE);
              // set default values
              for (int row = 0; row < defaultTableModel.getRowCount(); row++) {
                   defaultTableModel.setValueAt(SMALL_LARGE[0], row, COMBO_BOX_COLUMN);
              modelColumn.setCellEditor(new DefaultCellEditor(jComboBox));
              DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for small/large"); // tooltip
              modelColumn.setCellRenderer(renderer);
              // index spinner column ------------------------------------------------------------
              modelColumn = this.getColumnModel().getColumn(SPINNER_COLUMN);
              spinnerEditor = new SpinnerEditor(this, defaultTableModel);
              modelColumn.setCellEditor(spinnerEditor);
              renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for index value"); // tooltip
              modelColumn.setCellRenderer(renderer);
         private void setListeners() {
              jComboBox.addItemListener(this);
         @Override
         public void itemStateChanged(ItemEvent event) {
              // set spinner values depending on small or large
              String smallOrLarge = (String)event.getItem();
              if (this.getEditingRow() != -1 && this.getEditingColumn() != -1) {
                   spinnerEditor.setValueRange(smallOrLarge);
         public static void main(String[] args) {
              try{
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e){
                   e.printStackTrace();
              String[] columnNameArray = {"JComboBox", "JSpinner"};
              Object[][]  dataArray = {
                        {"", "0"},
                        {"", "0"},
                        {"", "0"},
              final MyTable myTable = new MyTable("called from main", dataArray, columnNameArray);
              final JFrame frame = new JFrame();
              frame.getContentPane().add(new JScrollPane(myTable));
              frame.setTitle("My Table");
              frame.setPreferredSize(new Dimension(200, 125));
              frame.addWindowListener(new WindowAdapter(){
                   @Override
                   public void windowClosing(WindowEvent e) {
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setLocation(800, 400);
              frame.pack();
              frame.setVisible(true);
    public class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
         private JComponent parent;
         private DefaultTableModel defaultTableModel;
         private final JSpinner spinner = new JSpinner();
         private String[] spinValues;
         private int row;
         private int column;
         public SpinnerEditor(JTable parent, DefaultTableModel defaultTableModel ) {
              super();
              this.parent = parent;
              this.defaultTableModel = defaultTableModel;
              setValueRange(MyTable.SMALL);
              // update every time spinner is incremented or decremented
              spinner.addChangeListener(new ChangeListener(){
                   public void stateChanged(ChangeEvent e) {
                        String value = (String) spinner.getValue();
                        System.out.println ("SpinnerEditor.stateChanged(): " + value);
                        setValue(value);
         private void setValue(String value) {
              // save to equation string
              System.out.println ("SpinnerEditor.setValue(): " + value + " at (" + row + ", " + MyTable.SPINNER_COLUMN + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
         @Override
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)      {
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): row: " + row + "\tcolumn: " + column);
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): value: " + value);
              this.row = row;
              this.column = column;
              return spinner;
         @Override
         public boolean isCellEditable(EventObject evt) {
              return true;
         // Returns the spinners current value.
         @Override
         public Object getCellEditorValue() {
              return spinner.getValue();
         @Override
         public boolean stopCellEditing() {
              System.out.println("SpinnerEditor.stopCellEditing(): spinner: " + spinner.getValue() + " at (" + this.row + ", " + this.column + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
              return true;
         public void setValueRange(String smallOrLarge) {
              System.out.println ("SpinnerEditor.setValueRange for " + smallOrLarge);
              final int ARRAY_SIZE = 50;
              if (MyTable.SMALL.equals(smallOrLarge)) {
                   final int MIN_SPIN_VALUE = 0;               
                   final int MAX_SPIN_VALUE = 49;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = MIN_SPIN_VALUE; i <= MAX_SPIN_VALUE; i++) {
                        spinValues[i] = new String(Integer.toString(i));
              else { // large
                   final int MIN_SPIN_VALUE = 50;               
                   final int MAX_SPIN_VALUE = 99;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = 0; i <ARRAY_SIZE; i++) {
                        spinValues[i] = new String(Integer.toString(MIN_SPIN_VALUE + i));
                   //for (int i = 0; i <ARRAY_SIZE; i++) {
                   //     System.out.println ("spinValues[" + i + "] = " + spinValues);
              System.out.println ("SpinnerEditor.setValueRange(): [" + spinValues[0] + ".." + spinValues[ARRAY_SIZE-1] + "]");
              // set model
              spinner.setModel(new SpinnerListModel(java.util.Arrays.asList(spinValues)));

    However, it sets the range not only for the row in which the combo box was clicked, but all rows. Yes, because a single editor is used by the column.
    One solution is to create two editors, then you override the getCellEditor(...) method to return the appropriated editor. Something like:
    If (column == ?)
        if (smallOrLarge)
          return the small or large spinner editor
        else
           return the large spinner editor
    else
        return super.getCellEditor(...);

  • How to stop Auto Edit in JTable With JComboBox or JTextField

    Hi everybody
    I'm working with JTable and having 5 columns last 3 are hidden. First contains a Combobox Editor and Second contens JTextbox for editing. Every thing working fine except that whenever i clik the table it automatically opens its editor either JComboBox or JTextField for editing.
    I want to remove this and want to allow editing whenever user press Enter key on that column.
    I am using class
    FeeAmtEditor extends JTextField implements TableCellEditor for Textbox editing and class FeeTypeEditor extends JComboBox implements TableCellEditor for combobox edition
    another promblem that I need to press 'Escape' key to deactivate combo box or text box after entering data. This also i want to avoid.
    thanks in advance

    public void setComboBox(JComboBox cb, int columnindex)
            if(columnindex < 0 || columnindex >= getColumnCount())
                return;
            DefaultCellEditor dce = new DefaultCellEditor(cb);
            dce.setClickCountToStart(2);
            TableColumn column = jtable.getColumn(getColumnName(columnindex));
            column.setCellEditor(dce);
        }hope this help you..

  • JTable with JComboBox cells

    Hi all,
    When I make the JComboBox(es) become the cell of the JTable, the list of JComboBox is not expanded as the way a JComboBox behaves when you click on the arrow to see the whole list. I think the JComboBox is not receiving the mouse click event. Another way to say, something keeps the JComboBox from receiving the mouse click.
    Has anybody experienced this scenario?
    Frank.

    Is the table cell editable? If it isn't, that is your problem. Enable cell editing for that cell(s).
    Stephen

  • JTable with custom combobox

    Hi
    I been trying to create a JTable with a custom combobox, that is in a column the lists contained within each combobox is unique. I tried using a renderer, even though the combo appears I cannot select the combo for editing. Any suggestions on how to get the combo working properly would be appreciated thanks.

    It's been a few years since I did something like this, but my recollection is that you should implement the TableCellEditor interface and have the getTableCellEditor method return your custom combo box. Then, either override getCellEditor in your JTable to return your custom TableCellEditor or (better) call tableColumn.setCellEditor for the column you're interested in, passing an instance of your TableCellEditor. I suggest you return the same JComboBox from your implementation of getTableCellEditor every time, and either replace the underlying model or have a custom model in which you can easily switch the contents on-the-fly.
    Having done this in the past, I remember that it's quite easy to leak stuff - I wouldn't advise making a new JComboBox every time.
    Regards,
    Huw

  • Problem sorting JTable with custom cell editor

    Greetings,
    I have created a JTable with a JComboBox as the cell editor for the first column. However, I couldn't simply set the default cell editor for the column to be a JComboBox, since the values within the list were different for each row. So instead, I implemented a custom cell editor that is basically just a hashtable of cell editors that allows you to have a different editor for each row in the table (based on the ideas in the EachRowEditor I've seen in some FAQs - see the code below). I also used a custom table model that is essentially like the JDBCAdapter in the Java examples that populates the table with a query to a database.
    The problem comes when I try to sort the table using the TableSorter and TableMap classes recommended in the Java Tutorials on JTables. All of the static (uneditable) columns in the JTable sort fine, but the custom cell editor column doesn't sort at all. I think that the problem is that the hashtable storing the cell editors never gets re-ordered, but I can't see a simple way to do that (how to know the old row index verses the new row index after a sort). I think that I could implement this manually, if I knew the old/new indexes...
    Here's the code I use to create the JTable:
    // Create the Table Model
    modelCRM = new ContactTableModel();
    // Create the Table Sorter
    sorterCRM = new TableSorter(modelCRM);
    // Create the table
    tblCRM = new JTable(sorterCRM);
    // Add the event listener for the sorter
    sorterCRM.addMouseListenerToHeaderInTable(tblCRM);
    Then, I populate the column for the custom cell editor like this:
    // Add the combo box for editing company
    TableColumn matchColumn = getTable().getColumn("Match");
    RowCellEditor rowEditor = new RowCellEditor();
    // loop through and build the combobox for each row
    for (int i = 0; i < getTable().getRowCount(); i++) {
    JComboBox cb = new JComboBox();
    cb.addItem("New");
    //... code to populate the combo box (removed for clarity)
    rowEditor.add(i,new DefaultCellEditor(cb, i))); //TF
    } // end for
    matchColumn.setCellEditor(rowEditor);
    Any ideas how to do this, or is there a better way to either sort the JTable or use a combobox with different values for each row? Please let me know if more code would help make this clearer...
    Thanks,
    Ted
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class RowCellEditor implements TableCellEditor
    protected Hashtable editors;
    protected TableCellEditor editor, defaultEditor;
    public RowCellEditor()
    editors = new Hashtable();
    defaultEditor = new DefaultCellEditor(new JTextField());
    public void add(int row, TableCellEditor editor)
    editors.put(new Integer(row), editor);
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column)
    editor = (TableCellEditor) editors.get(new Integer(row));
    if (editor == null)
    editor = defaultEditor;
    return editor.getTableCellEditorComponent(table,
    value,
    isSelected,
    row,
    column);
    public Object getCellEditorValue() {
    return editor.getCellEditorValue();
    public boolean stopCellEditing() {
    return editor.stopCellEditing();
    public void cancelCellEditing() {
    editor.cancelCellEditing();
    public boolean isCellEditable(EventObject anEvent) {
    return true; //TF
    //return editor.isCellEditable(anEvent);
    public void addCellEditorListener(CellEditorListener l) {
    editor.addCellEditorListener(l);
    public void removeCellEditorListener(CellEditorListener l) {
    editor.removeCellEditorListener(l);
    public boolean shouldSelectCell(EventObject anEvent) {
    return editor.shouldSelectCell(anEvent);
    -------------------

    Well, I found a solution in another post
    (see http://forum.java.sun.com/thread.jsp?forum=57&thread=175984&message=953833#955064 for more details).
    Basically, I use the table sorter to translate the row index for the hashtable of my custom cell editors. I did this by adding this method to the sorter:
    // This method is used to get the correct row for the custom cell
    // editor (after the table has been sorted)
    public int translateRow(int sortedRowIndex)
    checkModel();
    return indexes[sortedRowIndex];
    } // end translateRow()
    Then, when I create the custom cell editor, I pass in a reference to the sorter so that when the getTableCellEditorComponent() method is called I can translate the row to the newly sorted row before returning the editor from the hashtable.

  • JTable with JCheckbox problems

    Ok so I have a couple of questions. I have a JTable with a column represented as a checkbox.
    1. If I put the checkbox column as the first in the table, the rest of the cells are blank/null. Any idea what the reason is?
    2. What is the best workaround to having draggable columns, meaning icons/checkboxes don't render if you move the columns around?
    3. Does anyone have some links to good resources on JTables and things like custom components in them. I have googled but don't get many good links so would appreciate any help
    Code snippet as follows:
    public class ClobberTableCellRenderer implements TableCellRenderer
    private JPanel renderPanel = new JPanel(new BorderLayout());
    private JLabel renderLbl = new JLabel("");
    private JCheckBox checked = new JCheckBox();
    private Icon successIcon;
    private Icon errorIcon;
    public Component getTableCellRendererComponent(JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row,
    int column)
    String columnName = table.getModel().getColumnName(column);
    if (value == null)
    return null;
    else if ("Status".equals(columnName) && "ok".equals(value))
    renderLbl.setIcon(successIcon);
    renderLbl.setText("");
    renderPanel.remove(checked);
    else if ("Status".equals(columnName) && "error".equals(value))
    renderLbl.setIcon(errorIcon);
    renderLbl.setText("");
    renderPanel.remove(checked);
    else if ("Active".equals(columnName))
    renderLbl.setText("");
    renderPanel.add(checked);
    renderPanel.setBackground(Color.white);
    else
    renderLbl.setHorizontalAlignment(value instanceof Date || value instanceof Number ? JLabel.RIGHT : JLabel.LEFT);
    renderLbl.setIcon(null);
    renderLbl.setText(value instanceof Date ? df.format((Date)value) : value.toString());
    renderLbl.setToolTipText(null);
    renderPanel.setToolTipText(null);
    renderPanel.remove(checked);
    if (isSelected)
    renderPanel.setBackground((Color)UIManager.getDefaults().get("Table.selectionBackground"));
    else
    renderPanel.setBackground((Color)UIManager.getDefaults().get("Table.background"));
    return renderPanel;
    }

    Hi :) I have also worked on JTables and JCheckBoxes before. This article
    helped me a lot: http://www-128.ibm.com/developerworks/java/library/j-jtable/

  • How do I create a jtable with horizontalScroll bar,plz help me!

    I created a jtable component,Because my table's columns has 50 items,I must need a horizontalScroll Bar.
    but I find the horizontalScroll don't display,when I add record to the jtable,the verticalScroll Bar is showed.How do I create a jtable with horizontalScroll bar,can u help me!
    thank you in advance!

    Hi,
    This piece of code will help :
         //Get the Component Adapter for taking action against resizing of
    //of Panel
    ComponentListenerAdapter componentAdapter =
    new ComponentListenerAdapter()
    //Get the scrollbar or remove the scrollbar upon resizing
    protected void resizingAction()
    Container tableParent = table.getParent();
    if (tableParent instanceof JViewport)
    //Check if the width of the Table Parent Container
    //is less than the Preferred Size of the Table
    if (tableParent.getSize().getWidth() <
    table.getPreferredSize().getWidth())
    //Yes it is
    //Remove the Auton Resize Function and get the
    //Scrollbar
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF );
    else
    //No it is not
    //Get the Auto Resize functionality back in place
    table.setAutoResizeMode(
    JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
    //Add the component Adapter to the Table Header
    table.getTableHeader().addComponentListener(componentAdapter);
    private abstract class ComponentListenerAdapter
    implements ComponentListener
              * The <code>componentHidden<code> method has no implementation
              * @param event The Event occured whenever the Component is Hidden
              public void componentHidden(ComponentEvent event)
                   //No Implementaion - Intentially Left Blank
              * The <code>componentShown</code> method has no implementation
              * @param event The Event occured whenever the Component is Shown
              public void componentShown(ComponentEvent event)
                   //No Implementaion - Intentially Left Blank
              * The <code>componentMoved</code> method has no implementation
              * @param event The Event occured whenever the Component is Moved
              public void componentMoved(ComponentEvent event)
                   //No Implementaion - Intentially Left Blank
              * The <code>componentResized</code> method is invoked whenever the
              * component is resized. The resizing action will set the columns and
              * scrollbar to act properly
              * @param event The Event occured whenever the Component is Resized
              public void componentResized(ComponentEvent event)
                   resizingAction();
    * Subclasses of this override this method to determine what is to be
    * done once the Component has been Resized
    protected abstract void resizingAction();
    Hope this will solve all your JTable horizontal resizing problems
    --j                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • JTable in JComboBox

    if any one has got a code for displaying more then one column in JCombobox(i.e JTable in JComboBox)
    plz. send to this mail id :- [email protected]
    Hope this helps.
    Regards,
    chandru

    do u want JTable in JCombobox or a JComboBox in a JTable?

  • FocusListener problem with JComboBox

    Hi,
    I am facing a problem with JComboBox. When I make it as Editable it is not Listening to the FocucListener Event....
    Please tell me if there is any way to overcome this..
    Regards,
    Chandan Sharma

    I searched the forum using "jcombobox focuslistener editable" and quess what, the first posting I read had the solution.
    Search the forum before posting questions.

  • JTable with custom column model and table model not showing table header

    Hello,
    I am creating a JTable with a custom table model and a custom column model. However the table header is not being displayed (yes, it is in a JScrollPane). I've shrunk the problem down into a single compileable example:
    Thanks for your help.
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test1 extends JFrame
         public static void main(String args[])
              JTable table;
              TableColumnModel colModel=createTestColumnModel();
              TestTableModel tableModel=new TestTableModel();
              Test1 frame=new Test1();
              table=new JTable(tableModel, colModel);
              frame.getContentPane().add(new JScrollPane(table));
              frame.setSize(200,200);
              frame.setVisible(true);
         private static DefaultTableColumnModel createTestColumnModel()
              DefaultTableColumnModel columnModel=new DefaultTableColumnModel();
              columnModel.addColumn(new TableColumn(0));
              return columnModel;
         static class TestTableModel extends AbstractTableModel
              public int getColumnCount()
                   return 1;
              public Class<?> getColumnClass(int columnIndex)
                   return String.class;
              public String getColumnName(int column)
                   return "col";
              public int getRowCount()
                   return 1;
              public Object getValueAt(int row, int col)
                   return "test";
              public void setValueAt(Object aValue, int rowIndex, int columnIndex)
    }Edited by: 802416 on 14-Oct-2010 04:29
    added                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    Kleopatra wrote:
    jduprez wrote:
    See http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setHeaderValue(java.lang.Object)
    When the TableColumn is created, the default headerValue  is null
    So, the header ends up rendered as an empty label (probably of size 0 if the JTable computes its header size based on the renderer's preferred size).nitpicking (can't resist - the alternative is a cleanup round in some not so nice code I produced recently <g>):
    - it's not the JTable's business to compute its headers size (and it doesn't, the header's the culprit.) *> - the header should never come up with a zero (or near-to) height: even if there is no title shown, it's still needed as grab to resize/move the columns. So I would consider this sizing behaviour a bug.*
    - furthermore, the "really zero" height is a longstanding issue with MetalBorder.TableHeaderBorder (other LAFs size with the top/bottom of their default header cell border) which extends AbstractBorder incorrectly. That's easy to do because AbstractBorder itself is badly implemented
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459419
    Thanks for the opportunity to have some fun :-)
    JeanetteNo problem, thanks for the insight :)

  • Need help serializing an AbstractTableModel for a JTable with cell editing.

    Fun times are ahead. Here we go!
    I have a JTable that contains data I'd like to serialize out to a file to be restored and viewed later.
    So I tried saving the AbstractTableModel subclass out to a file. Whenever I do this, I get the following error message:
    java.io.NotSerializableException: javax.swing.JTable$CellEditorRemover
    Now I know for fact that serializing an AbstractTableModel that was installed in a JTable without cell editing works just fine (my old code did exactly that). As a result, I think that the code that handles events in the AbstractTableModel contains references back out to the JTable, which causes the JTable to be saved no matter what (even though I'm just interested in saving the TableModel only). It causes a bigger file than normal, but file size is not an issue. The only issue I have is that CellEditorRemover (an undocumented inner class of JTable), which is automatically installed for JTables with editable cells, is not serializable.
    This leads to the following questions:
    1. Is there a way to avoid serialization/deserialization of the CellEditorRemover inner class of JTable?
    2. Is there a way to save an AbstractTableModel without saving all of the event listeners associated with it?
    I think an answer to either of these questions would go a long way towards solving my problem. Otherwise, I'll resign myself to weeping silently in the corner of my office.
    Thanks!

    I would suggest that if you can you only save the
    data... but i would do this by using the
    externalizable interface.
    What you will need to do is have the
    writeExternal(ObjectOutputStream out) and
    readExternal(ObjectOutputStream out) methods in your
    class. These will be responsiable for saving the
    data.
    Here's an example of what you can do in these
    methods... this is just a little tidbit from a program
    i've written.public void writeExternal(ObjectOutput out) throws
    IOException {
              out.writeInt(size);
              out.writeObject(drawName);
              out.writeInt(playersLength);
    for(int i = 0; i < playersLength; i++)
    ) out.writeObject(players);
              out.writeInt(seedsLength);
    for(int i = 0; i < seedsLength; i++)
    ) out.writeObject(seeds[i]);
              out.writeInt(drawLength);
    for(int i = 0; i < drawLength; i++)
    ) out.writeObject(draw[i]);
    public void readExternal(ObjectInput in) throws
    IOException, ClassNotFoundException {
              size = in.readInt();
              drawName = (String)in.readObject();
              playersLength = in.readInt();
    for(int i = 0; i < playersLength; i++) players[i] =
    = (String)in.readObject();
              seedsLength = in.readInt();
    for(int i = 0; i < seedsLength; i++) seeds[i] =
    = (String)in.readObject();
              drawLength = in.readInt();
    for(int i = 0; i < drawLength; i++) draw[i] =
    = (String)in.readObject();
    You can now use your class as you would a Serializable
    class, but it will only save the data
    Hope this helped
    webaf409java
    I forgot to add some critical information in my original post. My apologies. :(
    I've thought about using Externalizable, but am hesitant to use it because the application would no longer be able to read in files using the old save format (ie, AbstractTableModels for JTables without CellEditorRemovers ).  I want to preserve the ability to read the old saved AbstractTableModel formats if possible. 
    Do you know of a way to revert to the default deserialization mechanism from readExternal?  This way, during deserialization, I could do a quick test on the object being read and have the ability to default to the regular deserialization mechanism if the object is of the old type or continue with the new Externalizable stuff if the object is one of the new type.  Maintaining file compatibility is key.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Can we create JTable with multiple rows with varying number of columns ?

    Hi All,
    I came across a very typical problem related to JTable. My requirement is that cells should be added dynamically to the JTable. I create a JTable with initial size of 1,7 (row, columns) size. Once the 7 columns are filled with data, a new row should be created. But the requirement is, the new row i.e. second row should have only one cell in it initially. The number of cells should increase dynamically as the data is entered. The table is automatically taking the size of its previous row when new row is added. I tried by using setColumnCount() to change the number of columns to '1' for the second row but the same is getting applied to the first row also.
    So can you please help me out in this regard ? Is it possible to create a JTable of uneven size i.e. multiple rows with varying number of columns in each row ?
    Thanks in Advance.

    Well a JTable is always going to paint the same number of columns for each row. Anything is possible if you want to rewrite the JTable UI to do this, but I wouldn't recommend it. (I certainly don't know how to do it).
    A simpler solution might be to override the isCellEditable(...) method of JTable and prevent editing of column 2 until data in column 1 has been entered etc., etc. You may also want to provide a custom renderer that renderers the empty column differently, maybe with a grey color instead of a white color.

  • Mouse motion listener for JTable with JScrollpane

    Hi All,
    I have added mouse motion listener for JTable which is added in JScrollPane. But if i move the mouse, over the vertical/horizontal scroll bars, mouse motion listener doesn't works.
    So it it required to add mousemotionlistener for JTable, JScrollPane, JScrollBar and etc.
    Thanks in advance.
    Regards,
    Tamizhan

    I am having one popup window which shows address information. This window contains JTable with JScrollPane and JButton components to show the details. While showing this information window, if the mouse cursor is over popupwindow, it should show the window otherwise it should hide the window after 30 seconds.
    To achieve this, i have added mouse listener to JPanel, JTable, JButton and JScrollPane. so if the cursor is in any one of the component, it will not hide the window.
    but for this i need to add listener to all the components in the JPanel. For JScrollPane i have to add horizontal, vertical and all the top corner buttons of Scroll bar.
    Is this the only way to do this?

  • JTable with ImageIcons does not react to even handling

    Hi.
    I have a populated JTable with ONLY ImageIcons in it. I need to generate event responses on mouseClicks. However, any event listener I associate with this, nothing seems to be happening.
    (Somehow, I'm guess the ImageIcons - which are rendered on a JLabel, are/is the source of all troubles!!)
    The code is below :
    import java.io.File;
    import java.awt.Point;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Container;
    import java.awt.Component;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.ImageIcon;
    import javax.swing.JScrollPane;
    import javax.swing.ListSelectionModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    *     Entry point for the Images Table.
    *     @author Raj Gaurav
    public class SpecialCharacterDialog extends JDialog{
         String collectionString[] = null;
         ImageIcon suite[] = null;
         public SpecialCharacterDialog() {
              Container contentPane = getContentPane();
              //     Create the Table Model and create the Table from the model
              MyTableModel model = new MyTableModel();
              JTable table = new JTable(model);
              table.setDefaultRenderer(ImageIcon.class, new CustomCellRenderer());
              table.setCellSelectionEnabled(true);
              table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionModel rowSM = table.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    System.out.println("No rows are selected.");
    } else {
    int selectedRow = lsm.getMinSelectionIndex();
    System.out.println("Row " + selectedRow
    + " is now selected.");
              //     Add the table to the contentPane
              JScrollPane pane = new JScrollPane(table);
              contentPane.add(pane);
    *     This class contains all the DATA information, the ImageIcons
    *     needed for display.
    class SymbolCollection {
         final static int NUMBER_OF_COLUMNS = 15;
         private String collectionString[] = null;
         private ImageIcon suite[] = null;
         *     Constructor : Initialises all the ImageIcon and their Names.
         public SymbolCollection() {
              File f = new File("C:\\Test\\Images");
              collectionString = f.list();
              int numberOfImages = collectionString.length;
              suite = new ImageIcon[numberOfImages];
              for(int i = 0;i < numberOfImages; i++) {
                   suite[i] = new ImageIcon("C:\\Test\\images" + File.separator + collectionString);
         *     Returns the total number of images in "images" folder.
         public int getTotalNumberOfImages() {
              return suite.length;
         *     Returns the target ImageIcon.
         public ImageIcon getImageIconAt(int number) {
              return suite[number];
         *     Returns the target ImageIcon Name.
         public String getImageIconNameAt(int number) {
              return collectionString[number];
         *     Returns an array of ALL the ImageIcons available.
         public ImageIcon[] getImageIcons() {
              return suite;
         *     Returns an array of ALL the ImageIcon names available
         public String[] getImageIconNames() {
              return collectionString;
         *     Returns TRUE for all cells
         public boolean isEditable(int row, int col) {
              return true;
    *     Defines the table model for the tabel.
    class MyTableModel extends AbstractTableModel {
         private SymbolCollection collection = null;
         private Object data[][] = null;
         *     Constructor for the TableModel. Initialises the "data" field for table.
         public MyTableModel() {
              int countOfImages = 0;
              collection = new SymbolCollection();
              data = new Object[getRowCount()][SymbolCollection.NUMBER_OF_COLUMNS];
              for(int i = 0; i < getRowCount(); i++) {
                   for(int j = 0; j < SymbolCollection.NUMBER_OF_COLUMNS; j++) {
                        if(countOfImages == collection.getTotalNumberOfImages()) {
                             break;
                        data[i][j] = collection.getImageIconAt(countOfImages);
                        countOfImages++;
         *     Returns the number of rows for this table.
         *     It is calculated as : TotalNumber/NumberOfColumns if remainder is ZERO or,
         *                              TotalNumber/NumberOfColumns + 1 if not.
         public int getRowCount() {
              int numberOfRows = collection.getTotalNumberOfImages()/SymbolCollection.NUMBER_OF_COLUMNS;
              if(numberOfRows == 0) {
                   return numberOfRows;
              else {
                   return numberOfRows + 1;
         *     Returns the number of Columns for this table
         public int getColumnCount() {
              return SymbolCollection.NUMBER_OF_COLUMNS;
         *     Returns the CLASS data type for this table
         public Class getColumnClass(int col) {
              return collection.getImageIconAt(0).getClass();
         *     Returns the table data at (row, col).
         public Object getValueAt(int row, int col) {
              return data[row][col];
    *     Renders the table to display images in individual cells
    class CustomCellRenderer extends JLabel implements TableCellRenderer {
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
              setIcon((ImageIcon)value);
              return this;

    Hi.
    I have a populated JTable with ONLY ImageIcons in it. I need to generate event responses on mouseClicks. However, any event listener I associate with this, nothing seems to be happening.
    (Somehow, I'm guess the ImageIcons - which are rendered on a JLabel, are/is the source of all troubles!!)
    The code is below :
    import java.io.File;
    import java.awt.Point;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Container;
    import java.awt.Component;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.ImageIcon;
    import javax.swing.JScrollPane;
    import javax.swing.ListSelectionModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    *     Entry point for the Images Table.
    *     @author Raj Gaurav
    public class SpecialCharacterDialog extends JDialog{
         String collectionString[] = null;
         ImageIcon suite[] = null;
         public SpecialCharacterDialog() {
              Container contentPane = getContentPane();
              //     Create the Table Model and create the Table from the model
              MyTableModel model = new MyTableModel();
              JTable table = new JTable(model);
              table.setDefaultRenderer(ImageIcon.class, new CustomCellRenderer());
              table.setCellSelectionEnabled(true);
              table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionModel rowSM = table.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    System.out.println("No rows are selected.");
    } else {
    int selectedRow = lsm.getMinSelectionIndex();
    System.out.println("Row " + selectedRow
    + " is now selected.");
              //     Add the table to the contentPane
              JScrollPane pane = new JScrollPane(table);
              contentPane.add(pane);
    *     This class contains all the DATA information, the ImageIcons
    *     needed for display.
    class SymbolCollection {
         final static int NUMBER_OF_COLUMNS = 15;
         private String collectionString[] = null;
         private ImageIcon suite[] = null;
         *     Constructor : Initialises all the ImageIcon and their Names.
         public SymbolCollection() {
              File f = new File("C:\\Test\\Images");
              collectionString = f.list();
              int numberOfImages = collectionString.length;
              suite = new ImageIcon[numberOfImages];
              for(int i = 0;i < numberOfImages; i++) {
                   suite[i] = new ImageIcon("C:\\Test\\images" + File.separator + collectionString);
         *     Returns the total number of images in "images" folder.
         public int getTotalNumberOfImages() {
              return suite.length;
         *     Returns the target ImageIcon.
         public ImageIcon getImageIconAt(int number) {
              return suite[number];
         *     Returns the target ImageIcon Name.
         public String getImageIconNameAt(int number) {
              return collectionString[number];
         *     Returns an array of ALL the ImageIcons available.
         public ImageIcon[] getImageIcons() {
              return suite;
         *     Returns an array of ALL the ImageIcon names available
         public String[] getImageIconNames() {
              return collectionString;
         *     Returns TRUE for all cells
         public boolean isEditable(int row, int col) {
              return true;
    *     Defines the table model for the tabel.
    class MyTableModel extends AbstractTableModel {
         private SymbolCollection collection = null;
         private Object data[][] = null;
         *     Constructor for the TableModel. Initialises the "data" field for table.
         public MyTableModel() {
              int countOfImages = 0;
              collection = new SymbolCollection();
              data = new Object[getRowCount()][SymbolCollection.NUMBER_OF_COLUMNS];
              for(int i = 0; i < getRowCount(); i++) {
                   for(int j = 0; j < SymbolCollection.NUMBER_OF_COLUMNS; j++) {
                        if(countOfImages == collection.getTotalNumberOfImages()) {
                             break;
                        data[i][j] = collection.getImageIconAt(countOfImages);
                        countOfImages++;
         *     Returns the number of rows for this table.
         *     It is calculated as : TotalNumber/NumberOfColumns if remainder is ZERO or,
         *                              TotalNumber/NumberOfColumns + 1 if not.
         public int getRowCount() {
              int numberOfRows = collection.getTotalNumberOfImages()/SymbolCollection.NUMBER_OF_COLUMNS;
              if(numberOfRows == 0) {
                   return numberOfRows;
              else {
                   return numberOfRows + 1;
         *     Returns the number of Columns for this table
         public int getColumnCount() {
              return SymbolCollection.NUMBER_OF_COLUMNS;
         *     Returns the CLASS data type for this table
         public Class getColumnClass(int col) {
              return collection.getImageIconAt(0).getClass();
         *     Returns the table data at (row, col).
         public Object getValueAt(int row, int col) {
              return data[row][col];
    *     Renders the table to display images in individual cells
    class CustomCellRenderer extends JLabel implements TableCellRenderer {
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
              setIcon((ImageIcon)value);
              return this;

Maybe you are looking for