Announcement

Collapse
No announcement yet.

JTable Daten serialisieren, lesen und schreiben

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • JTable Daten serialisieren, lesen und schreiben

    Hallo an alle,
    ich sitze schon seit Tagen an meinem Java Projekt für das Studium und habe nicht mehr allzu viel Zeit das Projekt fertig zu stellen und bitte euch um eure Hilfe.

    Zum Programm:
    Ich bin gerade am Schreiben einer Buchverwaltung mittels JTable. Es gibt 5 Spalten: "Title,Author,Release,ISBN,Summary". Ich benutze ein DefaultTableModel in meinem JTable.

    Zur Problemstellung:
    Ich möchte, dass die Daten von dem JTable/DefaultTableModel in eine Datei geschrieben und von einer Datei gelesen werden mittels einen JFileChooser, doch weiss ich nicht so recht wie ich da vorgehen sollte.
    Wenn ich auf die Menüleiste File>Save gehe, sollte der JFileChooser sich öffnen (soweit hab ich es geschafft) und dann sollte man den Ort wählen, wo man eine Datei speichert.
    Wenn ich auf die Menüleiste File>Load gehe sollte das gleiche wie oben geschen, nur dass nicht gespeichert sondern eine bereits gespeicherte Datei geöffnet werden soll

    Es geht hauptsächlich nur um 2 Methoden, die ich hier farblich kennzeichnen werde, ich stelle die wichtigsten Sachen rein.

    Die vielen Beispiele die man im Web findet, finde ich persönlich etwas kompliziert und brauche einen spezifischen Lösungsvorschlag

    Ich wäre euch sehr dankbar wenn ihr mir bei diesem Problem helfen könntet :-)

    Code:
    package bookmanager.version6;
    
    
    public class Book extends JFrame {
    	
    	private static JDialog dialog;
    	
    	private static Container mainPanel;
    	
    	private static JScrollPane scroll;
    
    	private static JPanel buttonPanel;
    	private static JPanel checkPanel;
    	private static JPanel dialogPanel;
    	
    	private static BorderLayout border;
    	
    	private static GridLayout grid;
    	
    	private static JTable table;
    	
    	private static DefaultTableModel defModel;
    	
    	private static JMenuBar bar;
    	private static JMenu file;
    	private static JMenuItem save;
    	private static JMenuItem load;
    	private static JMenuItem exit;
    
    	private static JCheckBox check;
    	
    	private static JLabel titleText;
    	private static JLabel text;
    	private static JLabel title;
    	private static JLabel author;
    	private static JLabel release;
    	private static JLabel isbn;
    	private static JLabel summary;
    	
    	private static JTextField fieldTitle;
    	private static JTextField fieldAuthor;
    	private static JTextField fieldRelease;
    	private static JTextField fieldISBN;
    	private static JTextArea fieldSummary;
    	
    	private static JButton buttonAdd;
    	private static JButton buttonAdd2;
    	private static JButton buttonCancel;
    	
    	private static JButton buttonLoad;
    	
    	private static int id;
    	private static Object[] columnNames = {"ID","Title","Author","Release","ISBN","Summary"};
    	
    	
    	// Konstruktor
    	Book(String title, int x, int y) throws FileNotFoundException
    	{
    		// Ruft die Methode createGUI() auf, welche das GUI erstellt
    		createGUI(title,x,y);
    		
    		// Ruft die Methode auf, die die oben erstellten Objekte initialisiert
    		// bzw Werte zuweist
    		init();
    		
    		// Methode aufrufen, welche die Tabellen manipuliert
    		editTable();
    				
    		// Methode aufrufen, die es erlaubt ein neues Buch / eine neue
    		// Zeile zu erstellen
    		newBook();
    		addToDatabaseButton();
    		
    		dialogClose();
    		
    		saveData();
    		
    		// Methode aufrufen, die es erlaubt, das Programm zu beenden
    		exitProgram();
    	}
    	
    	// Die Methode init() initialisiert die oben erstellten Objekte und
    	// fügt diese dann dem Fenster hinzu
    	public void init()
    	{						
        	dialog = new JDialog(this,"Add a Book",true);
    
    		dialogPanel	=	new JPanel();
    		
    		mainPanel	=	new Container();
    		
    		buttonPanel	=	new JPanel();
    				
    		checkPanel	=	new JPanel();
    		
    		border		=	new BorderLayout();
    		
    		grid		= 	new GridLayout();
    		
    		mainPanel.setLayout(border);
    		checkPanel.setLayout(grid);
    		
    		defModel	=	new DefaultTableModel(null,columnNames);		
    		
    		bar			= 	new JMenuBar();
    		file		=	new JMenu("File");
    		load		=	new JMenuItem("Load");
    		save		=	new JMenuItem("Save");
    		exit		=	new JMenuItem("Exit");
    		
    		table		= 	new JTable(defModel);
    		
    		scroll		=	new JScrollPane(table);
    		
    		check		= 	new JCheckBox();
    		
    		buttonAdd	=	new JButton("New Book");
    		buttonAdd2	=	new JButton("Add to Database");
    		buttonCancel=	new JButton("Cancel");
    		buttonLoad	=	new JButton("Load Database");
    		
    		id			=	0;
    		
    		titleText	=	new JLabel("Book Manager v. 0.3");
    		text		=	new JLabel("Geben Sie hier das Buch ein.");
    		title		=	new JLabel("Title");
    		author		=	new JLabel("Author");
    		release		=	new JLabel("Release");
    		isbn		=	new JLabel("ISBN");
    		summary		=	new JLabel("Summary");
    		
    		addFont(text,16);
    		addFont(title,14);
    		addFont(author,14);
    		addFont(titleText,24);
    		addFont(release,14);
    		addFont(isbn,14);
    		addFont(summary,14);
    		
    		fieldTitle		=	new JTextField(null,20);
    		fieldTitle.setDocument(new SetMaxText(25));
    		fieldAuthor		=	new JTextField(null,20);
    		fieldAuthor.setDocument(new SetMaxText(25));
    		fieldRelease	=	new JTextField(null,4);
    		fieldRelease.setDocument(new SetMaxText(4));
    		fieldISBN		=	new JTextField(null,13);
    		fieldISBN.setDocument(new SetMaxText(13));
    		fieldSummary	=	new JTextArea();
    		fieldSummary.setDocument(new SetMaxText(255));
    		fieldSummary.setAutoscrolls(true);
    		
    		this.add(mainPanel);
    		this.setJMenuBar(bar);
    		bar.add(file);
    		file.add(load);
    		file.add(save);
    		file.add(exit);
    		
    		mainPanel.add(titleText,border.NORTH);
    		mainPanel.add(scroll,border.CENTER);
    		mainPanel.add(buttonPanel,border.SOUTH);
    		mainPanel.add(checkPanel, border.EAST);
    		
    		buttonPanel.add(buttonAdd);
    		buttonPanel.add(buttonLoad);
    
    
    	}
    	
    	public static void addBook(final String index0, final String index1, final String index2, final String index3, final String index4)
    	{
    
                	// Id ist eindeutig für jedes Buch, dass angelegt wird
                	id++;
                	
                    // Array erstellen mit default Werten in jeder Zeile
                    Object[] data = {id,index0,index1,index2,index3,index4};
                    
                    // eine neue Zeile hinzufügen
                    defModel.addRow(data);
    
    	}
    	
    	public static void newBook()
    	{
            buttonAdd.addActionListener( new ActionListener(){
                public void actionPerformed(ActionEvent e) {
            		createDialog();
                }
            });
    
    	}
    	
    	public static void addDefaultValues(int id, String title, String author, String ISBN, String date, String summary)
    	{
    		id++;
    		Object[] data		=	new Object[]
    		{
    				id,title,author,ISBN,date,summary
    		};
    		defModel.addRow(data);
    	}
    	
    	
    	public void exitProgram()
    	{
            exit.addActionListener( new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                	System.exit(0);
                }
            });
    	}
    	
    	public void addToDatabaseButton()
    	{
            buttonAdd2.addActionListener( new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                	String index0 = fieldTitle.getText();
                	String index1 = fieldAuthor.getText();
                	String index2 = fieldRelease.getText();
                	String index3 = fieldISBN.getText();
                	String index4 = fieldSummary.getText();
                	addBook(index0,index1,index2,index3,index4);
                }
            });
    	}
    	
    	public static void addFont(Component comp,int size)
    	{
    		comp.setFont(new Font("Times New Roman",Font.BOLD,size));
    	}
    	
    	// Methode zum speichern der Daten
    	public static void saveData() throws FileNotFoundException
    	{
            save.addActionListener( new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                	JFileChooser fileSave	=	new JFileChooser();
                	fileSave.setDialogTitle("Please Choose a file");
                	fileSave.setVisible(true);
                	fileSave.showSaveDialog(null);
                	FileNameExtensionFilter filter = new FileNameExtensionFilter("txt", "book");
                    fileSave.setFileFilter(filter);
                    File file	=	new File("BookManager.book");
                	
                	try 
                	{
    					FileOutputStream fileoutput		=	new FileOutputStream(file);
    					ObjectOutputStream output = new ObjectOutputStream(fileoutput);
    					output.writeObject(defModel);
    				} 
                	catch (FileNotFoundException e1) 
    				{
    					e1.printStackTrace();
    				} catch (IOException e2) {
    					e2.printStackTrace();
    				}
    
                }
            });
    	}
    	
    	// Methode zum laden der Daten
    	public static void loadData() throws FileNotFoundException
    	{
            load.addActionListener( new ActionListener(){
                public void actionPerformed(ActionEvent e) {
    
                	try 
                	{
                    	String filename		=	"BookManager.book";
                        FileInputStream file = new FileInputStream( filename );
                        ObjectInputStream o = new ObjectInputStream( file );
                        defModel = (DefaultTableModel) o.readObject();
                        o.close();
    				} 
                	catch (FileNotFoundException e1) 
    				{
    					e1.printStackTrace();
    				} catch (IOException e2) {
    					e2.printStackTrace();
    				} catch (ClassNotFoundException e3) {
    					e3.printStackTrace();
    				}
    
                }
            });
    	}
    	
    	public static int getID()
    	{
    		return id++;
    	}
    }

  • #2
    Du versuchst offenbar das DefaultTableModel selbst zu speichern und wieder zu laden

    Und? Was ist die Frage?

    Warum immer so kompliziert und nicht einfach die Daten wegschreiben und wieder lesen?

    Hier mal ein Beispiel:

    Bild1.jpg



    Code:
     
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.FileWriter;
    import javax.swing.table.DefaultTableModel;
    public class NewJDialog extends javax.swing.JDialog
    {
        private javax.swing.JButton clearTableButton;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JButton loadTableButton;
        private javax.swing.JButton saveTableButton;
        private javax.swing.JTable tabelle;
    public NewJDialog(java.awt.Frame parent,boolean modal)
        {
        super(parent,modal);
        initComponents();
        }
    @SuppressWarnings("unchecked")
         private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            tabelle = new javax.swing.JTable();
            saveTableButton = new javax.swing.JButton();
            clearTableButton = new javax.swing.JButton();
            loadTableButton = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            tabelle.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {"a", "aa", "aaa", "aaaa"},
                    {"b", "bb", "bbb", "bbbb"},
                    {"c", "cc", "ccc", "cccc"},
                    {"d", "dd", "ddd", "dddd"}
                },
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
                }
            ));
            jScrollPane1.setViewportView(tabelle);
            saveTableButton.setText("Speichere Tabelle");
            saveTableButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    saveTableButtonActionPerformed(evt);
                }
            });
            clearTableButton.setText("Lösche Tabelle");
            clearTableButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    clearTableButtonActionPerformed(evt);
                }
            });
            loadTableButton.setText("Lade Tabelle");
            loadTableButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    loadTableButtonActionPerformed(evt);
                }
            });
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(saveTableButton)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(clearTableButton)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(loadTableButton)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(saveTableButton)
                        .addComponent(clearTableButton)
                        .addComponent(loadTableButton))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
            pack();
        }
     
     
     private void loadTableButtonActionPerformed(java.awt.event.ActionEvent evt) {
         DefaultTableModel deft=(DefaultTableModel)tabelle.getModel();
         clearTableButtonActionPerformed(null);
         try
             {
             FileReader fr=new FileReader("c:\\test.txt");
             BufferedReader br=new BufferedReader(fr);
             String zeile;
             while((zeile=br.readLine())!=null)
                 {
                 String[] teile=zeile.split("#");
                 deft.addRow(new Object[]
                             {
                             teile[0],teile[1],teile[2],teile[3],
                             });
                 }
             fr.close();
             }
         catch(Exception e)
             {
             System.out.println("Lesefehler: "+e.getMessage());
             }
     }
     
     
        private void saveTableButtonActionPerformed(java.awt.event.ActionEvent evt) {
         DefaultTableModel deft=(DefaultTableModel)tabelle.getModel();
         try
             {
             FileWriter fw=new FileWriter("c:\\test.txt");
             for(int row=0;row<deft.getRowCount();row++)
                 {
                 StringBuilder sb=new StringBuilder();
                 for(int col=0;col<deft.getColumnCount();col++)
                     {
                     sb.append(deft.getValueAt(row,col)).append("#");
                     }
                 sb.append(System.getProperty("line.separator"));
                 fw.write(sb.toString());
                 }
             fw.close();
             }
         catch(Exception e)
             {
             System.out.println("Schreibfehler: "+e.getMessage());
             }
     }
        private void clearTableButtonActionPerformed(java.awt.event.ActionEvent evt) {
            ((DefaultTableModel)tabelle.getModel()).setRowCount(0);
        }
    public static void main(String args[])
        {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
        public void run()
            {
            NewJDialog dialog=new NewJDialog(new javax.swing.JFrame(),true);
            dialog.addWindowListener(new java.awt.event.WindowAdapter()
            {
            public void windowClosing(java.awt.event.WindowEvent e)
                {
                System.exit(0);
                }
            });
            dialog.setVisible(true);
            }
        });
        }
    }
    Zuletzt editiert von Christian Marquardt; 20.12.2010, 18:56.
    Christian

    Comment


    • #3
      JFileChooser

      Okay vielen Dank für diese schnelle Antwort,
      ich habe es in meinem Programm umgesetzt und es läuft wunderbar, doch wollte ich wissen, wie ich das mit dem JFileChooser umsetze, also Wenn ich auf den Menüpunkt oder Button klicke, sich dann der FileChooser öffnet und ich dann entscheiden kann wo ich die Textdatei speichere oder lade.

      Ich hätte noch eine kleine Frage, und zwar muss ich noch Checkboxen einbauen, ich habe irgendwas von tablecellrenderer gehört doch weiss ich nicht wie ich diese in dieses jtable einbaue. ich möchte, dass dass sich in der letzten Spalte in jeder Zelle eine Checkbox entsteht. Kann mir jemand noch ein kleines einfaches Beispiel geben?

      Diese Beispiele im Internet finde ich irgendwie zu kompliziert. Ich bedanke mich im vorraus!


      PS: So habe ich das umgesetzt:
      Code:
      [ public static void saveData() throws FileNotFoundException
      {
      save.addActionListener( new ActionListener(){
      public void actionPerformed(ActionEvent e) {
      /*
      JFileChooser fileSave = new JFileChooser();
      fileSave.setDialogTitle("Please Choose a file");
      fileSave.setVisible(true);
      fileSave.showSaveDialog(null);
      */
      try
      {
      FileWriter fw=new FileWriter("c:\\test.txt");
      for(int row=0;row<defModel.getRowCount();row++)
      {
      StringBuilder sb=new StringBuilder();
      for(int col=0;col<defModel.getColumnCount();col++)
      {
      sb.append(defModel.getValueAt(row,col)).append("#" );
      }
      sb.append(System.getProperty("line.separator"));
      fw.write(sb.toString());
      }
      fw.close();
      }
      catch(Exception e1)
      {
      System.out.println("Fehler beim Schreiben aufgetreten: "+e1.getMessage());
      }
      }
      });
      }
      
      // Methode zum laden der Daten
      public static void loadData() throws FileNotFoundException
      {
      load.addActionListener( new ActionListener(){
      public void actionPerformed(ActionEvent e) {
      ((DefaultTableModel)table.getModel()).setRowCount( 0);
      try
      {
      FileReader fr=new FileReader("c:\\test.txt");
      BufferedReader br=new BufferedReader(fr);
      String row;
      while((row=br.readLine())!=null)
      {
      String[] index=row.split("#");
      defModel.addRow(new Object[]
      {
      index[0],index[1],index[2],index[3],
      });
      }
      fr.close();
      }
      catch(Exception e1)
      {
      System.out.println("Fehler beim Lesen aufgetreten: "+e1.getMessage());
      }
      }
      });
      }

      mfg

      e-styles
      Zuletzt editiert von Christian Marquardt; 04.01.2021, 20:27.

      Comment


      • #4
        JFileChooser:
        Code:
            JFileChooser chooser=new JFileChooser();
            FileNameExtensionFilter filter=new FileNameExtensionFilter("XML","xml");
            chooser.setAcceptAllFileFilterUsed(false);
            chooser.setMultiSelectionEnabled(false);
            chooser.addChoosableFileFilter(filter);
            chooser.setDialogTitle("Titel");
            int returnVal=chooser.showDialog(this.getFrame(),"Buttontext");
            if(returnVal==JFileChooser.APPROVE_OPTION)
                {
                 //Der Anwender hat den OK-Button gedrückt
                }
        Christian

        Comment


        • #5
          Checkboxen:

          Der Spalte ein boolean zuorden:

          Beispiel

          Code:
                 tblMails.setModel(new javax.swing.table.DefaultTableModel(
                      new Object [][] {
                      },
                      new String [] {
                          "Konto", "Absender", "Datum / Zeit", "Betreff", "Löschen", "ID"
                      }
                  ) {
                      Class[] types = new Class [] {
                          java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Boolean.class, java.lang.String.class
                      };
                      boolean[] canEdit = new boolean [] {
                          false, false, false, false, true, false
                      };
                      public Class getColumnClass(int columnIndex) {
                          return types [columnIndex];
                      }
                      public boolean isCellEditable(int rowIndex, int columnIndex) {
                          return canEdit [columnIndex];
                      }
                  });
          Zuletzt editiert von Christian Marquardt; 20.12.2010, 22:02.
          Christian

          Comment


          • #6
            Super Erklärung!

            Hallo Christian,
            vielen Dank für die Hilfe, habe jetzt mein Projekt fast geschafft, super gut hast du es erklärt!


            mfg

            e-styles

            Comment


            • #7
              Neues Problem, neues Thema

              http://entwickler-forum.de/showthread.php?t=65409
              Christian

              Comment

              Working...
              X