Insert values from ArrayList into a JTable - java

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.

Related

JTable displaying the same row from Mysql table

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.

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);

How do you change Vector to ArrayList?

I am developing an application in Java and since Vector is obsolete I am required to change this to using ArrayList.
This is the relevant code that needs to be changed to ArrayList:
This is the "House" Class.
public Vector<Vector> getItems() {
Vector<Vector> data = new Vector<Vector>();
for (int i = 0; i < _itemList.size(); i++) {
Vector<String> row = new Vector<String>();
row.add(_itemList.get(i).getDecription());
row.add(String.valueOf(_itemList.get(i).getprice()));
data.add(row);
}
return data;
}
This is the GUI Class:
private void updateView() {
//Gets Rows and Columns from the House.class
Vector<Vector> rowData = _listener.getHouse().getItems();
Vector<String> columnNames = new Vector<String>();
columnNames.add("Product Name");
columnNames.add("Product Price(€)");
//Creates Shopping Cart and sets size + properties
table1 = new JTable(rowData, columnNames);
table1.setPreferredScrollableViewportSize(new Dimension(375, 325));
table1.setFillsViewportHeight(true);
//Adds ScrollPane to the container and sets the component position to center
JScrollPane scrollPane = new JScrollPane(table1);
centerPanel.add(scrollPane, BorderLayout.CENTER);
}
I need to entirely stop the usage of VECTOR and use ArrayList instead. Is there a simple way out? Any ways on how to replace this?
Vector<String> vector = new Vector<String>();
// (... Populate vector here...)
ArrayList<String> list = new ArrayList<String>(vector);
This is from here java vector to arraylist
This should do for the first one.
public List<List<String>> getItems() {
List<List<String>> data = new ArrayList<ArrayList<String>>();
for (int i = 0; i < _itemList.size(); i++) {
List<String> row = new ArrayList<String>();
row.add(_itemList.get(i).getDecription());
row.add(String.valueOf(_itemList.get(i).getprice()));
data.add(row);
}
return data;
}
The second is a little less trivial. You could start with something like this but I suspect using a TableModel would be a good step forward.
private void updateView() {
//Gets Rows and Columns from the House.class
List<List<String>> rowData = _listener.getHouse().getItems();
List<String> columnNames = new ArrayList<String>();
columnNames.add("Product Name");
columnNames.add("Product Price(€)");
//Creates Shopping Cart and sets size + properties
// **** Will not work - Probably better to use a TableModel.
table1 = new JTable(rowData, columnNames);
table1.setPreferredScrollableViewportSize(new Dimension(375, 325));
table1.setFillsViewportHeight(true);
//Adds ScrollPane to the container and sets the component position to center
JScrollPane scrollPane = new JScrollPane(table1);
centerPanel.add(scrollPane, BorderLayout.CENTER);
}

Building Java TableModel from list of results

Hi I have problems with populating a TableModel, I cannot understand what the problem is
here is my method
private TableModel buildTableModel(List<Player> result) {
// build the columns
Vector<String> columnNames = new Vector<String>();
//int columnCount = metaData.getColumnCount();
//for (int column = 1; column <= columnCount; column++) {
// columnNames.add(metaData.getColumnName(column));
//}
columnNames.add("playerid");
columnNames.add("squeezePlay");
columnNames.add("weakShowdown");
columnNames.add("numberOfPlays");
columnNames.add("playsWithFriends");
columnNames.add("suspend");
columnNames.add("grade");
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (result.iterator().hasNext()) {
Player player = result.iterator().next();
Vector<Object> vector = new Vector<Object>();
vector.add((Object) player.GetId());
vector.add((Object) player.GetSqueezePlay());
vector.add((Object) player.GetWeakShowdown());
vector.add((Object) player.GetNumberOfPlays());
vector.add((Object) player.GetPlaysWithFriends());
vector.add((Object) player.GetSuspended());
vector.add((Object) player.GetGrade());
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
Note: with or without the Object casting, the table still doesn't work..
Please suggest any alternative solution to populate a TableModel.
Thanks!!
Every time you call result.iterator() you are reading the beginning of your List. Instead, use this:
for (Player player : result)

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});
}

Categories