How to convert an object into a JTable in Java - java

I recently started using OpenCSV's CSVReader to get data from a CSV file to a JTable in java, but I keep getting an error. DaTroop gave the answer to how to get data from the CSV here: import csv to JTable . In my case I copied the code
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
List myEntries = reader.readAll();
JTable table = new JTable(myEntries.toArray());
into Netbeans IDE 7.4, but I keep getting the error "Incompatible types - Object Cannot be converted to TableModel". in the
(myEntries.toArray());
Any ideas?
Thanks
As in comment, please find my whole code snippet. The JFrame works and views, so it should be called fine.
public static void LoadLog() throws FileNotFoundException, IOException {
LogViewer log = new LogViewer();
log.setVisible(true);
CSVReader reader = new CSVReader(new FileReader("testog.csv"));
String[][] rowData = {
{ "A", "B" },
{ "C", "D" }
};
List<String[]> myEntries = reader.readAll();
rowData = myEntries.toArray(new String[0][]);
String[] columnNames = { "Column 1", "Column 2" };
System.out.println(myEntries);
table1 = new JTable(rowData, columnNames);
log.pack();
log.setVisible(true);
}

First, note that reader.readAll() returns List<String[]>.
Also note that calling myEntries.toArray() returns Object[], and not Object[][], or more specifically String[][], which would be more preferable to work with.
The closest constructor for JTable that matches what you're trying to do would be this one:
JTable(Object[][] rowData, Object[] columnNames)
So you need to supply both rowData and columnNames. You can get the rowData like this:
List<String[]> myEntries = reader.readAll();
String[][] rowData = myEntries.toArray(new String[0][]);
Create a variable to hold the column names (or don't, your choice, but column names are still required):
String[] columnNames = { "Column 1", "Column 2" };
And then create your JTable:
JTable table = new JTable(rowData, columnNames);
Based on your comment, here's a short and simple code snippet for creating and displaying a table. As long as you initialize rowData and columnNames with the correct data, then it should work fine.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[][] rowData = {
{ "A", "B" },
{ "C", "D" }
};
String[] columnNames = { "Column 1", "Column 2" };
JTable table = new JTable(rowData, columnNames);
frame.add(new JScrollPane(table));
frame.pack();
frame.setVisible(true);

Related

Searching ArrayList using JTable and JButton

I have an ArrayList holding football matches and when the user types a date and presses "search" button, a new JTable opens showing you all matches played on that day. I have looped to get the date and compared it to the input inside the JTextField but it just gives me an empty table even if there is a record of a match played on the date the user enters. In this code below, I am just using hitting enter on JTextField to execute search because I do not know how to map JTextField to JButton. I have tried but it just prints the search Jbutton name.
public void searchMatch(ArrayList<Matches> searchMatch, String e)
{
DefaultTableModel searchModel = new DefaultTableModel();
for(int i = 0; i < searchMatch.size(); i++)
{
if(searchMatch.get(i).getM_date().equals(e))
{
System.out.println(searchMatch.get(i).getM_date());
String date = searchMatch.get(i).getM_date();
String teamName = searchMatch.get(i).getM_teamName();
String teamName2 = searchMatch.get(i).getM_teamName2();
int goalsScoredTeam1 = searchMatch.get(i).getGoalsTeam1();
int goalsScoredTeam2 = searchMatch.get(i).getGoalsTeam2();
Object[] row = {teamName, teamName2, goalsScoredTeam1, goalsScoredTeam2,date};
searchModel.addRow(row);
JTable searchTable = new JTable(searchModel);
searchTable.setFillsViewportHeight(true);
JPanel searchPanel = new JPanel();
JScrollPane scrollPane = new JScrollPane(searchTable);
searchPanel.add(scrollPane);
JFrame frame = new JFrame("Searched Matches");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
searchTable.setOpaque(true);
frame.setContentPane(searchPanel);
frame.pack();
frame.setSize(500, 500);
frame.setVisible(true);
}
}
}
DefaultTableModel searchModel = new DefaultTableModel();
You TableModel has no columns to display.
Even though you add rows of data, none of the data can be displayed unless you also have defined the "column names" for the TableModel.
Your code should be something like:
String columnNames = { "Date", "Name", "..." };
DefaultTableModel searchModel = new DefaultTableModel(columnNames, 0);
Which will create an empty TableModel with just the column names. Your looping code will then add each row of data.
Note, you should also look at storing all the data in your TableModel and then just filter the TableModel. Read the section from the Swing tutorial on Sorting and Filtering for a working example.

Apache POI - Is there a way to count occurrence of a string in a pivot table?

