-
Table, beginner stuff
Hi!
My problem is as follows:
Code:
import java.io.BufferedWriter;
import java.io.FileWriter;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
[B] public class Book implements TableModelListener{
public Book( ){
String [] columnNames = {"first name","last name","sport","# of years","vegetarian"};
Object [][] data = {
{"Mary", "Campione",
"Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", "Huml",
"Rowing", new Integer(3), new Boolean(true)},
{"Kathy", "Walrath",
"Knitting", new Integer(2), new Boolean(false)},
{"Sharon", "Zakhour",
"Speed reading", new Integer(20), new Boolean(true)},
{"Philip", "Milne",
"Pool", new Integer(10), new Boolean(false)}
};
//Creates the GUI
JTable table = new JTable (data, columnNames);
JScrollPane pane = new JScrollPane(table);
JFrame frame = new JFrame();
frame.add(pane);
frame.setVisible(true);
frame.setSize(500,500);
//adds the listener
table.getModel().addTableModelListener(this);
}
//the listener
public void tableChanged(TableModelEvent e) {
//just checks if it goes past this part
System.out.println("Check");
//Try and catch block
try{
FileWriter fs = new FileWriter("C:\\hej10.txt");
BufferedWriter ws = new BufferedWriter(fs);
for(int i = 0; i<=2; i++){ //Amount of rows
if (i >= 1){
System.out.println("den går igenom");
ws.write("\r\n");
}
for(int j = 0; j<=3; j++){ //amount of columns
if(j == 3){
//The problem with table not being found
ws.write((String) table.getValueAt(i,j).toString());
}
else{
ws.write((String) table.getValueAt(i,j)+",");
}}
}
ws.close();
}catch (Exception error){
System.err.println("Error"+ error.getMessage());
}
}
public static void main(String[] args){
//Creates the Book object
new Book();
}
}
[/B]
In need to somehow make table global or somehow accessible so that it can be written to a text file.:confused:
and yes the array part is taken from Javas tutorial JTable, and yes I'm to lazy to write the array myself :D
any help is appreciated
-
somehow make table global or somehow accessible
Make it a member variable in class scope:
Code:
public class BookRx implements TableModelListener{
JTable table; // member variable
public BookRx( ){
...
//Creates the GUI
// table is a local variable when declared here
// JTable table = new JTable (data, columnNames);
// instantiate the member variable
table = new JTable (data, columnNames);
...