im developing an application and i'm trying to insert a new row into jtable
i've followed this tutorial , the user can add/remove product information(row) through a form.the database & the table should be updated ,the remove function works well but i can't insert new row into the table .
Note:- when i close the app & run it again the table is updated
and here's my code
public class TableModel extends AbstractTableModel {
Object[] values;
String[] columnNames;
private ArrayList productInfoList;
public TableModel() {
super();
Session session = HibernateUtil.openSession();
Query q = session.createQuery("from Product");
productInfoList = new ArrayList(q.list());
session.close();
}
#Override
public int getRowCount() {
//return dataVec.size();
return productInfoList.size();
}
#Override
public int getColumnCount() {
return 9;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Product product = (Product) productInfoList.get(rowIndex);
values = new Object[]{product.getProdectId(),
product.getProductName(), product.getProductBuyingPrice(),
product.getProductSalesPrice(), product.getCategory(), product.getBrand(),
product.getProductQuantity(), product.getProductMinQuantity(), product.getProductDescription()};
return values[columnIndex];
}
#Override
public String getColumnName(int column)
{
columnNames=new String[]{"id","Product Name","Buy price","Sale price ","Category",
"Brand","Quantatity","Min Quantatity","Description"};
return columnNames[column];
}
public void removeRow(int rowIndex) {
productInfoList.remove(rowIndex);
fireTableRowsDeleted(rowIndex, rowIndex);
}
public void insertRow(int rowIndex,Product everyRow) {
productInfoList.add(rowIndex, everyRow);
fireTableRowsInserted(rowIndex, rowIndex);
}
}
this is the code that i try to insert row with
public void AddRow() {
int position = jTable1.getRowCount() - 1;
System.out.println(position); // test
Product product = new Product();
tablemodel.insertRow(position, product);
}
Please help me as i'm get tired of it :|
Your TableModel is storing a Product object in an ArrayList.
So, when you want to add a new row to the model you need to create a new Product object and add the Product to the ArrayList.
Also, you don't need to invoke table.repaint(), the insertRow(...) method is invoking the fireTableRowsInserted(...) method which will tell the table to repaint the row.
Related
What I am trying to do is to populate a JTable from an ArrayList.
The array list is a type Record which I have defined below:
public class Record {
int Parameter_ID;
int NDC_Claims;
int NDC_SUM_Claims;
public Record(int parameter, int claims, int ndc_sum_claims){
Parameter_ID = parameter;
NDC_Claims = claims;
NDC_SUM_Claims = ndc_sum_claims;
}
public Record() {
// TODO Auto-generated constructor stub
}
I don't know how to populate the table with the column headers as well. This is what I have so far:
DefaultListModel listmodel = new DefaultListModel();
ArrayList<Record> test = new ArrayList<Record>();
DefaultTableModel modelT = new DefaultTableModel();
Object data1[] = new Object[3];
for(int i=0; i<test.size();i++){
data1[0] = test.get(i).Parameter_ID;
data1[1] = test.get(i).NDC_SUM_Claims;
data1[2] = test.get(i).NDC_Claims;
modelT.addRow(data1);
}
table_1 = new JTable(modelT, columnNames);
contentPane.add(table_1, BorderLayout.CENTER);
contentPane.add(table_1.getTableHeader(), BorderLayout.NORTH);
Nothing is outputted. Any help would be great!
Well you need to start by reading the API. You can't program if you don't read the API first.
DefaultTableModel modelT = new DefaultTableModel();
When you read the API what does that constructor do? It creates a model with 0 rows and 0 columns. You will want to create a model with 3 columns and 0 rows so that you can add rows of data to the model. Read the DefaultTableModel API
table_1 = new JTable(modelT, columnNames);
What does that statment do? I don't see a constructor that allows you to specify a model and column names so how does your code compile. You just want to create the table using
the model.
contentPane.add(table_1, BorderLayout.CENTER);
contentPane.add(table_1.getTableHeader(), BorderLayout.NORTH);
The table should be added to the viewport of a JScrollPane. The header will then be displayed as the column header of the scroll pane.
Read the JTable API. The API also has a link to the Swing tutorial on How to Use Tables you need to read for the basics.
ArrayList<Record> test = new ArrayList<Record>();
You create an empty ArrayList. So what do you expect to happen when you iterate through the loop? How can you add data to the model if there is no data in the ArrayList?
Also, did you search the forum/web for examples that use the DefaultTableModel or JTable classes. Those examples will help you write your code.
You can create a custom AbstractTableModel and then create a JTable using that model.
Here is a class handling ArrayList of Arrays:
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class DataTableModel<T> extends AbstractTableModel {
/**
* Benjamin Rathelot
*/
private static final long serialVersionUID = -7361470013779016219L;
private ArrayList<T[]> data = new ArrayList<T[]>();
private String[] tableHeaders;
public DataTableModel(ArrayList<T[]> data, String[] headers) {
super();
this.data = data;
this.tableHeaders = headers;
}
#Override
public int getRowCount() {
return data.size();
}
#Override
public int getColumnCount() {
if(data.size()>0) return data.get(0).length;
return 0;
}
#Override
public Object getValueAt(int arg0, int arg1) {
// TODO Auto-generated method stub
if(data.size()>=arg0) {
if(data.get(arg0).length>=arg1) {
return data.get(arg0)[arg1];
}
}
return null;
}
#Override
public String getColumnName(int columnIndex) {
return tableHeaders[columnIndex];
}
}
I've added a checkbox to rows on my table, but unfortunately I'm unable to select/deselect them.
I'm using an own Table Model that I got on internet.
Table Model's code:
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
/**************/
public class ModeloTabela extends AbstractTableModel {
private ArrayList linhas = null;
private String [] colunas = null;
public ModeloTabela(ArrayList lin, String[] col){
setLinhas(lin);
setColunas(col);
}
public ArrayList getLinhas(){
return linhas;
}
public void setLinhas(ArrayList dados){
linhas = dados;
}
public String[] getColunas(){
return colunas;
}
public void setColunas(String [] nomes){
colunas = nomes;
}
public int getColumnCount(){
return colunas.length;
}
public int getRowCount(){
return linhas.size();
}
public String getColumnCount (int numCol){
return colunas[numCol];
}
public Object getValueAt(int numLin, int numCol){
Object[] linha = (Object[])getLinhas().get(numLin);
return linha[numCol];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col) {
return true;
}
}
And this Method will fill the Table:
public void PreencheTabela(String sql, JTable jt1, JTextField j1){
c.conexao();
ArrayList dados = new ArrayList();
String [] Colunas = new String[] {"STATUS", "ID", "FABRICANTE", "FORNECEDOR", "NOME", "CATEGORIA", "DATA DO CADASTRO", " CODIGO DE BARRAS", "QUANTIDADE"};
c.executaSQL(sql);
try {
c.rs.first();
do{
dados.add(new Object[]{c.rs.getInt("prod_id"),c.rs.getString("prod_fabricante"),c.rs.getString("prod_fornecedor"),c.rs.getString("prod_nome"),
c.rs.getString("prod_categoria"),c.rs.getDate("prod_datacadastro"),c.rs.getString("prod_codbarras"), c.rs.getInt("est_quantidade")});
j1.setBorder(BorderFactory.createLineBorder(Color.black));
}while(c.rs.next());
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro!\n"+ex.getMessage());
}
ModeloTabela modelo = new ModeloTabela(dados, Colunas);
jt1.setModel(modelo);
}
Which code can I use? Also, where do I put this code??
but unfortunately I'm unable to select/deselect them.
You didn't implement the setValueAt(...) method in your TableModel so the value can never be updated in the model.
I'm using an own Table Model that I got on internet.
Why are you using a custom TableModel? You can use the DefaultTableModel. It implements the setValueAt(...) method correctly. It also has an addRow(..) method that allows you to dynamically update the model.
Are you actually storing Boolean objects in the TableModel? I don't see you using getBoolean() to get the data from your ResultSet. The default renderers/editors for a check box will only be used when you have Boolean data in the column.
Also take a look at: Can't create column with checkboxes in JTable for a better implementation of the getColumnClass() method.
If you insist on using your custom TableModel, then take a look at the Swing tutorial link you were given in your last question. It shows and example of implementing the setValueAt() method.
I have An Object called Student and in this Object i have A arrayList of Object That Contains material(name,note)
Public Class Student{
private String StudentFirstName;
private String StudentLastName;
private List<Material> materials;
}
public Class Material{
String String materialName;
String Float note;
}
i want to display All Data in Jtable like that:
StudentFirstName:Jack StudentLastName:Dupont materialName:Math note:15
StudentFirstName:Jack StudentLastName:Dupont materialName:french note:12
StudentFirstName:Jack StudentLastName:Dupont materialName:Math note:15
StudentFirstName:Jack StudentLastName:Dupont materialName:Sport note:10
StudentFirstName:peter StudentLastName:sanchez materialName:Math note:14
StudentFirstName:peter StudentLastName:sanchez materialName:french note:17
StudentFirstName:peter StudentLastName:sanchez materialName:Arabic note:11
this Is My Table Model
package com.orange.tableModel;
public class DataTableModel extends AbstractTableModel {
String[] entete = {"StudentFisrtName", "StudentLastNameName",
"Mat erialName", "MaterialNote"};
List<Student> allStudents;
public DataTableModel() {
allStudents = new ArrayList<>();
}
#Override
public int getRowCount() {
return allStudents.size();
}
#Override
public int getColumnCount() {
return entete.length;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0: {
return allStudents.get(rowIndex).getStudentFirstName();
}
case 1: {
return allStudents.get(rowIndex).getStudentLastName();
}
case 2: {
return allStudents.get(rowIndex).materials(rowIndex).getMaterialName();
}
case 3: {
return allStudents.get(rowIndex).materials(rowIndex).getNote();
}
default:
throw new IllegalArgumentException();
}
}
#Override
public String getColumnName(int column) {
return entete[column];
}
}
Jtable dataTable=new Jtable();
dataTable.setModel(new DataTableModel()); `
So the result Is:
StudentFirstName:Jack StudentLastName:Dupont materialName:Math note:15
StudentFirstName:peter StudentLastName:sanchez materialName:Math note:14
I'll do something like this:
First of all, the method getRowCount()
returns allStudents.size()
and actually this value is two, so you tell to your DataTableModel that your tables contains 2 rows and that is incorrect.
Try to modify this method doing something like that:
#Override
public int getRowCount() {
int row_count=0;
for (int i=0; i<allStudents.size(); i++) {
row_cont+=allStudents.get(i).getMaterials().size();
}
in this way, you'll force the jtable to have how many rows you need. Next, you should write a smarter method getValueAt. You should maintain a variable (e.g. count_row) that tells you how many rows are dedicated to the same Student and doing a control over that, for example
if (count_row< allStudents.get(rowIndex).getMaterials().size()) {
//show information of the same Student but with materials(count_row)
}
or something like this. In a nutshell, you tell to your jTable to display the same Student until every Material is displayed.
You can solve this problem following another way: you should create an ArrayList with redundant data, for example doing something like this
Student A_B=new Student("A","B","Math",12); //first_name, last_name, subject, note
Student A_B=new Student("A","B","History",4);
Student B_C=new Student("B","C","Geograph",10);
Hope that this can be to you an useful tip. Hi !!
i've created a swing jtable with some data from a database. in web apps, usually i display the data to the user and set it's unique database id in as an html tag attribute, so that when the user clicks on say edit, i pick the element's hidden db unique id from the html tag attribute using javascript. That way, i know which data user wants to edit and i can update it in the database using it's unique primary key.
Now how do i do this in a desktop app writen in java using swing.
Put it more clearly, am looking for an equivalent of;
<table>
<tr id=1 ><td>david</td></tr>
<tr id=2 ><td>peter</td></tr>
<tr id=3 ><td>Timothy</td></tr>
</table>
Hope am clear. Thanks
Your TableModel which backs up the JTable can contain anything you like. It can for example contain objects like
class User{
public final int ID;
public String name;
public int age;
}
and you can then choose to only include certain values in your JTable
class MyTableModel implements TableModel{
private List<User> users;
#Override
public Object getValueAt(int row, int column){
if ( column == 0 ){
return users.get( row ).name;
}
}
}
But since your TableModel still contains the full User objects, you have all the required information.
Note: the above code will not compile due to missing methods, ... . It is just here to illustrate what I mean
The equivalent is an AbstractTableModel subclass instance backed by a List<YourObject>. When you edit a row, you get the index of the selected row from the table (JTable.getSelectedRow()), then you convert this row index to a model row index (JTable. convertRowIndexToModel()), then you ask your model for the YourObject at this row, and you get the ID of YourObject directly from the object.
Read the JTable tutorial for more details.
public class UserTableModel extends AbstractTableModel {
private List<User> users;
public UserTableModel(List<User> users) {
this.users = new ArrayList<User>(users);
}
#Override
public int getRowCount() {
return users.size();
}
#Override
public int getColumnCount() {
return 1;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex == 0) {
return users.get(rowIndex).getName();
}
else {
throw new IllegalArgumentException();
}
}
#Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex == 0) {
return String.class;
}
else {
throw new IllegalArgumentException();
}
}
public User getUserAtRow(int rowIndex) {
return users.get(rowIndex);
}
}
I have to display authors on a table and I made only 1 column for it. I have used a jtable before but with 2d arrays and multiple columns. I'm having problems with this one.The 'authors name' are stored in mysql.
tblAuthor.setModel(new javax.swing.table.DefaultTableModel(
authorData,new String[]{"Name"}){
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
#Override
public Class getColumnClass(int columnIndex) {
return String.class;
}
})
}
this one is how i retrieve the authors
private Object[][] getAuthors(int id) throws SQLException{
sql="SELECT authorName FROM tbl_textbook as b,tbl_txauthor as a where a.bookID=b.bookID AND a.bookID="+id;
rs=stm.executeQuery(sql);
rs.next();
Object authors[][] = new String[countAuthors(id)][1];
if(rs.getRow()!=0)
authors=new String[rs.getInt(1)][1];
i=0;
while(rs.next()){
authors[i][1]=rs.getString(1);
i++;
}
return authors;
}
I'm a noob so please help.thank you
try
authors[i][0]=rs.getString(1);
java array are 0 based unlike resultset that are 1 based