Add a row to JTable and Database (phpMyAdmin)? - java

initComponents();
try {
ResultSet res = statement.executeQuery("SELECT * FROM banh");
ResultSetMetaData RSMD = res.getMetaData();
NumberOfColumns = RSMD.getColumnCount();
AttributeNames = new String[NumberOfColumns];
for(int i=0;i<NumberOfColumns;i++)
AttributeNames[i]=RSMD.getColumnName(i+1);
MyArray=new Object[10000][NumberOfColumns];
int R=0;
while(res.next()) {
for(int C=1; C<=NumberOfColumns;C++)
MyArray[R][C-1]=res.getObject(C);
R++;
}
res.close();
NumberOfRows=R;
Object[][] TempArray=MyArray;
MyArray=new Object[NumberOfRows][NumberOfColumns];
for(R=0;R<NumberOfRows;R++)
for(int C=0;C<NumberOfColumns;C++)
MyArray[R][C]=TempArray[R][C];
TableData.setModel(new MyTableModel());
TableData.setVisible(true);
}
catch(Exception e)
{
e.printStackTrace();
}
public void initComponents()
{
model = new DefaultTableModel (new Object [][]
{
{null},
{null},
{null},
{null}
},
new String [] {""}
) {
Class[] types = new Class [] {java.lang.Object.class};
boolean[]canEdit=new boolean[]{false};
public Class getColumnClass(int columnIndex)
{
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return canEdit [columnIndex];
}
};
TableData.setModel(model);
JScrollPane ScrollPane1 = new JScrollPane(TableData);
ScrollPane1.setBounds(30,170,950,290);
Frame.add(ScrollPane1,BorderLayout.CENTER);
}
I show my Database to JTable by this way, I found it on Internet, it's not mine and it's work. But now I don't know how to add row to JTable and Database, I've found many website but no use (PreparedStatement, executeUpdate...). Can anyone help me about this because I've just learnt. Thank You !

That is a poor example to use:
Variable names should NOT start with an upper case character.
Hardcoding the array size to support 10,000 rows is the wrong approach. You can also use Vector which are dynamic.
Instead check out the Table From Database Example code found in Table From Database. This example uses Vectors which will grow depending on the number of rows found in the ResultSet.
I don't know how to add row to JTable and Database
You can use the addRow(...) method of the DefaultTableModel to add data dynamically. Read the API or search the forum/web for examples that use the addRow(...) method.
For database inserts you can start with the tutorial on JDBC Database Access.

Related

JTable showing only 1 row despite having more than 1 row count

