JTable adding new row - java

I have a JTable with 5 rows at the time of design. Now i have to add more rows as i go dynamically. I am getting array out of bound exception error when i add more rows. How do i solve this issue ?
item_list = new javax.swing.JTable();
item_list.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null},
{null, null, null},
{null, null, null},
{null, null, null}
},
new String [] {
"No.", "Description", "Cost"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.Float.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
item_list.getColumnModel().getColumn(0).setPreferredWidth(30);
item_list.getColumnModel().getColumn(1).setPreferredWidth(100);
item_list.getColumnModel().getColumn(2).setPreferredWidth(50);
jScrollPane2.setViewportView(item_list);

this works for me
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
public class Grow extends JFrame {
private static final Object[][] rowData = {{"Hello", "World"}};
private static final Object[] columnNames = {"A", "B"};
private JTable table;
private DefaultTableModel model;
public Grow() {
Container c = getContentPane();
c.setLayout(new BorderLayout());
model = new DefaultTableModel(rowData, columnNames);
table = new JTable();
table.setModel(model);
c.add(new JScrollPane(table), BorderLayout.CENTER);
JButton add = new JButton("Add");
c.add(add, BorderLayout.SOUTH);
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
model.addRow(rowData[0]);
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public static void main(String[] args) {
Grow g = new Grow();
g.setLocationRelativeTo(null);
g.setVisible(true);
}
}

I assume You have a table with six column.
Follow this code ,it will append a new row to already existing table
DefaultTableModel defaultModel = (DefaultTableModel) table.getModel();
Vector newRow = new Vector();
newRow.add("Total Amount Spend");
newRow.add(TotalAmt);
newRow.add(Apaid);
newRow.add(Bpaid);
newRow.add(Cpaid);
newRow.add(Dpaid);
defaultModel.addRow(newRow);
Where JTable table = new JTable(data, columnNames);

The DefaultTableModel has an addRow(...) method that you should be using.
If you need more help then post your SSCCE that demonstrates the problem.

Related

Removing combobox as the cell editor of a jtable cell

I have made a combobox as cell editor of a column. I want when i create a new row the cell in that column should not have the combobox as the cell editor and should retain JTextField as the cell editor. Here is what i have done so far.
addRow(mainWindow.salesTable);
final TableColumn items = mainWindow.salesTable.getColumnModel().getColumn(0);
final JTextField tfield = new JTextField();
DefaultCellEditor editorqty = new DefaultCellEditor(tfield);
items.setCellEditor(editorqty);
private static void addRow(JTable table) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
Vector row = new Vector();
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
model.addRow(row);
}
Overriding the getCellEditor(...) method of JTble is one approach:
import java.awt.*;
import java.util.List;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
public class TableComboBoxByRow extends JPanel
{
List<String[]> editorData = new ArrayList<String[]>(3);
public TableComboBoxByRow()
{
setLayout( new BorderLayout() );
// Create the editorData to be used for each row
editorData.add( new String[]{ "Red", "Blue", "Green" } );
editorData.add( new String[]{ "Circle", "Square", "Triangle" } );
editorData.add( new String[]{ "Apple", "Orange", "Banana" } );
// Create the table with default data
Object[][] data =
{
{"Color", "Red"},
{"Shape", "Square"},
{"Fruit", "Banana"},
{"Plain", "Text"}
};
String[] columnNames = {"Type","Value"};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model)
{
// Determine editor to be used by row
public TableCellEditor getCellEditor(int row, int column)
{
int modelColumn = convertColumnIndexToModel( column );
if (modelColumn == 1 && row < 3)
{
JComboBox<String> comboBox1 = new JComboBox<String>( editorData.get(row));
return new DefaultCellEditor( comboBox1 );
}
else
return super.getCellEditor(row, column);
}
};
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane );
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Table Combo Box by Row");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new TableComboBoxByRow() );
frame.setSize(200, 200);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

JTable, JComboBox - problems in showing JComboBox in second column

I have written this simple program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class JcomboboxJtableDemo extends JPanel
implements ActionListener {
private DefaultTableModel tableModel;
JTable table = new JTable (tableModel);
private JScrollPane scrollpaneTable = new JScrollPane( table );
private JPanel PaneBottoniTabella = new JPanel( );
public JcomboboxJtableDemo() {
super(new BorderLayout());
String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
JComboBox comboBox = new JComboBox(petStrings);
comboBox.setSelectedIndex(4);
tableModel = CreateTableModel();
tableModel.insertRow( 0, new Object[] {"Header col1", ""} );
tableModel.insertRow( 0, new Object[] {petStrings[0], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[1], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[2], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[3], ""} );
tableModel.setValueAt("Header col2", 0, 1);
DefaultCellEditor editor = new DefaultCellEditor(comboBox);
table.getColumnModel().getColumn(0).setCellEditor(editor);
table.getColumnModel().getColumn(1).setCellEditor(editor);
//Lay out the demo.
add(comboBox, BorderLayout.PAGE_START);
add(table, BorderLayout.PAGE_END);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
private final DefaultTableModel CreateTableModel () {
DefaultTableModel modello = new DefaultTableModel( new Object[] { "Col1","Col2" }, 0 ) {
#Override
public boolean isCellEditable(int row, int column) {
return true;
}
};
table.setModel(modello);
return modello;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ComboBoxDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new JcomboboxJtableDemo();
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();
}
});
}
}
I you try to run it you will see that there is a problem in showing correctly the JComboBox components in the second column, in the first column the are correctly shown and you can see each selected item as set in the code, instead in the second column there are some problems: none on the relative cell.
Could you tell me why? How can I solve the problem?
Thanks
You're using the same JComboBox component for both ColumnModel columns which in turn share the same ComboBoxModel. Any change in the selected item from one column will be reflected in the other column. Create a second combobox
JComboBox comboBox2 = new JComboBox(petStrings);
...
table.getColumnModel().getColumn(1).setCellEditor(editor2);
so that any changes can occur independently in either column.

