How do you change Vector to ArrayList? - java

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

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.

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.

This is my code to print the jtable on frame

I added MouseListener to select a particular row from table,the content of row is getting printed on console but I want to print this content on new frame what should I do for this.
I attached my code along with the screenshot of the table.
thanks for help.
This is my code.
final JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane( table );
cp.add(scrollPane,BorderLayout.CENTER);
frame.add(cp);
frame.setSize(300,300);
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
if(e.getClickCount()==1){
JTable target = (JTable)e.getSource();
System.out.println(target);
int row = target.getSelectedRow();
System.out.println(row);
Object [] rowData = new Object[table.getColumnCount()];
Object [] colData = new Object[table.getRowCount()];
for(int j = 0;j < table.getRowCount();j++)
for(int i = 0;i < table.getColumnCount();i++)
{
rowData[i] = table.getValueAt(j, i);
System.out.println(rowData[i]);
}
}
}
});
}
First of all, if you make a graphical interface with swing, you can't use System.out.print.
You need to set every row in a Label and print it out that way. If it is a Label then you can select it with your mouse
In the Mouse Listener method, Call the new JFrame,
in that JFrame , put the Contents of selected Row to Constructor Parameters.
JFrame newframe=new JFrame("Selected Contents);
When you output the result (System.out.println(rowData[i]);) just create a new JFrame and place the text you want to output here :
...
JFrame secondFrame = new JFrame();
JPanel myPanel = new JPanel();
for(int j = 0;j < table.getRowCount();j++){
for(int i = 0;i < table.getColumnCount();i++){
rowData[i] = table.getValueAt(j, i);
JLabel label = new JLabel(rowData[i]);
myPanel.add(label);
}
}
secondFrame.add(myPanel);
secondFrame.setVisible(true);
....

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

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)

Categories