Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

JTable.addRow(Vector)

376 views
Skip to first unread message

RVince

unread,
Jan 22, 2010, 2:33:37 PM1/22/10
to
I jave a JTable on a JPanel which has a JButton to add a row to the
table -- the JButton implements actionListener, with the following
code to add the row:

Vector rowData = new Vector();
rowData.add("");
rowData.add(Double.toString(account.getDefaultallocation()));
rowData.add(Integer.toString(minlotsize));
rowData.add("0");
rowData.add("0");
rowData.add("0");
DefaultTableModel model = (AccountSlotsTableModel)
iam.accountSlots.table.getModel();
try{
model.addRow(rowData);
}catch(Exception ex){
log.error(getStackTrace(ex));
}

My table initially has NO rows. So,the first row, and all subsequent
rows, are to be created by hitting this JButton. However, when the
JButton is clicked, the try-catch catches the followign stack trace:

java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
at java.util.Vector.elementAt(Unknown Source)
at javax.swing.table.DefaultTableModel.justifyRows(Unknown Source)
at javax.swing.table.DefaultTableModel.insertRow(Unknown Source)
at javax.swing.table.DefaultTableModel.addRow(Unknown Source)
at com.leveragespacemodel.Gravity.actionPerformed(Gravity.java:967)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown
Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown
Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown
Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)


I am at a complete loss as to how this can occur, or how to stop it.
Does anyone have any insight here on this? Below, I have posted my
JTable on TableModel code corresponding to this problem. Thans so
much, RVince.

import java.awt.LayoutManager;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.Vector;

public class AccountSlots extends JPanel {
public JTable table;

/** are we setting values based uopn a table read right now? */
private boolean reading;

public AccountSlots(LayoutManager arg0) {
super(arg0);
}

public AccountSlots(boolean arg0) {
super(arg0);
}

public AccountSlots(LayoutManager arg0, boolean arg1) {
super(arg0, arg1);
}

public AccountSlots() {
super(new GridLayout(1, 0));
table = new JTable(new AccountSlotsTableModel());

TableColumn col = table.getColumnModel().getColumn(0);
col.setWidth(100);
col.setPreferredWidth(100);
col = table.getColumnModel().getColumn(1);
col.setWidth(50);
col.setPreferredWidth(50);
col = table.getColumnModel().getColumn(2);
col.setWidth(50);
col.setPreferredWidth(50);
col = table.getColumnModel().getColumn(3);
col.setWidth(50);
col.setPreferredWidth(50);
col = table.getColumnModel().getColumn(4);
col.setWidth(50);
col.setPreferredWidth(50);
col = table.getColumnModel().getColumn(5);
col.setWidth(50);
col.setPreferredWidth(50);

table.setPreferredScrollableViewportSize(new Dimension(325, 70));
table.setFillsViewportHeight(true);

// Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);

// Add the scroll pane to this panel.
add(scrollPane);
}

public void setEditorsandRenderers(Object [] o) {
String[] values = new String[o.length];
for (int i=0;i<o.length;i++){
values[i]=o[i].toString();
}
// Set the combobox editor on the 1st visible column
int vColIndex = 0;
TableColumn col = table.getColumnModel().getColumn(vColIndex);
col.setCellEditor(new MyComboBoxEditor(values));
// If the cell should appear like a combobox in its
// non-editing state, also set the combobox renderer
col.setCellRenderer(new MyComboBoxRenderer(values));
}

public class MyComboBoxRenderer extends JComboBox implements
TableCellRenderer {
public MyComboBoxRenderer(String[] 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;
}
}

public class MyComboBoxEditor extends DefaultCellEditor {
public MyComboBoxEditor(String[] items) {
super(new JComboBox(items));
}
}

class AccountSlotsTableModel extends DefaultTableModel {
private String[] columnNames = { I18N.rb.getString("component"),
I18N.rb.getString("allocation"), I18N.rb.getString("minlotsize"),
I18N.rb.getString("nmbrbreaks"), I18N.rb.getString("volatility"),
I18N.rb.getString("lastdayonfile"), I18N.rb.getString("quantity"),
I18N.rb.getString("avgprice") };
private Vector data;

public void setData(Vector data) {
this.data = data;
}

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

public int getRowCount() {
if(data==null){
return 0;
}
return data.size();
}

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

public Object getValueAt(int row, int col) {
if (row >= data.size()) {
return null;
}
Slot slot = (Slot) data.get(row);
switch (col) {
case 0:
return slot.issue.componentName;
case 1:
return slot.allocation;
case 2:
return slot.minlotsize;
case 3:
return slot.nmbrbreaks;
case 4:
return slot.issue.volatility;
case 5:
return slot.issue.lastprice;
case 6:
return slot.quantity;
case 7:
return slot.avgprice;
default:
return null;
}
}

/*
* JTable uses this method to determine the default renderer/ editor
for
* each cell. If we didn't implement this method, then the last
column
* would contain text ("true"/"false"), rather than a check box.
*/
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}

/*
* Don't need to implement this method unless your table's editable.
*/
public boolean isCellEditable(int row, int col) {
// Note that the data/cell address is constant,
// no matter where the cell appears onscreen.
switch (col) {
case 0:
return true;
case 1:
return true;
case 2:
return true;
case 3:
return true;
case 4:
return false;
case 5:
return false;
case 6:
return false;
case 7:
return false;
default:
return false;
}
}

/*
* Don't need to implement this method unless your table's data can
* change.
*/
public void setValueAt(Object value, int row, int col) {
Slot slot = (Slot) data.get(row);
switch (col) {
case 0:
slot.issue.componentName = (String) value;
case 1:
if (!isReading()) {
slot.allocated = true;
}
slot.allocation = ((Double) value).doubleValue();
case 2:
slot.minlotsize = ((Integer) value).intValue();
case 3:
slot.nmbrbreaks = ((Integer) value).intValue();
case 6:
slot.quantity = ((Integer) value).intValue();
case 7:
slot.avgprice = ((Double) value).doubleValue();
default:
break;
}
fireTableCellUpdated(row, col);
}

}