Dynamic Creation of JTable (Boolean Truth Tables)

I have a code that generates a truth table for a given Boolean Expression. For example, consider a user-input expression of (A+B)+(C+D). I have a string array headers[] that will store all necessary headers for the truth table.
In this case, it would contain: "A", "B", "C", "D", "A+B", "C+D", "(A+B)+(C+D)"
Then the generated truth table (a 2d int array TruthTable[][]) will contain the following data:
0000000
1000101
0100101
1100101
0010011
1010111
0110111
1110111
0001011
1001111
0101111
1101111
0011011
1011111
0111111
1111111
So the first element of the headers[] array will correspond to the first column of TruthTable[][]. How do I dynamically generate a truth table (using JTable) considering these data?
Create JTable with DefaultTableModel and insert new rows to table model.
Tutorial for it JTable and Model
Simple example for table:
public class Example extends JFrame{
private JTable table;
private DefaultTableModel modelTable;
public Example(){
init();
}
private void init() {
table = new JTable();
table.setGridColor(Color.BLACK);
table.setAutoResizeMode(2);
modelTable = new DefaultTableModel(new Object[][]{}, new String[] {"A", "B", "C"});
table.setModel(modelTable);
Object[][] data = new Object[][]{{"1","2","3"},{"4","5","6"}};
for(int i =0;i<data.length;i++){
modelTable.addRow(data[i]);
}
}
public static void main(String... s){
Example p = new Example();
p.add(new JScrollPane(p.table));
p.pack();
p.setVisible(true);
}
}
#alex2410 has a point when he says to use DefaultTableModel.
If you have some problem with FormLayout, download the JGoodies Form or simple change the layout =)
Maybe that's what You're looking for:
ThruthTablePanel
public class ThruthTablePanel extends JPanel {
private JScrollPane scrollPane;
private JTable table;
/**
* Create the panel.
*/
public ThruthTablePanel() {
initComponents();
}
private void initComponents() {
String columnsLayout = "3dlu, default:grow, 3dlu";
String rowsLayout = "3dlu, default:grow, 3dlu";
setLayout(new FormLayout(columnsLayout, rowsLayout));
scrollPane = new JScrollPane();
add(scrollPane, "2, 2, fill, fill");
Object[] headers = new Object[] { "A", "B", "C",
"D", "A+B", "C+D",
"(A+B)+(C+D)" };
String[] results = new String[] { "0000000", "1000101", "0100101",
"1100101", "0010011", "1010111", "0110111", "1110111",
"0001011", "1001111", "0101111", "1101111", "0011011",
"1011111", "0111111", "1111111" };
DefaultTableModel model = new DefaultTableModel(new Object[][] {}, headers);
model.setRowCount(results.length);
table = new JTable(model);
for (int j = 0; j < results.length; j++) {
for (int i = 0; i < results[j].length(); i++) {
model.setValueAt(results[j].charAt(i), j, i);
}
}
table.setFillsViewportHeight(true);
scrollPane.setViewportView(table);
}
public static void main(String[] args) {
JFrame frm = new JFrame();
frm.setContentPane(new ThruthTablePanel());
frm.setSize(new Dimension(400, 400));
// frm.pack();
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
But, if you have your ThruthTable[][] filled, you can just pass it as a parameter to the model.
Other Solution
DefaultTableModel model = new DefaultTableModel(/* Here you put your ThruthTable Vector */, headers);
table = new JTable(model);

JTable header not showing

JTable header not showing...
My JTable header wont show even if add it into a container like JScrollPane...tell me why is it happen and how can i fix it or debug it.. I search through internet and all they saying is add container to your jtable, i did but still my header are not showing.
public void table(){
try{
rs = stat.executeQuery("SELECT * FROM payments;");
Vector<String> header = new Vector<String>();
header.add("PAYMENT");
header.add("AMOUNT");
header.add("MODIFIER");
header.add("DATE MODIFIED");
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while(rs.next()) {
Vector<Object> row = new Vector<Object>();
row.add(rs.getString("description"));
row.add(rs.getString("amount"));
row.add(rs.getString("remarks"));
row.add(rs.getString("date"));
data.add(row);
} // loop
table = new JTable(data, header);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(table);
panel.add(table.getTableHeader());
//panel.removeAll();
//scroll.add(table);
validate();
}catch(Exception e){
System.out.println("Error in table: "+e);
}//try and catch
}
Start by removing
panel.add(table.getTableHeader());
The JTable is designed to add it's header to the JScrollPane. An instance of a component can only belong to a one parent/container, the above line is removing it from the scrollpane
Also, change this...
panel.add(table);
To
panel.add(scrollPane);
Same problem I have face
You have to add the JTable to the JScrollPane then add JscrollPane to JFrame
e.g.
JTable table = new JTable();
JScrollPane scrollPane= new JScrollPane(table);
frame.add(scrollPane);
Best JTable Example (Working smoothly just paste in editor and execute as Java application) with dynamic data :
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TableTest {
private JFrame frame;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TableTest window = new TableTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TableTest() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
table = new JTable();
DefaultTableModel daDefaultTableModel = new DefaultTableModel(0, 0);
String[] columnNames = new String[] {"Column Header1", "Column Header2", "Column Header3"};
daDefaultTableModel.setColumnIdentifiers(columnNames);
//Dummy data for Table
daDefaultTableModel.addRow(new Object[] {"Test1","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test2","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test3","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test4","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test5","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test6","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test7","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test8","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test9","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test10","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test11","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test12","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test13","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test14","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test15","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test16","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test17","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test18","Test2","Test3"});
daDefaultTableModel.addRow(new Object[] {"Test19","Test2","Test3"});
table.setModel(daDefaultTableModel);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(10, 38, 414, 212);
frame.getContentPane().add(scrollPane);
}
}

Spacing JTable header

I know spacing JTable cells are pretty straight forward as shown below;
int gapWidth = 10;
int gapHeight = 5;
table.setIntercellSpacing(new Dimension(gapWidth, gapHeight));
Spacing like this doesn't seems to affect the tables header. Is there a way to space the header with the same dimension?
Easiest way could be to set EmptyBorders to the JTableHeader inside the TableCellRenderer
The code above does my spacing, but the alignment of header and the actual row cell values looks slighly off - as a result of spacing only placed on cells but not the header.
I added a SSCCE (3mins 27seconds inc. uploading here)
from code
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class IntercellSpacingTableHeader {
private JFrame frame = new JFrame("Table Demo");
private String[] columnNames = {"String", "Integer", "Float", "Double"};
private Object[][] data = {
{"aaa", new Integer(12), new Float(12.15), new Double(100.05)},
{"bbb", new Integer(5), new Float(7.154), new Double(6.1555)},
{"CCC", new Integer(92), new Float(0.1135), new Double(3.1455)},
{"ddd", new Integer(12), new Float(31.15), new Double(10.05)},
{"eee", new Integer(5), new Float(5.154), new Double(16.1555)},
{"fff", new Integer(92), new Float(4.1135), new Double(31.1455)}};
private TableModel model = new DefaultTableModel(data, columnNames) {
private static final long serialVersionUID = 1L;
#Override
public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
private JTable table = new JTable(model);
public IntercellSpacingTableHeader() {
int gapWidth = 10;
int gapHeight = 5;
table.setIntercellSpacing(new Dimension(gapWidth, gapHeight));
table.setRowHeight(20);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scroll = new JScrollPane(table);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scroll);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new IntercellSpacingTableHeader();
}
});
}
}

Categories

Resources