I'm trying to load some data from a database (I use Oracle's SQL Developer) into a JTable in java. I put the data from the database in a Vector of Vector, this is my load method which I put in a class called DBJobs:
public Vector load() {
try {
Vector tableData = new Vector();
Conn con = new Conn();
con.openConn();
con.statement = con.dbConn.createStatement();
ResultSet rs = con.statement.executeQuery("Select * from Jobs");
while (rs.next()) {
Vector<Object> row = new Vector<Object>();
row.add(rs.getString("Job_ID"));
row.add(rs.getString("Job_Title"));
row.add(rs.getString("Parent_Job_ID_1"));
row.add(rs.getString("Parent_Job_ID_2"));
row.add(rs.getString("Description"));
tableData.add(row);
}
con.closeConn();
return tableData;
} catch (SQLException ex) {
ex.printStackTrace();
return null;
}
}
Then I tried populating them into a JTable which I've made with an editor in another class:
private void populateJobsTable() {
Vector<String> tableHeader = new Vector<String>();
tableHeader.add("Job ID");
tableHeader.add("Job Name");
tableHeader.add("Parent Job ID 1");
tableHeader.add("Parent Job ID 2");
tableHeader.add("Description");
Vector tableData = dbJobs.load();
tblJobs.setModel(new DefaultTableModel(tableData, tableHeader));
}
But all I can see is 1 row of data in the table. I've tried printing how many data the Vector has and how many rows the Table has and they're both returning 49, which is the amount of data I have in my database. So why is my table only showing 1 data?
Edit:
I think this is the code generated to make the JTable:
tblJobs = new javax.swing.JTable();
tblJobs.setFont(new java.awt.Font("Tempus Sans ITC", 0, 14)); // NOI18N
tblJobs.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null}
},
new String [] {
"Job Name"
}
) {
Class[] types = new Class [] {
java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tblJobs.setPreferredSize(new java.awt.Dimension(225, 16));
jScrollPane5.setViewportView(tblJobs);
if (tblJobs.getColumnModel().getColumnCount() > 0) {
tblJobs.getColumnModel().getColumn(0).setResizable(false);
}
First of all that is NOT a MCVE. How is that code complete? How can we compile and test that code? Did you not read my comment???
I would suggest you get rid of the IDE and learn how to create GUIs manually. What is the point of the IDE generating JTable with a custom TableModel. That code is completely useless since you then use create your own TableModel and use the setModel(...) method which will replace the model created by the IDE.
tblJobs.setPreferredSize(new java.awt.Dimension(225, 16));
The above code looks suspicious. You should not be setting a preferred size on a Swing component. The size of the table looks like it will only display one row at a time.
It that is not the problem then I will have no more suggestion until a proper MCVE is posted. Every question should have a MCVE so we don't spend time guessing what you may or may not be doing.

Insert a row to Database and Table? [duplicate]

initComponents();
try {
ResultSet res = statement.executeQuery("SELECT * FROM banh");
ResultSetMetaData RSMD = res.getMetaData();
NumberOfColumns = RSMD.getColumnCount();
AttributeNames = new String[NumberOfColumns];
for(int i=0;i<NumberOfColumns;i++)
AttributeNames[i]=RSMD.getColumnName(i+1);
MyArray=new Object[10000][NumberOfColumns];
int R=0;
while(res.next()) {
for(int C=1; C<=NumberOfColumns;C++)
MyArray[R][C-1]=res.getObject(C);
R++;
}
res.close();
NumberOfRows=R;
Object[][] TempArray=MyArray;
MyArray=new Object[NumberOfRows][NumberOfColumns];
for(R=0;R<NumberOfRows;R++)
for(int C=0;C<NumberOfColumns;C++)
MyArray[R][C]=TempArray[R][C];
TableData.setModel(new MyTableModel());
TableData.setVisible(true);
}
catch(Exception e)
{
e.printStackTrace();
}
public void initComponents()
{
model = new DefaultTableModel (new Object [][]
{
{null},
{null},
{null},
{null}
},
new String [] {""}
) {
Class[] types = new Class [] {java.lang.Object.class};
boolean[]canEdit=new boolean[]{false};
public Class getColumnClass(int columnIndex)
{
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return canEdit [columnIndex];
}
};
TableData.setModel(model);
JScrollPane ScrollPane1 = new JScrollPane(TableData);
ScrollPane1.setBounds(30,170,950,290);
Frame.add(ScrollPane1,BorderLayout.CENTER);
}
I show my Database to JTable by this way, I found it on Internet, it's not mine and it's work. But now I don't know how to add row to JTable and Database, I've found many website but no use (PreparedStatement, executeUpdate...). Can anyone help me about this because I've just learnt. Thank You !
That is a poor example to use:
Variable names should NOT start with an upper case character.
Hardcoding the array size to support 10,000 rows is the wrong approach. You can also use Vector which are dynamic.
Instead check out the Table From Database Example code found in Table From Database. This example uses Vectors which will grow depending on the number of rows found in the ResultSet.
I don't know how to add row to JTable and Database
You can use the addRow(...) method of the DefaultTableModel to add data dynamically. Read the API or search the forum/web for examples that use the addRow(...) method.
For database inserts you can start with the tutorial on JDBC Database Access.

Adding data to jTable from Database (via Netbeans) no errors, but table disappears

somehow in debugging data is fully retrieved and resultModel actually has got column names, and data for rows. Although when compiled and ran in Netbeans after a search, table disappears, no data is shown even column names. Here is the code:
private void search(){
String[][] rowData = new String[0][4];
String[] columns = {"appointmentid", "fname", "lname", "registration", "make", "model", "engine", "year", "mileage", "type", "date", "time"};
resultModel = new DefaultTableModel(rowData,columns);
add(new JScrollPane(jTable1));
jTable1 = new JTable(resultModel);
jTable1.setAutoCreateRowSorter(true);
try{
Model_Customer[] appointment = Controller_ManageCustomer.FindCustomers(Searchtxt.getText());
resultModel.setRowCount(0);
for(int i = 0; i < appointment.length; i++)
resultModel.insertRow(i,new Object[]{appointment[i].GetID(),appointment[i].GetFName(), appointment[i].GetLName(), appointment[i].GetRegistration(), appointment[i].GetMake(), appointment[i].GetModel(), appointment[i].GetEngine(), appointment[i].GetYear(), appointment[i].GetMileage(), appointment[i].GetType(), appointment[i].GetDate(), appointment[i].GetTime()});
}catch(Exception ex){
JOptionPane.showMessageDialog(this,ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
}
}
DefaultTableModel resultModel
It could just be me...but this looks very suspicious...
add(new JScrollPane(jTable1));
jTable1 = new JTable(resultModel);
Not to mention, you go a build and nice new DefaultTableModel but don't actually apply it to anything that is actually on the screen...
Try something more like...
resultModel = new DefaultTableModel(rowData,columns);
try{
Model_Customer[] appointment = Controller_ManageCustomer.FindCustomers(Searchtxt.getText());
resultModel.setRowCount(0);
for(int i = 0; i < appointment.length; i++) {
resultModel.insertRow(i,new Object[]{appointment[i].GetID(),appointment[i].GetFName(), appointment[i].GetLName(), appointment[i].GetRegistration(), appointment[i].GetMake(), appointment[i].GetModel(), appointment[i].GetEngine(), appointment[i].GetYear(), appointment[i].GetMileage(), appointment[i].GetType(), appointment[i].GetDate(), appointment[i].GetTime()});
}
if (jTable1 == null) {
jTable1 = new JTable(resultModel);
add(new JScrollPane(jTable1));
} else {
jTable1.setModel(resultModel);
}
}catch(Exception ex){
JOptionPane.showMessageDialog(this,ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
}
Now, personally, I would simply create the JTable and add it to the screen, and leave it alone, and simply change the TableModel when ever you wanted to update it's content...
Swing uses a form of the MVC paradigm, which means it separates the view from the model, meaning that when you want to change what the JTable is showing (the view), you simply change the model...

Trying to create a JTable with 2D vector and string array header, how do I do it?

I'm returning errors from JTable inserting a 2D vector and a String[] as header...
try
{
refreshVector();
}
catch (Exception j)
{
throw j;
}
String[] headers = {"ID","Brand", "Item", "Details", "Qty", "Code", "re-order"};
JTable tbl_display = new JTable(data, headers);
JScrollPane scrollpane = new JScrollPane(tbl_display);
scrollpane.setBounds(120,120,600,300);
refreshVector method contains...
public void refreshVector() throws Exception
{
dbconnect conn = new dbconnect();
try
{
conn.connect();
}
catch (Exception p)
{
throw p;
}
rs = conn.getData();
while(rs.next())
{
Vector<Object> vec = new Vector<Object>();
vec.add(rs.getString("ID_product"));
vec.add(rs.getString("brand"));
vec.add(rs.getString("description"));
vec.add(rs.getString("details"));
vec.add(rs.getString("quantity"));
vec.add(rs.getString("product_code"));
vec.add(rs.getString("reorder"));
data.addElement(vec);
}
}
Do I have to use a table model? I'm just trying to create a simple table displaying the results of my search in the database. Is there a way to go about this without going into table models and use the standard table constructor. Thank you.
Do I have to use a table model?
Yes, the relevant tutorial includes several examples. In the particular case of database access, consider SwingWorker, as outlined here.
As an aside, use a layout manager rather than setBounds().

problem with adding data from DB to jtable

i want to add all my data from DB to jtable, but using this code i get only the last row from DB, added to the table severelal times.
Can someone tell where is mistake?
public Vector getOrder() throws Exception
{
DbConnection();
Statement st = null;
ResultSet res =null;
String query="Select * From Orders;";
try{
st=connect.createStatement();
res=st.executeQuery(query);
Vector v =new Vector();
Vector<String> record = new Vector<String>();
int i=0;
while(res.next())
{
record.clear();
uzsakNr=res.getString("Uzsakymo_nr");
priemDat=res.getString("Priemimo_data");
irengPav=res.getString("Irenginio_pavadinimas");
model=res.getString("Modelis");
status=res.getString("Statusas");
grazDat=res.getString("Grazinimo_data");
clientId=Long.toString(res.getLong("ClientId"));
//record.addElement(i);
record.addElement(uzsakNr);
record.addElement(priemDat);
record.addElement(irengPav);
record.addElement(model);
record.addElement(status);
record.addElement(grazDat);
record.addElement(clientId);
//record.addElement("");
v.addElement(record);
i++;
}
//Zle vydaji, daji tyko trzy takiesame ostatnie
System.out.println(v);
return v;
}finally {
if(res!=null) res.close();
if(st!=null) st.close();
}
}
in another class
try{
Vector ve=db.getOrder();
String heading[]={"uzsakNr","priemDat","irengPav","model","status","grazDat","ClientID"};
Vector columnHeads= new Vector();
for (int i=0;i<heading.length; i++)
columnHeads.addElement(heading[i]);
table = new JTable(ve,columnHeads);
table.addMouseListener(new TableMouseListener());
scrollPane.setViewportView(table);
UzsakPanel.add(scrollPane);
scrollPane.setBounds(10, 10, 901, 200);
}catch(Exception e2){e2.printStackTrace();}
Firstly,
Replace the line containing clear() with Vector<String> record = new Vector<String>();
Secondly, I think what you're doing is probably correct but your printing is the problem.
Since you have a vector of vectors containing strings, I would print it like so
for(Vector stringVect : v) {
for(String s : stringVect) {
System.out.print(s+ '\t');
}
System.out.println();
}

Categories

Resources