I am using version 4.1.2 of Apache Poi and I have this dataset:
String[] headers = new String[] { "Company", "Status" };
Object[][] sheetData = {
{"Company 1", "OK"},
{"Company 1", "NG"},
{"Company 2", "NG"},
{"Company 1", "OK"},
{"Company 3", "OK"},
{"Company 1", "NG"},
};
I'm trying to create a pivot table using Apache POI that groups and counts the occurrence of strings from the 2nd column. I've tried:
pivotTable.addRowLabel(0);
pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 1);
But it somehow still counts the occurrences from the first column.
The pivot table I'm trying to create:
and the pivot table that is being generated:
The pivot table you are showing as the one you are trying to create shows the column 1 = B (Status) as a column label using a DataConsolidateFunction as well as column label used for labeling columns. So one column has two different properties in the pivot table here. That makes it complicated.
The DataConsolidateFunction column label is done already using pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 1). This also sets dataField setting for the column.
For the column label used for labeling columns apache poi 4.1.2 provides the method XSSFPivotTable.addColLabel. But this method removes the dataField setting. So we need set it new using the low level ooxml-shemas classes.
And the order of the commands is important here because they effect the same column. First do pivotTable.addColumnLabeland then do pivotTable.addColLabel. Else addColumnLabel will set dataField setting but will remove axis="axisCol" setting from that column. But because of the two different properties in the pivot table both settings are needed for that column.
Complete example:
import java.io.FileOutputStream;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.ss.usermodel.DataConsolidateFunction;
import org.apache.poi.xssf.usermodel.*;
class CreatePivotTable {
public static void main(String[] args) throws Exception {
String[] headers = new String[] { "Company", "Status" };
Object[][] sheetData = {
{"Company 1", "OK"},
{"Company 1", "NG"},
{"Company 2", "NG"},
{"Company 1", "OK"},
{"Company 3", "OK"},
{"Company 1", "NG"},
};
try (XSSFWorkbook workbook = new XSSFWorkbook();
FileOutputStream fileout = new FileOutputStream("./ExcelResult.xlsx") ) {
XSSFSheet dataSheet = workbook.createSheet("Data");
XSSFRow row;
XSSFCell cell;
int r = 0;
row = dataSheet.createRow(r++);
int c = 0;
for (String header : headers) {
cell = row.createCell(c++);
cell.setCellValue(header);
}
for (Object[] dataRow : sheetData) {
row = dataSheet.createRow(r++);
c = 0;
for (Object value : dataRow) {
cell = row.createCell(c++);
if (value instanceof String) {
cell.setCellValue((String)value);
} //else if...
}
}
XSSFSheet pivotSheet = workbook.createSheet("Pivot");
AreaReference areaReference = new AreaReference(
new CellReference(0, 0),
new CellReference(sheetData.length, headers.length-1),
SpreadsheetVersion.EXCEL2007);
XSSFPivotTable pivotTable = pivotSheet.createPivotTable(areaReference, new CellReference("A4"), dataSheet);
pivotTable.addRowLabel(0);
pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 1);
pivotTable.addColLabel(1);
//Method addColLabel removes the dataField setting. So we need set it new.
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(1)
.setDataField(true);
workbook.write(fileout);
}
}
}

Re-Using JTableHeader

