Jtable Daten ändern nach dem Tabelle erstellt wurde

Ethan_Hunt

Grünschnabel
Hallo zusammen,

ich sitze seit einigen Tagen vor einem kleinen Problemchen und komme nicht weiter - auch nach dem ich mich hier im Tutorial durch einige Themen geklickt habe.

Ich möchte gerne mit Java eine Tabelle erstellen. Es soll möglich sein, dass der User in der Tabelle Änderungen vornehmen bzw. Daten hinzufügen kann. Anschließend möchte ich die eingegebenen Daten auswerten und das Ergebnis dieser Auswertung in der Tabelle ausgeben.

Bisher habe ich versucht das Ganze mit einer Jtable zu lösen, ich scheitere jedoch daran die Daten aus der Tabelle auszulesen und diese anschließend in der Tabelle wieder auszugeben.

Hat jemand eine Idee, wie man dieses Problem lösen könnte oder sogar ein Beispielprogramm.

Vielen Dank schon einmal für eure Hilfe!

Ethan
 
Wie bist du da ran gegangen? Ich nehme mal an, das Konzept der GenericTableModel-Klasse ist bekannt? Zeig mal deinen Versuch, dann können wir darauf aufbauen.
 
Hi Ethan_Hunt,

hab dir mal ein kleines Testprogramm geschrieben. Reicht für kleinere Tabellen auf jeden Fall aus:
Java:
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class JTableTest extends JFrame implements ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3985822080551726487L;
	private JTable input;
	private JTable output = new JTable();
	private JButton analyse = new JButton("Analyse Starten");
	private JScrollPane scpOutput;
	public static void main(String[]args){
		new JTableTest();
	}
	public JTableTest() {
		Dimension d = new Dimension(
				Toolkit.getDefaultToolkit().getScreenSize().width/2, Toolkit
						.getDefaultToolkit().getScreenSize().height/5);
		this.setTitle("Tabellen Test");
		this.setSize(d);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLayout(new GridLayout(0, 3));

		String[][] rowData = { { "Japan", "245" }, { "USA", "240" },
				{ "Italien", "220" }, { "Spanien", "217" },
				{ "Türkei", "215" }, { "England", "214" },
				{ "Frankreich", "190" }, { "Griechenland", "185" },
				{ "Deutschland", "180" }, { "Portugal", "170" } };

		String[] columnNames = { "Land",
				"Durchschnittliche Fernsehdauer pro Tag in Minuten" };
		
		input = new JTable( rowData, columnNames );
		scpOutput = new JScrollPane();
		analyse.addActionListener(this);
		this.add( new JScrollPane(input));
		this.add(analyse);
		this.add(scpOutput);
		this.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		String [][] rowData = new String[input.getRowCount()][input.getColumnCount()];
		for (int i = 0; i < input.getRowCount(); i++) {
			for (int j = 0; j < input.getColumnCount(); j++) {
				rowData[i][j] = analyseValue(String.valueOf(input.getModel().getValueAt(i, j)));
			}
		}
		String[] columnNames = { "Land",
		"Analyse" };
		this.remove(scpOutput);
		output = new JTable( rowData, columnNames ); 
		scpOutput = new JScrollPane(output);
		this.add(scpOutput);
		
		this.validate();
		this.invalidate();
		this.repaint();
	}
	private String analyseValue(String value){
		try{
			value = String.valueOf("a" + Double.parseDouble(value));
		}catch(NumberFormatException ne){
			return value;
		}
		return value;
	}
}

Viele Grüße
Youza
 
Hallo,

vielen Dank erst einmal für die schnellen Antworten. Ich habe mich noch einmal etwas mit dem Hinweis der GenericTableModel-Klasse beschäftigt.

Ich habe nun, nachdem ich mir einige Beispielprogramme angeschaut habe, mein eigenes Programm erweitert.

Jedoch scheint es bei mir einen Fehler bei dem Befehl "fireTableCellUpdated" zu geben.

Könntet ihr euch meinen Quelltext einmal anschauen? Vielleicht findet ihr ja meinen Fehler bzw. habt eine Idee wie ich das Ganze lösen könnte.

