JTable displaying the same row from Mysql table - java

I'm showing the method were the JTable is constructed, the error is when adding the rows inside the for (int i = 1; i <= numero_columnas; i++) loop, or the way the DefaultTableModel model = new DefaultTableModel(); is declared, I can't find the error.
public void verTablaTable (Connection db, String nombre) throws Exception{
Statement stmt=db.createStatement();
ResultSet sst_ResultSet = stmt.executeQuery("SELECT * FROM "+nombre);
ResultSetMetaData md = sst_ResultSet.getMetaData();
int numero_columnas = md.getColumnCount();
DefaultTableModel model = new DefaultTableModel();
for (int i=1;i<=numero_columnas; i++){
model.addColumn(md.getColumnName(i));
}
JTable tabla =new JTable(model);
DefaultTableModel model1 = (DefaultTableModel) tabla.getModel();
Vector row = new Vector();
row.setSize(numero_columnas);
while (sst_ResultSet.next()){
for (int i = 1; i <= numero_columnas; i++){
row.set(i-1,sst_ResultSet.getString(i));
}
model1.addRow(row);
}
tabla.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane sp_vertabla = new JScrollPane(tabla);
sp_vertabla.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
sp_vertabla.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
sp_vertabla.setBounds(50,30,700,500);
JPanel cont_vertabla = new JPanel(null);
cont_vertabla.setPreferredSize(new Dimension(750,600));
cont_vertabla.add(sp_vertabla);
f_vertabla.setContentPane(cont_vertabla);
f_vertabla.pack();
f_vertabla.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//f_vertabla.setResizable(false);
f_vertabla.setVisible(true);
f_vertabla.addWindowListener(this);
}
this is the way the JTable looks
The row listed in the above pic, is the last one in the mysql table

Try adding the line
Vector row = new Vector();
inside the while loop.

Related

Insert values from ArrayList into a JTable

public void populateJTable() {
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
Object[] rowData = new Object[4];
TrackService ts = new TrackService();
ArrayList<Track> tracks = ts.jsonToTracks();
for (int i = 0; i < tracks.size(); i++) {
rowData[0] = tracks.get(i).getTrackName();
rowData[1] = tracks.get(i).getArtist();
model.addRow(rowData);
}
jTable1 = new JTable(model);
}
In my json file I have stored metadata of an mp3 file which stores 5 values. My 'jsonToTracks' method stores them in an ArrayList.
I'm trying to get 2 of the values (trackName and artist) from inside my ArrayList and display them in my JTable.
My JTable has 4 columns - Name, Artist, Key, Mood. I'm trying to store the trackName and Artist in their corresponding columns. The Key and Mood column should be blank and the Name and Artist fields should be populated.
I can't see what I'm doing wrong, can anyone help?
Maybe you should try, moving your rowData initialization inside for loop.
public void populateJTable() {
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
TrackService ts = new TrackService();
ArrayList<Track> tracks = ts.jsonToTracks();
for (int i = 0; i < tracks.size(); i++) {
Object[] rowData = new Object[4];
rowData[0] = tracks.get(i).getTrackName();
rowData[1] = tracks.get(i).getArtist();
model.addRow(rowData);
}
jTable1 = new JTable(model);
}
jTable1 = new JTable(model);
I suspect the problem is that you are creating a new JTable but you never add the table to the frame.
Instead you should use:
jTable1.setModel( model );
This will replace the data in the existing JTable was I assume you have already added to a JScrollpane that has been added to the frame.

getRowCount() and getSelectedColumn() don't work

This is how I get data from csv-file:
cSVFileReader = new CSVReader(new FileReader(sciezka), ','); // csv reader with coma-separator
java.util.List<String[]> myEntries = cSVFileReader.readAll();
String[][] rowData = myEntries.toArray(new String[0][]);
rowData = myEntries.toArray(new String[0][]);
columnnames = myEntries.get(0);
rowData = myEntries.toArray(new String[0][]);
DefaultTableModel tableModel = new DefaultTableModel(rowData, columnnames);
JTable table = new JTable(tableModel);
return table;
and this is how I count average:
public void getAverage() throws IOException{
CSVFile table = new CSVFile() ;
float sum = 0;
DefaultTableModel model = (DefaultTableModel) table.getModel();
int column = table.getSelectedColumn();
System.out.println(column); //show -1
rowcount = model.getRowCount();
System.out.println(rowcount); //show zero
}
I think, the problem is in wrong getting TableModel from JTable, but actually I can't understand how can I do it another way.
So finally it works. My solution is table, which is passed as a parameter
public float getAverage(JTable table) throws IOException