The code below displays 2 JTables.
As they both will have exactly the same headers I wanted, for the sake of efficiency, to reuse the header from the first table.
However running the code results in the header appearing in the second table but not in the table it came from originally.
I am less interested in work-arounds, but - for the sake of learning and understanding - more interested in finding out why the header does not appear in the first table.
Here is the code:
public class HeaderTest1 {
public void doTheTest() {
JFrame testFrame = new JFrame("Header Test");
JPanel pane = new JPanel();
Container theContentPane = testFrame.getContentPane();
BoxLayout box = new BoxLayout(pane, BoxLayout.Y_AXIS);
pane.setLayout(box);
theContentPane.add(pane);
String theData[][]
= {
{"One", "two", "3"},
{"four", "5", "six"},
{"7", "8", "9.0"},
{"£10.00", "11", "twelve"}
};
String columnNames[] = {"Column 1", "Column 2", "Column 3"};
JTable firstTable = new JTable(theData, columnNames);
JScrollPane thisScrollPane = new JScrollPane(firstTable);
JTableHeader thisTableHeader = firstTable.getTableHeader();
pane.add(thisScrollPane);
buildTheSecondTable(thisTableHeader, firstTable, columnNames, pane);
testFrame.pack();
testFrame.setVisible(true);
}
private void buildTheSecondTable(JTableHeader headerFromTheFirstTable,
JTable firstTable, String[] columnNames, JPanel pane) {
JTable secondTable = new JTable();
int columnCount = columnNames.length;
JScrollPane thisScrollPane = new JScrollPane(secondTable);
secondTable.setTableHeader(headerFromTheFirstTable);
Object[][] emptyData = new Object[1][columnCount];
for (int n = 0; n < columnCount; n++) {
emptyData[0][n] = "";
}
DefaultTableModel thisTableModel = new DefaultTableModel();
thisTableModel.setDataVector(emptyData, columnNames);
secondTable.setModel(thisTableModel);
secondTable.setLayout(firstTable.getLayout());
secondTable.setCellEditor(firstTable.getCellEditor());
pane.add(thisScrollPane);
}
public static void main(String[] args) throws SQLException, ParseException {
HeaderTest thisTest = new HeaderTest();
thisTest.doTheTest();
}
Any advice would be appreciated
A Swing component can only have a single parent so you can't share the table header component.
You can however share the Array of column names:
JTable firstTable = new JTable(theData, columnNames);
In your buildTheSecondTable method you have access to the array of column names so just use:
//DefaultTableModel thisTableModel = new DefaultTableModel();
DefaultTableModel thisTableModel = new DefaultTableModel(columnNames);
Then you can add data to the model and the model to the table.
Then reorder the code to create the JScrollPane after you add the model to the table.
Also, get rid of the table.setLayout() code. You would never use a layout manager on a table. You don't add components to the table. The table renders the data itself without using real components.

DefaultTableModel doesn't show columns

I have problem with DefaultTableModel it won't show me my columns in table, there is a part of code:
JTable table = new JTable() {
public boolean isCellEditable(int data, int columnNames) {
return false;
}
};
String columnNames[] = new String[] { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian", "asd", "asd" };
DefaultTableModel dtm = new DefaultTableModel(0, 0);
dtm.setColumnIdentifiers(columnNames);
table.setModel(dtm);
for (Reservation r : reservation) {
rez.add(new Reservation(r.getID(), r.getA(), r.getB(), r.getC(), r.getD(), r.getE(), r.getF()));
}
for (int i = 0; i < rez.size(); i++) {
int id = rez.get(i).getID();
String l = rez.get(i).getA();
String w = rez.get(i).getB();
String z = rez.get(i).getC();
String o = rez.get(i).getD();
String d = String.valueOf(rez.get(i).getE());
String g = rez.get(i).getF();
dtm.addRow(new Object[] { id, l, w, z, d,o,g });
}
JScrollPane sp = new JScrollPane(dtm);
add(table);
}
Im trying to make a dynamic table. Data will be from data base (posgreSQL) using hibernate, and thats fine, it work's but I cant see a column names from
String columnNames[] = new String[] { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian", "asd", "asd" };
Don't care about names of columns and name of getters i changed it for this post.
In addition I can't make it scrollable:
JScrollPane sp = new JScrollPane(dtm);
I'm not sure how this would be able to compile
JScrollPane sp = new JScrollPane(dtm);
add(table);
dtm is an instance of DefaultTableModel so it should never be possible to pass it to a JScrollPane,
Instead you should be using
JScrollPane sp = new JScrollPane(table);
add(sp);
See How to Use Tables and How to Use Scroll Panes for more details
Add the table rather than the TableModel to the JScrollPane
add(new JScrollPane(table));

Trouble with Java's Vector's and JTable

I'm tinkering with JTables and Vectors for the first time in Java, and I've hit an interesting snag. My code compiles correctly, but when I go to run it, I get the following exception:
Exception in thread "main" java.lang.ClassCastException:
java.lang.String cannot be cast to java.util.Vector
I don't see anywhere where I'm casting, so I'm a bit confused.
Vector<String> columnNames = new Vector<String>();
columnNames.add("Tasks");
Vector<String> testing = new Vector<String>();
testing.add("one");
testing.add("two");
testing.add("three");
table = new JTable(testing, columnNames); // Line where the error occurrs.
scrollingArea = new JScrollPane(table);
My goal is to have a table of JPanels, but I have the same type of error when I try to use a Vector of < taskPanel > Here's the class that extends JPanel:
class taskPanel extends JPanel
{
JLabel repeat, command, timeout, useGD;
public taskPanel()
{
repeat = new JLabel("Repeat:");
command = new JLabel("Command:");
timeout = new JLabel("Timeout:");
useGD = new JLabel("Update Google Docs:");
add(repeat);
add(command);
add(timeout);
add(useGD);
}
}
You need to use a Vector of Vectors here:
Vector<Vector> rowData = new Vector<Vector>();
rowData.addElement(testing);
JTable table = new JTable(rowData, columnNames);
For a multi-column Vector table model, see this example.
Your testing vector should be vector of vectors as each row is supposed to contain data for all columns e.g.
Vector<Vector> testing = new Vector<Vector>();
Vector<String> rowOne = new Vector<String>();
rowOne.add("one");
Vector<String> rowTwo = new Vector<String>();
rowTwo.add("two");
Vector<String> rowThree = new Vector<String>();
rowThree.add("three");
testing.add(rowOne);
testing.add(rowTwo);
testing.add(rowThree);
table = new JTable(testing, columnNames); // should work now
scrollingArea = new JScrollPane(table);
The casting is the < String >. You can't have Vector Strings at the moment. Take a look at this.

Categories

Resources