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(...);
Similar Messages
-
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
RavichandraIf 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. -
JTable with ScrollPane update problem
hay i have a table and scrollpane is used as a container, at runtime i create new object of table and assign it to the scrollpane, but its still showing the old table,
I also tried to
updateUI();
repaint();
but it still showing the same old table,
I also debug and saw that the new table has been created n successfuly displaying the values at command prompt.
Can any one know whats wrong in it.Dont be ferious budy, now this is a working example....
Problem is: I am changing the table object in jPanel2 but still jPanel2 is showing the same old table, I think there is a refresh kind of a problem
Be kool dude n tell where is the problem.
package tabletesting;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerAdapter;
public class EmbededTable extends JFrame {
public EmbededTable() {
try {
jbInit();
} catch (Exception exception) {
exception.printStackTrace();
private void jbInit() throws Exception {
flag=1; // flag to alter between objects
getContentPane().setLayout(null);
jPanel1.setBorder(BorderFactory.createEtchedBorder());
jPanel1.setBounds(new Rectangle(28, 11, 320, 76));
jPanel1.setBackground(Color.pink);
jPanel1.setVisible(true);
// jPanel1 contain the buttons when press toggel the table in panel
this.setSize(new Dimension(640, 600));
this.addContainerListener(new EmbededTable_this_containerAdapter(this));
jPanel1.setLayout(null);
jButton1.setBounds(new Rectangle(57, 2, 71, 29));
jButton1.setText("jButton1");
jButton1.addActionListener(new EmbededTable_jButton1_actionAdapter(this));
jPanel2.setBorder(BorderFactory.createEtchedBorder());
jPanel2.setBounds(new Rectangle(22, 133, 578, 304));
jPanel2.addContainerListener(new EmbededTable_jPanel2_containerAdapter(this));
jPanel2.setLayout(borderLayout1);
testTable(); // to initially populate the jPanel2 with the tabel
jButton2.setBounds(new Rectangle(191, 20, 93, 25));
jButton2.setText("jButton2");
jButton2.addActionListener(new EmbededTable_jButton2_actionAdapter(this));
this.getContentPane().add(jPanel1);
jPanel1.add(jButton1, null);
jPanel1.add(jButton2);
this.getContentPane().validate();
this.setVisible(true);
this.show();
public void testTable()
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"Include Input",
"Include Output"};
Object[][] data = {
{"Mary", "Campione",
"Snowboarding", new Boolean(false), new Boolean(false)},
{"Alison", "Huml",
"Rowing", new Boolean(false), new Boolean(true)},
{"Kathy", "Walrath",
"Knitting", new Boolean(false), new Boolean(false)},
{"Sharon", "Zakhour",
"Speed reading", new Boolean(false), new Boolean(true)},
{"Philip", "Milne",
"Pool", new Boolean(false), new Boolean(false)},
if(flag==1)
TableDemo newContentPane = new TableDemo(columnNames,data,4,5);
newContentPane.setOpaque(true); //content panes must be opaque
jPanel2.add(newContentPane, BorderLayout.CENTER);
jPanel2.updateUI();
jPanel2.repaint();
jPanel2.revalidate();
this.getContentPane().add(jPanel2);
flag=0;
else if(flag==0)
Object[][] daa = {
{"A", "T",
"B", new Boolean(false), new Boolean(false)},
{"C", "T",
"Rowing", new Boolean(false), new Boolean(true)},
{"D", "T",
"Knitting", new Boolean(false), new Boolean(false)},
{"E", "T",
"Speed reading", new Boolean(false), new Boolean(true)},
{"F", "T",
"Pool", new Boolean(false), new Boolean(false)},
TableDemo newContentPane = new TableDemo(columnNames,daa,4,5);
newContentPane.setOpaque(true); //content panes must be opaque
this.getContentPane().add(jPanel2);
this.jPanel2.add(newContentPane,BorderLayout.CENTER);
this.jPanel2.updateUI();
jPanel2.repaint();
jPanel2.revalidate();
this.getContentPane().add(jPanel2);
flag=1;
public static void main(String[] args) {
EmbededTable embededtable = new EmbededTable();
JPanel jPanel1 = new JPanel();
static int flag;
JButton jButton1 = new JButton();
JPanel jPanel2 = new JPanel();
JPanel jPanel3 = new JPanel();
BorderLayout borderLayout1 = new BorderLayout();
JButton jButton2 = new JButton();
public void CreateGUI()
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"Include Input",
"Include Output"};
Object[][] data = {
{"A", "Campione",
"B", new Boolean(false), new Boolean(false)},
{"C", "Huml",
"Rowing", new Boolean(false), new Boolean(true)},
{"D", "Walrath",
"Knitting", new Boolean(false), new Boolean(false)},
{"E", "Zakhour",
"Speed reading", new Boolean(false), new Boolean(true)},
{"F", "Milne",
"Pool", new Boolean(false), new Boolean(false)},
//Create and set up the content pane.
TableDemo newContentPane = new TableDemo(columnNames,data,4,5);
newContentPane.setOpaque(true); //content panes must be opaque
jPanel3.setBorder(BorderFactory.createEtchedBorder());
jPanel3.setBounds(new Rectangle(22, 133, 578, 304));
jPanel3.setLayout(borderLayout1);
// this.getContentPane().remove(jPanel2);
this.getContentPane().add(jPanel3);
this.jPanel3.add(newContentPane,BorderLayout.CENTER);
this.jPanel3.updateUI();
this.validate();
public void jButton1_actionPerformed(ActionEvent e) {
CreateGUI();
public void jButton2_actionPerformed(ActionEvent e) {
testTable();
public void this_componentAdded(ContainerEvent e) {
public void jPanel2_componentRemoved(ContainerEvent e) {
System.out.println(" component removed");
public void jPanel2_componentAdded(ContainerEvent e) {
System.out.println(" component added");
class EmbededTable_jPanel2_containerAdapter extends ContainerAdapter {
private EmbededTable adaptee;
EmbededTable_jPanel2_containerAdapter(EmbededTable adaptee) {
this.adaptee = adaptee;
public void componentRemoved(ContainerEvent e) {
adaptee.jPanel2_componentRemoved(e);
public void componentAdded(ContainerEvent e) {
adaptee.jPanel2_componentAdded(e);
class EmbededTable_this_containerAdapter extends ContainerAdapter {
private EmbededTable adaptee;
EmbededTable_this_containerAdapter(EmbededTable adaptee) {
this.adaptee = adaptee;
public void componentAdded(ContainerEvent e) {
adaptee.this_componentAdded(e);
class EmbededTable_jButton2_actionAdapter implements ActionListener {
private EmbededTable adaptee;
EmbededTable_jButton2_actionAdapter(EmbededTable adaptee) {
this.adaptee = adaptee;
public void actionPerformed(ActionEvent e) {
adaptee.jButton2_actionPerformed(e);
class EmbededTable_jButton1_actionAdapter implements ActionListener {
private EmbededTable adaptee;
EmbededTable_jButton1_actionAdapter(EmbededTable adaptee) {
this.adaptee = adaptee;
public void actionPerformed(ActionEvent e) {
adaptee.jButton1_actionPerformed(e);
TabelDemo class
public class TableDemo extends JPanel {
private boolean DEBUG = false;
public TableDemo(String[] c, Object[][] d,int col,int row) {
super(new GridLayout(1, 0));
JTable table = new JTable(new MyTableModel(c,d,4,5));
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
Object obj=table.getValueAt(0,1);
table.updateUI();
JScrollPane scrollPane = new JScrollPane();
scrollPane.getViewport().setView(table);
Object ob= table.getValueAt(0,0);
System.out.println(" ob " + ob.toString());
scrollPane.updateUI();
scrollPane.getViewport().revalidate();
scrollPane.getViewport().updateUI();
add(scrollPane);
this.updateUI();
this.revalidate();
super.repaint();
super.validate();
Tabel class
public class MyTableModel extends AbstractTableModel {
boolean DEBUG= false;
public String[] columnNames ;
public String[] str; // to verify only one output variable
Boolean fal= new Boolean(false);
public Object[][] data;
MyTableModel()
MyTableModel(String[] col, Object[][] dat, int lenRow, int lenCol)
data=dat;
columnNames=col;
str= new String[col.length];
funcopy(str,lenRow);
void funcopy(String[] str, int lenRow)
for(int i=0;i<lenRow;i++)
str=fal.toString();
for(int i=0;i<str.length;i++)
System.out.println("values are " + str[i]);
public int getColumnCount() {
return columnNames.length;
public int getRowCount() {
return data.length;
public String getColumnName(int col) {
return columnNames[col];
public Object getValueAt(int row, int col) {
return data[row][col];
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
System.out.println("row " + row + "col " + col + value.toString());
Object obj= getValueAt(row,col);
if(col==3) // column 3 is the output column.
if(value.toString().equals("true"))
int savepointer=row;
int flag=-1;
for(int i=0;i<str.length;i++)
if(str[i].toString().equalsIgnoreCase("true"))
flag=1;
if(flag!=1)
System.out.println("inside flag ==1");
data[row][col]=value;
str[row]=value.toString();
fireTableCellUpdated(row, col);
if(value.toString().equals("false"))
data[row][col]=value;
str[row]=value.toString();
fireTableCellUpdated(row, col);
}// id col ends...
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
System.out.println();
System.out.println("--------------------------"); -
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 -
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 advancepublic 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.. -
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. -
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 SharmaI searched the forum using "jcombobox focuslistener editable" and quess what, the first posting I read had the solution.
Search the forum before posting questions. -
Strange problem with JComboBox
I am having a strange problem with JComboBox, I created a method as a JComboBox factory which returns a JComboBox filled with items. the method works fine and I can see the items in the JComboBox. The problem is when I try using the method myCombo.SelectedItem(String item); the object myCombo does not set the selected item, it just leaves the item blank (or unselected).
//This method build a JComboBox
public javax.swing.JComboBox makeJComboBox(String[] items) {
javax.swing.JComboBox myComboBox = new javax.swing.JComboBox();
for (int index=0;index<items.length;index++){
myComboBox.addItem(makeObj(items[index]));
return myComboBox;
public Object makeObj(final String item) {
return new Object() {
public String toString() {
return item;
}Couple of better ways to populate a combo with items-
public javax.swing.JComboBox makeJComboBox(String[]items) {
javax.swing.ComboBoxModel cbModel = new DefaultComboBoxModel(items);
javax.swing.JComboBox myComboBox = new javax.swing.JComboBox(cbModel);
return myComboBox;
}OR
public javax.swing.JComboBox makeJComboBox(String[]items) {
return new javax.swing.JComboBox(items); -
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 Awt -Event Queue problem
Hi
I've been looking everywhere for a solution to this, but can't seem to find one. I've got a JTable with an underlying model that is being continuously updated (every 100ms or so). Whenever I try to sort the JTable using TableRowSorter while the model is being added to I get
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.Vector.elementAt(Vector.java:430)
at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
I don't understand this as in my custom table model I've added the fireTableChanged etc. in a SwingUtilities.invokeLater( ...) thread.
Has anyone else encountered this problem and found a solution? I'd be really grateful!
ThanksHi
Thanks for responding, I'm still a little confused. I've posted the code below for both the JTable and the TableModel. The tablemodel simply gets values from a vector which is being dynamically updated from outside the table - but whenever the vector is added to
The problem seems to only occur when I press the column header to sort the tables during the updates. My understanding is that the method refresh() should create a threadsafe update of the table - but somehow it refreshes the binding to the tablemodel and during this time the table returns a defaulttablemodel that doesn't correspond to the actual underlying data....I thought this kind of problem would be solved by invoking all updates on the swing event thread, but it seems to still produce the effect and I'm stumped!!
(The data is in an array called turns, and the addElement() in another class calls the refresh() method)
many thanks, in the hope that someone has the kindness and and benevolence to wade through the following code!
public class JContiguousTurnsListTable extends JTable {
private JContiguousTurnsListTableModel jctltm;
public JContiguousTurnsListTable(Conversation c) {
super();
jctltm = new JContiguousTurnsListTableModel(this,c);
this.setModel(jctltm);
setSize();
//this.setAutoResizeMode(AUTO_RESIZE_ALL_COLUMNS);
//this.setAutoCreateRowSorter(true);
TableRowSorter <TableModel> sorter = new TableRowSorter <TableModel>(jctltm);
//sorter.setSortsOnUpdates(true);
this.setRowSorter(sorter);
System.err.println("Setting up ");
private void setSize(){
TableColumn column = null;
for (int i = 0; i <11; i++) {
column = this.getColumnModel().getColumn(i);
if(i==1||i==2||i==3||i==4||i==8||i==9){
column.setPreferredWidth(50);
else if (i==0||i==5){
column.setPreferredWidth(180);
else if (i == 6) {
column.setPreferredWidth(150);
else if(i==10){
column.setPreferredWidth(250);
else
column.setPreferredWidth(100);
//column.setPreferredWidth(100);
//column.setMinWidth(100);
//column.setMaxWidth(100);
public String getColumnName(int column){
return jctltm.getColumnName(column);
public void refresh(){
this.jctltm.refresh();
----------------And the table model:
public class JContiguousTurnsListTableModel extends AbstractTableModel {
private Conversation c;
public JContiguousTurnsListTableModel(JTable jt,Conversation c) {
super();
this.c=c;
public void refresh(){
//System.out.println("Refresh");
SwingUtilities.invokeLater(new Runnable(){public void run(){fireTableDataChanged();fireTableStructureChanged();} });
public boolean isCellEditable(int x, int y){
return false;
public String getColumnName(int column){
if(column==0){
return "Sender";
else if(column==1){
return "Onset";
else if (column==2){
return "Enter";
else if(column ==3){
return "E - O";
else if(column ==4){
return "Speed";
else if(column ==5){
return "Spoof Orig.";
else if(column ==6){
return "Text";
else if(column ==7){
return "Recipients";
else if(column ==8){
return "Blocked";
else if(column ==9){
return "Dels";
else if(column ==10){
return "TaggedText";
else if(column ==11){
return "ContgNo";
else if(column ==12){
return "Inconcistency";
else{
return " ";
public Object getValueAt(int x, int y){
try{
//System.out.println("GET VALUE AT "+x+" "+y);
Vector turns = c.getContiguousTurns();
if(x>=turns.size())return " ";
ContiguousTurn t = (ContiguousTurn)turns.elementAt(x);
if(y==0){
return t.getSender().getUsername();
else if(y==1){
return t.getTypingOnset();
else if(y==2){
return t.getTypingReturnPressed();
else if(y==3){
return t.getTypingReturnPressed()-t.getTypingOnset();
else if(y==4){
long typingtime = t.getTypingReturnPressed()-t.getTypingOnset();
if(typingtime<=0)return 0;
return ((long)t.getTextString().length())/typingtime;
else if(y==5){
return t.getApparentSender().getUsername();
else if(y==6){
return t.getTextString();
else if(y==7){
//System.out.println("GETTINGRECIP1");
Vector v = t.getRecipients();
String names ="";
// System.out.println("GETTINGRECIP3");
for(int i=0;i<v.size();i++){
Conversant c = (Conversant)v.elementAt(i);
// System.out.println("GETTINGRECIP4");
names = names+", "+c.getUsername();
// System.out.println("GETTINGRECIP5");
return names;
else if (y==8){
if (t.getTypingWasBlockedDuringTyping())return "BLOCKED";
return "OK";
else if(y==9){
return t.getNumberOfDeletes();
else if(y==10){
String returnText="";
Vector v = t.getWordsAsLexicalEntries();
for(int i=0;i<v.size();i++){
LexiconEntry lxe= (LexiconEntry)v.elementAt(i);
returnText = returnText+lxe.getWord()+" ("+lxe.getPartOfSpeech()+") ";
return returnText;
else if(y==11){
return t.getNumberOfTurns();
else if(y==12){
// System.out.println("CONTIGUOUS1");
String value ="";
boolean hasSameRecipients = t.getTurnsHaveSameRecipients();
boolean hasSameApparentOrigin = t.getTurnsHaveSameApparentOrigin();
if (hasSameRecipients&hasSameApparentOrigin){
value = "OK";
else if (hasSameRecipients&!hasSameApparentOrigin){
value = "Diff. O";
else if(!hasSameRecipients&hasSameApparentOrigin){
value = "Diff. Recip";
else {
value = "Diff O&R";
//System.out.println("CONTIGUOUS2");
return value;
return " ";
}catch (Exception e){
return "UI ERROR";
public Class getColumnClass(int column) {
Class returnValue;
if ((column >= 0) && (column < getColumnCount())) {
returnValue = getValueAt(0, column).getClass();
} else {
returnValue = Object.class;
return returnValue;
public int getRowCount(){
return this.c.getContiguousTurns().size();
public int getColumnCount(){
return 13;
} -
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
addedKleopatra 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. -
Hello,
I have some problem implementing events associated with JComboBox. My requirement is "the event should get fired only when an item is selected in the combobox". It may occur thet using arrow keys I can traverse all elements in the combobox and on item change the event should not get fired. I tried with itemstatechanged, actionperformed but no result.
Any help will be appreciated.
regards,
RanjanA simple working example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class ComboBoxAction extends JFrame implements ActionListener
private JComboBox comboBox;
public ComboBoxAction()
comboBox = new JComboBox();
comboBox.addActionListener( this );
comboBox.addItem( "Item 1" );
comboBox.addItem( "Item 2" );
comboBox.addItem( "Item 3" );
comboBox.addItem( "Item 4" );
// This prevents action events from being fired when the
// up/down arrow keys are used on the dropdown menu
comboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
getContentPane().add( comboBox );
public void actionPerformed(ActionEvent e)
System.out.println( comboBox.getSelectedItem() );
// make sure popup is closed when 'isTableCellEditor' is used
comboBox.hidePopup();
public static void main(String[] args)
JFrame frame = new ComboBoxAction();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible( true );
}
Maybe you are looking for
-
How to delete the Hierarchy data from Infoobjects.
How to delete the Hierarchy data from Infoobjects. In my case I had 300 records in the corresponding table of info object. When i was trying to delete the hierarchy data, I am getting error message. "Some master data not deleted". Can any one tell me
-
My old 17" MBP (2005) often crashes, freezes or shows grey screen at start up. Also track pad often does not work. I have re fomatted the HD and reinstalled system but to no avail. Genius bar says possible faulty HD, but I suspect logic board. All ch
-
OWB 10gR2 map returning status = Complete and Result = Null in Process Flow
Hi, I have an OWB process flow which invokes an OWB map. There are 2 outgoing transitions attached to the OWB map. 1st transition is a conditinal one (on SUCCESS) and the 2nd one is unconditional transition. I am monitoring the status of process flow
-
How to set field "third party" in the Web Adi, General Ledger - Journals?
Hello, We are trying to find how to set the field "Third Party" in the template WebAdi, and validate data and also can display in the form of general ledger journals. thanks for the collaboration.
-
My FaceTime goes directly to my phone! Please help!
I have a white iPhone 4 and a MacBook Pro. I had facetime set up on my macbook, and got my iPhone months later. Now, my facetime calls go directly to my phone. When I turn the facetime on my phone off to try and get it to work on my computer, it says