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
Related
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.
[![enter image description here][1]][1]I'm having a problem populating a JTable from an excel file. Here is the operation, I will search, lets say "Line 1", there are 2 cells matching this value, if there is a match, I would like to pull the row and insert it into my JTable. I was able to get this working, however, this only creates one row for the first matching value, when i click on search button again, it will replace the row, with a new row, if there was more than 1 match.
I would the jtable to add both rows in the same table, rather one by one. I attached what I have so far.
Thank You in advanced.
try {
FileInputStream fis = new FileInputStream(
new File("S:\\Tester Support\\0LineTester Database\\Audit\\LASAudit.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getRichStringCellValue().getString().trim().equals(LinNum_Text.getText())) {
int rowNum = row.getRowNum();
Row r = sheet.getRow(rowNum);
DefaultTableModel model = new DefaultTableModel();
int col_0 = 0;
String val_0 = r.getCell(col_0).getStringCellValue();
int col_1 = 1;
String val_1 = r.getCell(col_1).getStringCellValue();
int col_2 = 2;
String val_2 = r.getCell(col_2).getStringCellValue();
int col_3 = 3;
String val_3 = r.getCell(col_3).getStringCellValue();
model.addColumn("ID", new Object[] { val_0 });
model.addColumn("Date", new Object[] { val_1 });
model.addColumn("Auditor Name", new Object[] { val_2 });
model.addColumn("Line #", new Object[] { val_3 });
table = new JTable(model);
table.setVisible(true);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 278, 670, 303);
contentPane.add(scrollPane);
scrollPane.setViewportView(table);
}
}
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
I was able to get this working, however, this only creates one row for the first matching value,
That is because in your "looping code" you create a new JTable each time.
Instead you want to create the table once and add data to your TableModel inside the loop. So the structure of your code should be something like:
String[] columnNames = { "Id", "Date", ... };
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
for (...)
{
...
if (matched row found)
{
...
Object[] row = { val_0, val_1, ...};
model.addRow( row );
}
JTable table = new JTable( model );
...
With camickr's help I got this to work. Here is the final code.
try {
FileInputStream fis = new FileInputStream(
new File("S:\\Tester Support\\0LineTester Database\\Audit\\LASAudit.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
String[] columnNames = {"Id","Date","Auditor Name","Line Number"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(model);
table.setVisible(true);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 278, 670, 303);
contentPane.add(scrollPane);
scrollPane.setViewportView(table);
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getRichStringCellValue().getString().trim().equals(Spec_Text.getText())) {
int rowNum = row.getRowNum();
Row r = sheet.getRow(rowNum);
int col_0 = 0;
String val_0 = r.getCell(col_0).getStringCellValue();
int col_1 = 1;
String val_1 = r.getCell(col_1).getStringCellValue();
int col_2 = 2;
String val_2 = r.getCell(col_2).getStringCellValue();
int col_3 = 3;
String val_3 = r.getCell(col_3).getStringCellValue();
Object[] ROWS = { val_0, val_1, val_2,val_3};
model.addRow( ROWS );
}
}
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
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.
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)
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});
}