| Author |
Problems passing data into file from JTable
|
Kieran Murray
Ranch Hand
Joined: May 18, 2008
Posts: 47
|
|
Dear Anybody, My question is one about I think scope and how variables are visible. Unfortunately there is a lot of code but it is basic GUI building. I am new to Java. I have done a little programming. The program is similar to a code in one of the Sun's tutorials - Building an application by Dana Nourie. The full code consists of a PowerFrame class which is the main frame. In this main frame I have a BusbarUI class called which is given here below. This BusbarUI class gets some data from the BusbarRecord class which is insubstantiated in the Busbar class. The program loads correctly. The problem arises when I try to save the data in my updated JTable. I have passed the updated data to an array see saveModel() method in Busbar class. When I call this data in the PowerFrame getJTableFields() method I get the initial starting data. I would appreciate any help. This is my dissertation for my MSC project - just starting. I am an Electrical Engineer and this will be a program to calculate power flows on electrical networks. The code consists of four classes - PowerFrame class- the main class, BusbarsUI which is a JTable in a tabbed pane and BusbarRecords where some initial data is stored and the JavaFilter class. I include the all the classes so that the program can be compiled. Kind regards, Apprentice Code of Busbar class: package tables; import javax.swing.JTable; import javax.swing.JScrollPane; import javax.swing.JPanel; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.*; import java.awt.*; import java.util.*; public class BusbarsUI extends JPanel implements TableModelListener{ private int xcount; private int ycount; Vector rows; Vector columnNames; JTable table; BusbarRecords Busbar=new BusbarRecords(); { } public BusbarsUI() { DefaultTableModel model = new DefaultTableModel(); table = new JTable(model); for(xcount=1; xcount <= Busbar.ColumnNames.length; xcount++) { model.addColumn(Busbar.ColumnNames[xcount-1]); } model.addRow(Busbar.createBlankElement()); model.addRow(Busbar.createBlankElement()); model.addRow(Busbar.createBlankElement()); Object[][] data = InitData(); SetValues(); model.addTableModelListener(this); setLayout(new BorderLayout()); setBackground(Color.white); table.setPreferredScrollableViewportSize(table.getPreferredSize()); JScrollPane scrollPane = new JScrollPane(table); add(scrollPane, BorderLayout.CENTER); } public Object[][] InitData() { TableModel model = table.getModel(); Object[][] data = new Object[model.getRowCount()][Busbar.ColumnNames.length]; for(xcount=1; xcount <= model.getRowCount(); xcount++) { for(ycount=1;ycount<=Busbar.ColumnNames.length;ycount++) data[xcount-1][ycount-1]="no"; } return data; } public void SetValues(){ TableModel model = table.getModel(); Object[][] data1=InitData(); for(xcount=1; xcount <= model.getRowCount(); xcount++) { for(ycount=1;ycount<=Busbar.ColumnNames.length;ycount++) model.setValueAt(data1[xcount-1][ycount-1],xcount-1,ycount-1); } } public void tableChanged(TableModelEvent e) { System.out.println(e.getSource()); if (e.getType() == TableModelEvent.UPDATE); { int row = e.getFirstRow(); int column = e.getColumn(); System.out.println(row); System.out.println(column); saveModel(); } } private void stopEditing() { if (table.getCellEditor() != null) table.getCellEditor().stopCellEditing(); else { } } public Object[][] saveModel() { Object[][] data1=InitData(); for(int i=0; i < 3;i++){ for(int j=0;j < 5;j++) { System.out.println(data1[i][j]); } } TableModel model = table.getModel(); for(int i=0; i < model.getRowCount();i++){ for(int j=0;j < model.getColumnCount();j++) { data1[i][j]=model.getValueAt(i,j); System.out.println(data1[i][j]); } } return data1; } } Code ends here for BusbarUI. Code for PowerFrame package tables; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.Vector; public class PowerFrame extends JFrame { private JFrame PowerFrame; private JTabbedPane PowerTabPane; private JMenuItem fMenuOpen = null; private JMenuItem fMenuSave = null; private JMenuItem fMenuClose = null; JavaFilter fJavaFilter = new JavaFilter (); File fFile = new File ("default.dat"); private Object v; public Vector q; private int count; private int xcount; private int qcount; private int ycount; private int pcount; private File file; BusbarRecords Busbar = new BusbarRecords(); BusbarsUI ui = new BusbarsUI(); public PowerFrame () { super("Begin at the Beginning"); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); PowerTabPane = new JTabbedPane(SwingConstants.RIGHT); PowerTabPane.setBackground(Color.blue); PowerTabPane.setForeground(Color.white); populatePowerTabbedPane(); buildMenu(); getContentPane().add(PowerTabPane); } private void populatePowerTabbedPane() { PowerTabPane.addTab("Busbars", null, new BusbarsUI(), "Data for Busbar"); } private void buildMenu() { JMenuBar mb = new JMenuBar(); JMenu menu = new JMenu("File"); setJMenuBar (mb); setSize (400,400); JMenuItem openitem = new JMenuItem("Open"); JMenuItem saveitem = new JMenuItem("Save"); JMenuItem exititem = new JMenuItem("Exit"); exititem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); openitem.addActionListener(new ActionListener() { public void actionPerformed ( ActionEvent e ) { boolean status = false; status = openFile (); if (!status) JOptionPane.showMessageDialog ( null, "Error opening file!", "File Save Error", JOptionPane.ERROR_MESSAGE); } }); saveitem.addActionListener(new ActionListener() { public void actionPerformed ( ActionEvent e ) { boolean status = false; status = saveFile (); if (!status) JOptionPane.showMessageDialog ( null, "Error opening file!", "File Open Error", JOptionPane.ERROR_MESSAGE); } }); menu.add(openitem); menu.add(saveitem); menu.add(exititem); mb.add(menu); setJMenuBar(mb); } /** * Use a JFileChooser in Open mode to select files * to open. Use a filter for FileFilter subclass to select * for *.java files. If a file is selected then read the * file and place the string into the textarea. **/ boolean openFile () { JFileChooser fc = new JFileChooser (); fc.setDialogTitle ("Open File"); // Choose only files, not directories fc.setFileSelectionMode ( JFileChooser.FILES_ONLY); // Start in current directory fc.setCurrentDirectory (new File (".")); // Set filter for Java source files. fc.setFileFilter (fJavaFilter); // Now open chooser int result = fc.showOpenDialog (this); if (result == JFileChooser.CANCEL_OPTION) { return true; } else if (result == JFileChooser.APPROVE_OPTION) { fFile = fc.getSelectedFile (); // Invoke the readFile method in this class q = (Vector) readFile (fFile); { System.out.println(q.elementAt(1)); } /*ui.readFileIntoJTable(q);*/ } else { return false; } return true; } // openFile boolean saveFile () { File file = null; JFileChooser fc = new JFileChooser (); // Start in current directory fc.setCurrentDirectory (new File (".")); // Set filter for Java source files. fc.setFileFilter (fJavaFilter); // Set to a default name for save. fc.setSelectedFile (fFile); // Open chooser dialog int result = fc.showSaveDialog (this); if (result == JFileChooser.CANCEL_OPTION) { return true; } else if (result == JFileChooser.APPROVE_OPTION) { fFile = fc.getSelectedFile (); if (fFile.exists ()) { int response = JOptionPane.showConfirmDialog (null, "Overwrite existing file?","Confirm Overwrite", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (response == JOptionPane.CANCEL_OPTION) return false; } return getJTableFields(fFile); } else{ return false; } } // saveFile public Object readFile (File file) { try{ FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis); v = ois.readObject(); fis.close(); } catch(Exception e){ System.err.println("Exception:" + e.getMessage()); } return (v); } public boolean getJTableFields(File file) { * Object[][] data1=ui.saveModel();* System.out.println("Value of data: "); for (int i=0; i < 3; i++) { for (int j=0; j < 5; j++) { System.out.println(" " + data1[i][j]); } System.out.println(); } System.out.println("--------------------------"); for(int i=0; i < 3;i++){ for(int j=0;j < 5;j++) { /*System.out.println(model.getValueAt(i,j));*/ } } try { FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream object = new ObjectOutputStream(fos); /* object.writeObject(data2);*/ object.flush(); object.close(); } catch(Exception ex) { System.out.println("Exception:" + ex); return false; } return true; } public static void main(String[] args) { PowerFrame PF = new PowerFrame(); PF.pack(); PF.setSize(765,690); PF.setBackground(Color.white); PF.setVisible(true); } } Code for PowerFrame ends here. Code for BusbarRecords starts here package tables; import java.io.*; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import java.util.Vector; public class BusbarRecords implements Serializable { private String firstName, lastName, sport; private int years; private boolean vegetarian; private int xcount; private int ycount; private int pcount; private int y; private PowerFrame PR; File file; String[] ColumnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"}; public Vector createColumNames() { Vector t = new Vector(); t.addElement((String) "FirstName "); t.addElement((String) "LastName "); t.addElement((String) "Sport "); t.addElement((String) "# of Years"); t.addElement((String) "Vegetarian "); return t; } public Vector createBlankElement() { Vector p = new Vector(); p.addElement((String) " "); p.addElement((String) " "); p.addElement((String) " "); p.addElement((String) " "); p.addElement((String) " "); return p; } Code for BusbarRecords ends here. Code for JavaFilter starts here. package tables; import javax.swing.*; import java.io.*; /** Filter to work with JFileChooser to select java file types. **/ public class JavaFilter extends javax.swing.filechooser.FileFilter { public boolean accept (File f) { return f.getName ().toLowerCase ().endsWith (".java") || f.isDirectory (); } public String getDescription () { return "Java files (*.java)"; } } // class JavaFilter
|
 |