Database-JTable Interaction

Every time I implement a database viewer I have some functions that populate the table and adjust the column size. I would like to find ready component that can view the query result, also to sort, edit the entries in the table and automaticaly adjust the size of the column with respect to data. I want to use metadata to define the type of the entities automaticaly. The only thing that I will pass will be the ResultSet of the query and the component will do the rest. Any idea?
What I have done so far:
private static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
public static void showResult(ResultSet rs) throws SQLException{
//creates the table
JTable table = new JTable(buildTableModel(rs));
table.setEnabled(false);
//abjust table size
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumnAdjuster tca = new TableColumnAdjuster(table);//the class for adjusting the column size
tca.adjustColumns();
//JFrame
JFrame view = new JFrame("View");
view.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//add to frame
JScrollPane pane = new JScrollPane(table);
view.add(pane);
//settings
view.setVisible(true);
view.setSize(table.getWidth(), 400);
}
And also I have a class that adjust the column size.
To sort records use order by Clause to query you fire to get all records.
Use TableColumnModel to set column size.
Here is the code
//Your Edit Code
rs=st.executeQuery("select * from ManageVendor order by SName");
table.setModel(buildTableModel(rs));
TableColumnModel tcm=table.getColumnModel();
tcm.getColumn(0).setPreferredWidth(50);
tcm.getColumn(1).setPreferredWidth(200);
tcm.getColumn(2).setPreferredWidth(150);
tcm.getColumn(3).setPreferredWidth(60);
tcm.getColumn(4).setPreferredWidth(50);
tcm.getColumn(5).setPreferredWidth(250);

Fill JTable from database

I write this simple code to fill jTable1, but it just fills jTable1 with the last row from the database.
String SQL = "select * from usernames";
ResultSet rs = stmt.executeQuery(SQL);
String[] columnNames = {"Full Name", "Email"};
String n = "",e = "";
while(rs.next()) {
n = rs.getString("Full_Name");
e = rs.getString("Email");
Object[][]data = {{n,e}};
jTable1 = new JTable(data, columnNames);
}
I solved it by this code
String n = "",e = "";
DefaultTableModel model;
model = new DefaultTableModel();
jTable1 = new JTable(model);
model.addColumn("Full Name");
model.addColumn("Email");
while(rs.next())
{
n = rs.getString("Full_Name");
e= rs.getString("Email");
model.addRow(new Object[]{n,e});
}
Yes, it will always be the last row since in the while loop you are creating a new JTable instead of appending a row to the existing one. So do like this,
// Code
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
while(rs.next())
{
n = rs.getString("Full_Name");
e= rs.getString("Email");
//Object[][]data={{n,e}};
// This will add row from the DB as the last row in the JTable.
model.insertRow(jtable1.getRowCount(), new Object[] {n, e});
}

Retrieving Mysql data to the JTable in Netbeans

I used this coding to retrieve the Mysql data to the JTable.but it returns only the first data row of the relevant table of the database but then again it count the number of rows correctly and all it returns is same copy of the first row equal to the row count.
I'm new to Java and netbeans environment so if someone can help me to solve this problem i'll be really grateful and thank you in advance :)
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/data", "root", "1122");
Statement stat = (Statement) con.createStatement();
stat.executeQuery("select * from reserve;");
ResultSet rs=stat.getResultSet();
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
Vector data=new Vector();
Vector columnNames= new Vector();
Vector row = new Vector(columnCount);
for(int i=1;i<=columnCount;i++){
columnNames.addElement(md.getColumnName(i));
}
while(rs.next()){
for(int i=1; i<=columnCount; i++){
row.addElement(rs.getObject(i));
}
data.addElement(row);
}
DefaultTableModel model = new DefaultTableModel(data, columnNames);
jTable1.setModel( model );
You keep adding to the same Vector row. Try creating a new instance for each iteration of rs.next().
You have an error with your Vector. Consider using something like :
Vector data = new Vector(columnCount);
Vector row = new Vector(columnCount);
Vector columnNames = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
columnNames.addElement(md.getColumnName(i));
}
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
row.addElement(rs.getObject(i));
}
data.addElement(row);
row = new Vector(columnCount); // Create a new row Vector
}
DefaultTableModel model = new DefaultTableModel(data, columnNames);
jTable1.setModel( model );

Categories