Code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.JPanel;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import java.awt.Dimension;
import java.awt.Component;
import javax.swing.BoxLayout;
 
 
 
 
public class Tableau extends JPanel
implements  TableModelListener {
        private JTable table;
        private boolean DEBUG = false;
        
        public Tableau() {
               super();
              
               setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
              
               table = new JTable(new MyTableModel());
               table.setPreferredScrollableViewportSize(new Dimension(500, 70));
               table.setFillsViewportHeight(true);
        
               //Create the scroll pane and add the table to it.
               JScrollPane scrollPane = new JScrollPane(table);
        
               //Add the scroll pane to this panel.
               add(scrollPane);
              
               //Add another button
              
               JButton rechnenButton = new JButton("rechnen");
               rechnenButton.setAlignmentX(Component.CENTER_ALIGNMENT);
               
               final AbstractTableModel model = new MyTableModel();
               rechnenButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
             
                      int row = table.getSelectedRow();
                          int column = table.convertColumnIndexToModel(table.getSelectedColumn());
                          String currentValue=(String)model.getValueAt(row, column);
                          System.out.println(currentValue);
                      
                          model.setValueAt(new Integer(5), row, column);
                        }
                      });
 
               add(rechnenButton);
               table.getModel().addTableModelListener(this);
              
        }
        
        
        class MyTableModel extends AbstractTableModel {
              private String[] columnNames = {"U",
                 "A",
                 "1",
                 "2",
                 "3",
                 "4",
                 "B",
                 "C",
                 "D",
                 "E",
                 "F"};
             private Object[][] data = {
             {"1", " ","", "1","5","4","","","","",""},
             {"2", " ","4", "","6" ,"5","","","","",""},
             {"3", " ","5","8", "","5","","","","",""},
             {"4", " ","4", "4","5","","","","","",""} };
            
               public int getColumnCount() {
                   return columnNames.length;
               }
        
               public int getRowCount() {
                   return data.length;
               }
        
               public String getColumnName(int col) {
                   return columnNames[col];
               }
        
               public Object getValueAt(int row, int col) {
                   return data[row][col];
               }
              
               public void setValueAt(Object obj, int r, int c) {
                    System.out.println(r+" "+c);
                    data[r][ c] = obj.toString();
                    System.out.println(data[r][ c]);
                   fireTableCellUpdated(r, c);
                 }
               public boolean isCellEditable(int row, int col) {
                  
                    
                   if (col==2&&row==0) {
                       return false;
                   }
                 
                   if (col==3&&row==1) {
                       return false;
                   }
                 
                   if (col==4&&row==2) {
                       return false;
                   }
                 
                   if (col==5&&row==3) {
                       return false;
                   }
                 
                   //Note that the data/cell address is constant,
                   //no matter where the cell appears onscreen.
                   if (col < 1) {
                       return false;
                   } else {
                       return true;
                   }
                 
               
        
 
        }
        }
        
         public void tableChanged(TableModelEvent e) {
               int row = e.getFirstRow();
               int column = e.getColumn();
             
               TableModel model = (TableModel)e.getSource();
               String columnName = model.getColumnName(column);
               Object data = model.getValueAt(row, column);
           
               //Objekt wird an array1 weitergegeben
                   String s = data.toString();
                  
        
           }
        
         /**
            * Create the GUI and show it.  For thread safety,
            * this method should be invoked from the
            * event-dispatching thread.
            */
           private static void createAndShowGUI() {
               //Create and set up the window.
               JFrame frame = new JFrame("TablePrintDemo");
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
               //Create and set up the content pane.
               Tableau newContentPane = new Tableau();
               newContentPane.setOpaque(true); //content panes must be opaque
               frame.setContentPane(newContentPane);
        
               //Display the window.
               frame.pack();
               frame.setVisible(true);
           }
        
           public static void main(String[] args) {
               //Schedule a job for the event-dispatching thread:
               //creating and showing this application's GUI.
               javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                       createAndShowGUI();
                   }
               });
           }
       }
 

Neue Beiträge

Zurück