I'm trying to add row to JTable like this
DefaultTableModel model = new DefaultTableModel();
try {
Builder builder = new Builder();
Document doc = builder.build(Config.PATH +"incasation.xml");
Element root = doc.getRootElement();
Elements childs = root.getChildElements("locations");
model.addColumn("Name");
model.addColumn("Total");
model.addColumn("Location fee");
model.addColumn("Bank");
model.addColumn("Tax");
float baseSum = 0;
float locationSum = 0;
float bankSum = 0;
float taxSum = 0;
for(int i=0; i< childs.size(); i++)
{
Element child = childs.get(i);
model.addRow(new Object[] {
child.getFirstChildElement("name").getValue(),
child.getFirstChildElement("base").getValue(),
child.getFirstChildElement("locationfee").getValue(),
child.getFirstChildElement("bank").getValue(),
child.getFirstChildElement("tax").getValue()
});
baseSum += Float.parseFloat(child.getFirstChildElement("base").getValue());
locationSum += Float.parseFloat(child.getFirstChildElement("locationfee").getValue());
bankSum += Float.parseFloat(child.getFirstChildElement("bank").getValue());
taxSum += Float.parseFloat(child.getFirstChildElement("tax").getValue());
}
model.addRow(new Object[] {
"SUM",
Float.toString(baseSum),
Float.toString(locationSum),
Float.toString(bankSum),
Float.toString(taxSum)
});
}
catch(Exception e){}
and in that case it JTable gets only first row, so I tryied like this
DefaultTableModel model = new DefaultTableModel();
try {
Builder builder = new Builder();
Document doc = builder.build(Config.PATH +"incasation.xml");
Element root = doc.getRootElement();
Elements childs = root.getChildElements("locations");
model.addColumn("Name");
model.addColumn("Total");
model.addColumn("Location fee");
model.addColumn("Bank");
model.addColumn("Tax");
float baseSum = 0;
float locationSum = 0;
float bankSum = 0;
float taxSum = 0;
for(int i=0; i< childs.size(); i++)
{
Element child = childs.get(i);
model.addRow(new Object[] {
child.getFirstChildElement("name").getValue(),
child.getFirstChildElement("base").getValue(),
child.getFirstChildElement("locationfee").getValue(),
child.getFirstChildElement("bank").getValue(),
child.getFirstChildElement("tax").getValue()
});
}
for(int j=0; j< childs.size(); j++)
{
Element child = childs.get(j);
baseSum += Float.parseFloat(child.getFirstChildElement("base").getValue());
locationSum += Float.parseFloat(child.getFirstChildElement("locationfee").getValue());
bankSum += Float.parseFloat(child.getFirstChildElement("bank").getValue());
taxSum += Float.parseFloat(child.getFirstChildElement("tax").getValue());
}
model.addRow(new Object[] {
"SUM",
Float.toString(baseSum),
Float.toString(locationSum),
Float.toString(bankSum),
Float.toString(taxSum)
});
}
catch(Exception e){}
I this case the last row is not added.
How to solve this problem?
EDIT
I found the solution one of the value was empty string thats why there was no sum.
It should be like
String base = child.getFirstChildElement("base").getValue();
baseSum += Float.parseFloat(base.equals("") ? "0" : base);
You have edited the question with a solution. However, the solution was not obvious because an exception was thrown that was caught and disregarded.
This is a great example of why this line of code can be problematic:
catch(Exception e){}
I would suggest to at least do a e.printStackTrace(), so that worse case debugging would be easier.
Related
I am having some issues in terms of appending data into my CSV file. The problem is that whenever I try to append data into my CSV file on a second time, the second value which is appended to the CSV file comes with the first appended value. It's like it brings the existing value with it when appending to the CSV file. Thus, because of this issue, it results into an array index out of bounds exception in this statement: cust[read2DStringIndex][newVarIndexer] = fromfile[g]; , the data of the CSV file repeats the existing values along with the latest appended values and also the first value is only displayed on my GUI table.
CSV File:
Table:
Here's my source code in writing and reading the CSV:
public void writeCustomerCSV(){ // this creates a CSV file which stores the inputs of the user
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv",true)); // when I set append mode to true, cust[read2DStringIndex][newVarIndexer] = fromfile[g] results to index array out of bounds to 10
StringBuilder sb = new StringBuilder();
int y;
for(int x = 0; x < itemTo2D.length; x++){
if(itemTo2D[x][0] != null){
for(y = 0; y < itemTo2D[0].length; y++){
sb.append(itemTo2D[x][y]);
sb.append(",");
}
}
sb.append("-"); //separation for rows
sb.append(","); // separation for columns
}
bw.write(sb.toString());
bw.close();
}
catch (Exception ex){
}
}
public void readCustomerCSV(){ // reads the contents of the CSV file
String[][] twoDArray = new String[10][7];
int read2DStringIndex = 0;
int newVarIndexer = 0;
DefaultTableModel tblmodelll = (DefaultTableModel) mainTable.getModel(); // table
String[] fromfile = {}; // 1d string for getting the columns(7 columns) of the CSV file
int ak = 0;
int sk = 0;
try{
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv"));
String line;
while ((line = br.readLine()) != null){
fromfile = line.split(","); //separates the columns by a comma
for(int c = 0; c < fromfile.length; c++){
if(fromfile[c].equals("-")){
sk = 0;
ak++;
if(c > 0){
if(!fromfile[c-1].equals("-")){
id = id + 1;
}
}
} else{
twoDArray[ak][sk] = fromfile[c];
sk++;
}
}
}
} catch (Exception ex){
}
for(int g = 0; g < fromfile.length; g++){
if(fromfile[g].equals("-")){ //if there is a presence of a dash, it increments the read2DStringINdex (row index) of the 2D array
read2DStringIndex++;
newVarIndexer = 0;
}
else{
cust[read2DStringIndex][newVarIndexer] = fromfile[g]; //cust is the 2D array(declared universal) which is going to display the values to the table
newVarIndexer++;
}
}
for(int h = 0; h < cust.length; h++){ //prints cust (2D array) , just to check what data is being stored
for(int p = 0; p < cust[0].length; p++){
System.out.println(cust[h][p] + ",");
}
}
setrowcount = 0;
for(int r = 0; r < cust.length; r++){
if(setrowcount == 0){
tblmodelll.setRowCount(0);
}
try{
if(cust[r][0].equals("null") == false){
tblmodelll.addRow(cust[r]); //displays the cust(2D array) data to table
}
} catch(Exception e){
}
setrowcount++;
}
}
Is there something missing in my structure of the codes or is my logic in appending the values not right?
Your responses would indeed help me in resolving this issue.
Thank you very much.
I am a newbie coder.
Can anyone teach me how to get the value inside storedVector1[3] ? I tried a lot of ways but i can only loop through storedVector and not the value inside the storedVector object
EDIT:
tableData.java
public class TableData {
static Vector storedVector = new Vector();
public void fillSortedData(File file, Vector data){
Workbook workbook = null;
Calendar now = Calendar.getInstance();
int monthnow = now.get(Calendar.MONTH) + 1;
try {
try {
workbook = Workbook.getWorkbook(file);
} catch (IOException ex) {
Logger.getLogger(
excelTojTable.class.getName()).log(Level.SEVERE, null, ex);
}
Sheet sheet = workbook.getSheet(0);
headers.clear();
for (int i = 0; i < sheet.getColumns(); i++) {
Cell cell1 = sheet.getCell(i, 0);
headers.add(cell1.getContents()); }
data.clear();
for (int j = 1; j < sheet.getRows(); j++) {
Vector d = new Vector();
for (int i = 0; i < sheet.getColumns(); i++) {
Cell cell = sheet.getCell(i, j);
d.add(cell.getContents());
CellType type = cell.getType();
if(type == CellType.DATE){
String cellDateStr = cell.getContents();
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
try {
Date cellDate = formatter.parse(cellDateStr);
int month = cellDate.getMonth() + 1;
if(monthnow != month) {
d.clear();
//d.removeAllElemen8ts();
i = sheet.getColumns();
}
} catch (ParseException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
if(d.isEmpty() == false) {
d.add("\n");
data.add(d);
storedVector.add(d);
}
}
} catch (BiffException e) {
e.printStackTrace();
}
}
public void emailList() {
int abc = storedVector.size();
//iterate through the vector and get all the element
}
}
}
I created a vector "data" using the same method as storedVector in another java class.
In tableData.java, I wanted to create a method "emaillist" that can iterate and get all the email that was show in the picture and save it in a list or array
Vector extends AbstractList. So it should have a Vector.get(i) method.
Try using
Vector v = storedVector.get(1);
Object o = v.get(3);
if storedVector is a list/set of Vector, this code can help:
for(Vector vector: storedVector){
for(int i=0; i< vector.size(); i++){
//access to vector[i]
}
}
I am creating java editable table, and faced to problem: it "crashes" after reading data. Here is my table:
table.getTableHeader().setReorderingAllowed(false);
tableModel = new DefaultTableModel(new Object[]
{"#","1","2","3","4","5","6","7"},8);
table.setModel(tableModel);
table.getColumnModel().getColumn(0).setMaxWidth(22);
Reading from txt:
OK4.addActionListener(new ActionListener(){
#Override
File f = new File(fileName);
if(f.exists()){
try {
tableModel = new DefaultTableModel(new Object[]{"#","1","2","3","4","5","6","7"},0);
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
String[] colHeaders = line.split("\\s+");
tableModel.setColumnIdentifiers(colHeaders);
while ((line = br.readLine()) != null) {
String[] data = line.split("\\s+");
tableModel.addRow(data);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}else{
JOptionPane.showMessageDialog(null, "this day is not saved");
};
table.setModel(tableModel);
table.getColumnModel().getColumn(0).setMaxWidth(22);
});
And main problems causing my sum field:
OK3.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
int sum=0;
int number;
Object smth;
String Smth;
int kint2 = table.getRowCount()-1;
if(table.getValueAt(kint2, 1)=="total:"){
}else{
tableModel.addRow(new Object[]{});
int a = table.getRowCount()-1;
table.setValueAt("total:", a, 1);
}
for (int j = 2; j < 8; j++) {
for (int i = 0; i < table.getRowCount()-1; i++) {
smth = table.getValueAt(i,j);
Smth = (String) smth;
if (smth==null){
number=0;
}else{
number=Integer.parseInt(Smth);
}
sum=sum+number;
}
table.setValueAt(sum, table.getRowCount()-1, j);
sum=0;
}
}
});
Application stops calculate sum after being read from txt or calculates only first 4 rows sum. Have it something to do with my tableModel?
Thank you for answers.
The problem is that you add new rows with tablemodel and count rows with table. As discussed at "jTable row count VS model row count" your table won't update the rows count so always use tablemodel.getRowCount()
This is a last resort. I'm studying development of Information Systems and even my teachers can't solve this... this is a nut for you to crack!!
This is the problem: My jTable in GUI gives me this:
This is what Microsoft Management Studio shows me:
As you can tell the jTable (GUI) has got 2 main problems:
The columnname "Name" does not contain any information. And it should? Why isn't it showing?
Since as you can tell, the table contains several columns, too many to even show. I therefore want to "add a restriction" that changes so that the jTable only shows the first 6 columns.
This is the code for the "creation of the table", in the DataAccessLayer:
private TableModel getResultSetAsDefaultTableModel(ResultSet rs) {
try {
String[] columnHeadings = new String[0];
Object[][] dataArray = new Object[0][0];
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String columnName = md.getColumnName(i);
columnHeadings = Arrays.copyOf(columnHeadings, columnHeadings.length + 1);
columnHeadings[i - 1] = columnName;
}
int r = 0;
while (rs.next()) {
Object[] row = new Object[columnCount];
for (int i = 1; i <= columnCount; i++) {
row[i - 1] = rs.getObject(i);
}
dataArray = Arrays.copyOf(dataArray, dataArray.length + 1);
dataArray[r] = row;
r++;
}
DefaultTableModel dtm = new DefaultTableModel(dataArray, columnHeadings) {
public boolean isCellEditable(int row, int column) {
return false;
}
};
return dtm;
} catch (SQLException ex) {
Logger.getLogger(Dataaccesslayer.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
If you want me to show you the path of the code (frame, controller) just say so and I'll post it.
I would be so thankful if anyone can solve this...
Regards,
Christian
I think it is because in your for loop it should say i = 0; and not i = 1; since the first information (the name) is at index 0 right ?
In your case it could be enough to just leave the for-loop as it is and change this line to:row[i - 1] = rs.getObject(i-1);
To hide or show columns you could call setMin setMax and setPreferredWidth on your TableColumn.
Change your method like next, I think it helps you:
private TableModel getResultSetAsDefaultTableModel(ResultSet rs) {
try {
List<String> columnHeadings = new ArrayList<String>();
Object[][] dataArray = new Object[0][0];
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
columnHeadings.add(md.getColumnName(i));
}
int r = 0;
while (rs.next()) {
Object[] row = new Object[columnCount];
for (int i = 1; i <= columnCount; i++) {
row[i-1] = rs.getObject(i);
}
dataArray = Arrays.copyOf(dataArray, dataArray.length + 1);
dataArray[r] = row;
r++;
}
DefaultTableModel dtm = new DefaultTableModel(dataArray,columnHeadings.toArray(new Object[columnHeadings.size()])) {
public boolean isCellEditable(int row, int column) {
return false;
}
};
return dtm;
} catch (SQLException ex) {
Logger.getLogger(Dataaccesslayer.class.getName()).log(Level.SEVERE,null, ex);
}
return null;
}
For showing not all columns use dtm.setColumnCount(2);. Here 2 is column count to show.
This is the code for the "creation" of the table I have in my DataAccessLayer.
private TableModel getResultSetAsDefaultTableModel(ResultSet rs) {
try {
String[] columnHeadings = new String[0];
Object[][] dataArray = new Object[0][0];
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String columnName = md.getColumnName(i);
columnHeadings = Arrays.copyOf(columnHeadings, columnHeadings.length + 1);
columnHeadings[i - 1] = columnName;
}
int r = 0;
while (rs.next()) {
Object[] row = new Object[columnCount];
for (int i = 1; i <= columnCount; i++) {
row[i - 1] = rs.getObject(i);
}
dataArray = Arrays.copyOf(dataArray, dataArray.length + 1);
dataArray[r] = row;
r++;
}
DefaultTableModel dtm = new DefaultTableModel(dataArray, columnHeadings) {
public boolean isCellEditable(int row, int column) {
return false;
}
};
return dtm;
} catch (SQLException ex) {
Logger.getLogger(Dataaccesslayer.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
**This results in some complications, since one of my tables has 50 different columns and therefore you can't read the columnnames or what is in the cell.
The problem is that the table's values are determined by the metadata...
I want to limit the columns that are showed to a specific number (5) for all tables.
How do I do it?**
Kind regards,
Chris
you can remove tables if you want to...
int amountColumns = table.getColumnModel().getColumnCount(); //count columns
TableColumn c6 = table.getColumnModel().getColumn(6); //identif a random column
table.getColumnModel().removeColumn(c6); //remove this column
i hope that helped...
I would not remove them but change their size to 0.
int amountColumns = table.getColumnModel().getColumnCount(); //count columns
TableColumn c6 = table.getColumnModel().getColumn(6); //identif a random column
table.getColumnModel().setMin(0);
table.getColumnModel().setMax(0);
table.getColumnModel().setPreferredWidth(0);
Like i answered you in your other thread...