Jeanne Boyarsky
internet detective
Marshal
Joined: May 26, 2003
Posts: 26144
|
|
Kieran, Welcome to JavaRanch! You are right that the post contains a lot of code! A common troubleshooting technique is to remove code until you have the smallest version of the program that reproduces the problem. This helps people focus in on the problem. (It also increases the chances of figuring it out yourself.) Additionally, it helps nail down more on what part of the code is causing the problem. Also, what doesn't work? I see where you say it gets to a certain point. But then what happens? Do you get an error message? Does something unexpected happen?
|
[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
|
 |
Kieran Murray
Ranch Hand
Joined: May 18, 2008
Posts: 47
|
|
Hi Jeanne, Thank you. Apologies for too much code. I have removed all the extra pieces of code. The problem as far as I understand it is the line Object[][] data1=ui.saveModel(); in the getJTableFields(File file) in the PowerFrame class. It does not load what is on the screen. The screen at startup loads with rows of "no". The user changes them and should be able to save the updated data to a file. The console in Eclipse shows that the copied data is not the updated data. I include the shortened files. If this is still too much - tell me what would help and I will try and do it. Kind regards, Kieran Beginning of PowerFrame class End of PowerFrame class BusbarUI class End of BusbarUI class BusbarRecords class End of BusbarRecords class JavaFilter class
|
 |
Darryl Burke
Bartender
Joined: May 03, 2008
Posts: 4163
|
|
|
http://forum.java.sun.com/thread.jspa?threadID=5297047
|
luck, db
There are no new questions, but there may be new answers.
|
 |
Kieran Murray
Ranch Hand
Joined: May 18, 2008
Posts: 47
|
|
Is there a problem with sending the same problem to you and to the sun team. Kind regards, Kieran
|
 |
Kieran Murray
Ranch Hand
Joined: May 18, 2008
Posts: 47
|
|
With regret would you mind canceling this topic. I posted the question originally on the sun forum website and I can see now that having two teams working on the same problem is unfair. Kind regards, Kieran
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32599
|
|
Yes, there is a problem, and thank you Darryl Burke for pointing this out. You have presumably read what "encephalopathic" wrote on the Sun forum? It wastes time when we try to answer the same problems here, even worse if we have two postings on JavaRanch. Please decide which forum you wish to continue the discussion on; on Sun you said you would continue here. Suggest you post a reply on the sun forum requesting all answers be given here. Otherwise I might close this thread.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32599
|
|
I have checked with the other moderators, who say it is usually regarded as permissible to post on several websites. You have said on Sun that you wish to continue the discussion there, so I shall suggest people direct their replies to the link which Darryl Burke posted earlier. But I shall leave the post open, I shall transfer your other post because it is not really a "beginner's" question, and I seem to have overreacted rather, so I wish to apologise for overreacting. I hope you will be happy to post your next question here, but suggest you point out if you are posting on two websites.
|
 |
Kieran Murray
Ranch Hand
Joined: May 18, 2008
Posts: 47
|
|
Dear Campbell, I did read what was written on the sun forum. Please close this thread as I asked the question first on the Sun forum site. I said on the sun forum site that I would continue the question there. As I said there, this is my first time using forums for software questions and I do not know the etiquette. Sincere apologies. Kieran A. Murray
|
 |
Kieran Murray
Ranch Hand
Joined: May 18, 2008
Posts: 47
|
|
Dear Campbell, In view of the fact that some of the team at Sun feel I might have wasted their time I must decline your kind offer of working on this issue. I am thankful for your offer and can understand why people feel that I may have wasted their time. Kind regards, Kieran
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32599
|
|
Apologies accepted, and I hope you will feel happy posting here again. I can't remember my login on Sun, so I shall have to reply here regardless. If you are using eclipse, use the "debug" feature rather than "run" to start off your app. You can set breakpoints by double-clicking on the left of the line in the code and you get a little blue blob. When you debug, the code runs until you get to your next breakpoint, then you can click on the buttons toStep into (goes to the next line, or if a method call, into that method)Step over (goes to the next line. If a method call completes that method without showing details)Step return (completes present method and goes back to wherever it was called from)You can execute each of these actions with an f-key, I think f5 f6 f7. At each stage, you can get up a window which shows the values of all the variables (local and fields). Set a breakpoint near where you think your values change from no no no, and follow the execution and see whether they change as you expect.
|
 |
 |
|
|
subject: Problems passing data into file from JTable
|
|
|