public boolean isReading() {
return reading;
}

public void setReading(boolean reading) {
this.reading = reading;
}

/**
* Create the GUI and show it. For thread safety, this method should
be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("TableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create and set up the content pane.
AccountSlots newContentPane = new AccountSlots();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);

// Display the window.
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

}

John B. Matthews

unread,
Jan 22, 2010, 5:37:21 PM1/22/10
to
In article
<6357aace-f0c6-4256...@r24g2000yqd.googlegroups.com>,
RVince <rvin...@hotmail.com> wrote:

> I jave a JTable on a JPanel which has a JButton to add a row to the
> table -- the JButton implements actionListener, with the following
> code to add the row:
>
> Vector rowData = new Vector();
> rowData.add("");
> rowData.add(Double.toString(account.getDefaultallocation()));
> rowData.add(Integer.toString(minlotsize));
> rowData.add("0");
> rowData.add("0");
> rowData.add("0");
> DefaultTableModel model = (AccountSlotsTableModel)

> ...


> My table initially has NO rows. So,the first row, and all subsequent
> rows, are to be created by hitting this JButton. However, when the
> JButton is clicked, the try-catch catches the followign stack trace:
> java.lang.ArrayIndexOutOfBoundsException: 0 >= 0

Absent a complete example, it's hard to tell. I'm surprised that
your Vector has six elements, while your data model has eight.

At any rate, here's an example that shows a working add button:

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import javax.swing.table.DefaultTableModel;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JButton;

public class AccountSlots extends JPanel {

private final JTable table;
private final AccountSlotsTableModel model;
private static final Vector<String> rowData = new Vector<String>();
static {
rowData.add("0");
rowData.add("1");
rowData.add("2");
rowData.add("3");
rowData.add("4");
rowData.add("5");
rowData.add("6");
rowData.add("7");
}

public AccountSlots() {
super(new GridLayout(1,0));
model = new AccountSlotsTableModel();
table = new JTable(model);


JScrollPane scrollPane = new JScrollPane(table);

this.add(scrollPane);
}

class AccountSlotsTableModel extends DefaultTableModel {

private String[] columnNames = {
"component", "allocation", "minlotsize", "nmbrbreaks",
"volatility","lastdayonfile", "quantity", "avgprice"};

@Override


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

@Override


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

private static void createAndShowGUI() {


JFrame frame = new JFrame("TableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final AccountSlots slots = new AccountSlots();
JPanel panel = new JPanel();
JButton addBtn = new JButton("Add");
addBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
slots.model.addRow(rowData);
}
});
panel.add(addBtn);
frame.add(slots, BorderLayout.CENTER);
frame.add(panel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {
@Override


public void run() {
createAndShowGUI();
}
});
}
}

--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>

progra...@gmail.com

unread,
Apr 25, 2013, 8:33:43 PM4/25/13
to
0 new messages