Swing JTable custom ColumnModel Problem

Bib

Mitglied
Hallo,

ich versuche jeweils ein eigenes TableModel und TableColumnModel zu realisieren. Kein Problem mit dem TableModel, aber sobald ein ColumnModel ins Spielkommt geht nichts mehr. Suche jetzt seit mehreren Nächten eine Lösung. (IDE ist Netbeans 6.9.1) Mittelfristiges Ziel ist, jeweils ein TableModel, ein ColumnModel und einen CellRenderer in jeweils eigener Klasse für einfache Wiederverwendung und Anpassung zu haben.

Folgender Code funktioniert, die Tabelle wird entsprechend dem Model angezeigt und befüllt,

Java:
    TableModel tm = new warp.Tables.TablePanelDayViewTableModel();

    //TableColumnModel tcm = new warp.Tables.TablePanelDayViewColumnModel();
    dayViewTable = new javax.swing.JTable(tm); // oder (tm,tcm) vorige Zeile aktiv

    dayViewTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);

    dayViewTable.setFillsViewportHeight(true);

    dayViewTable.setMaximumSize(new java.awt.Dimension(30000, 30000));

    dayViewTable.setMinimumSize(new java.awt.Dimension(10, 10));

    dayViewTable.setName("dayViewTable"); // NOI18N

    dayViewTable.setPreferredSize(new java.awt.Dimension(429, 768));

    dayViewTable.getTableHeader().setReorderingAllowed(false);
    Font f = new Font("Tahoma",Font.BOLD ,11);
    dayViewTable.getTableHeader().setFont(f);
    jScrollPane1.setViewportView(dayViewTable);

Sobald nun das Column Model dazu kommt, (d.h. 3. Zeile aktivieren und Konstruktoraufruf in 4. Zeile anpassen) wird keine Tabelle mehr angezeigt. Auch wenn die Zeile mit 'super();' auskommentiert ist funktioniert es nicht. Der print-Befehl wird jedoch korrekt abgearbeitet, d.H. der Konstruktor wir gerufen. (Gilt auch für das TableModel)

Hier nun der Code vom ColumnModel:

Java:
    public class TablePanelDayViewColumnModel extends DefaultTableColumnModel {


    public TablePanelDayViewColumnModel(){

       super();

       System.out.println("Column model called." );


     }
   }

Ich habe schon alles mögliche ausprobiert, (Verschieben der Models in innere Klassen, diverse Varianten der Codierung etc., leider alles ohne Erfolg. Was sich als Hinweis noch sagen läst, ist dass

Java:
  System.out.println(" ColCount = " + dayViewTable.getColumnModel().getColumnCount());

egal wann und von wo es aufgerufen wird immer '0' zurückgibt, obwohl im TableModel 2 Spalten hart codiert angelegt werden.
Was mir gedanklich auch fehlt ist die eigentliche Verbindung zur Tabelle, aber es gibt auch keinen Konstruktor von DefaultColumnModel dem eine Tabelle übergeben werden kann, also muss es auch hier mit der setColumnMode() Methode getan sein. Aus dieser Überlegung resultiert auch der Ansatz mit der inneren Klasse um auf die Variablen (Tabelle) der umgebenden Klasse zugreifen zu können.
Der obige Code muss meines Erachten nach eigentlich funktional identisch mit dem DefaultColumnModel sein.
Ist aber wohl nicht so. Wer weiß hier Rat? Danke schon jetzt!

Bib
 
Zuletzt bearbeitet:
Hallo Bib.

Wahrscheinlich fehlen noch die TableColumns.

für jede Column muß wenigstens:
Java:
tcm.addColumn(new TableColumn());

oder z.B.

Java:
class MyColumnModel extends DefaultTableColumnModel {
        public MyColumnModel(int columnCount){
            super();
            for (int i = 0; i < columnCount; i++)
                this.addColumn(new TableColumn());
        }
        public MyColumnModel(Vector<TableColumn> columns){
            super();
            for (TableColumn tc : columns)
                this.addColumn(tc);
        }
}


Gruß Attila
 
Zuletzt bearbeitet:
Hallo Attila,


erst mal Danke für die schnelle Rückmeldung!
Dein Vorschlag ist im Ansatz gelungen, aber noch nicht perfekt. Ich bekomme nun zwei Spalten angezeigt, aber 2x die erste aus dem TableModel, die zweite fehlt dafür. Hab noch keine Idee hierzu. Code der aktuellen Klasse anbei. ColumnCount ist hier noch hart codiert, aber das sollte am Prinzip nichts ändern. Auch das TableModel habe ich zum besseren Verständnis noch beigefügt.

Und ich habe den Ansatz auch noch nicht ganz verstanden. Warum muss ich die Columns im custom ColumnModel erzeugen wenn es im DefaultColumnModel, das extended wird, doch auch ohne dies geht? Es wird doch eigentlich über den call von 'super()' der selbe Code ausgeführt.

Java:
public class TablePanelDayViewColumnModel extends DefaultTableColumnModel{


   public TablePanelDayViewColumnModel(){

       super();
       
            for (int i = 0; i < 2; i++)
                this.addColumn(new TableColumn());

       System.out.println("Column model called." );
  
    }

    public TablePanelDayViewColumnModel(Vector<TableColumn> columns){
            super();
            for (TableColumn tc : columns)
                this.addColumn(tc);
        }
}

Und hier das TableModel:

Java:
public class TablePanelDayViewTableModel extends AbstractTableModel
 
    {

    //TODO: Add id for serializazion


    // Constructor, fire-command makes the table redraw itself from scratch
    public TablePanelDayViewTableModel(){

        // TODO: Get data from database first
        
        fireTableStructureChanged();
        System.out.println("Table Model called.");
        
    }



 
    // Variables defininig the table structure
    String columnNames[] = {"ZEIT","EREIGNIS"};
    public int rowCount = 48;
    public int columnCount = 2;
    
    
    // Variables holding the table Data
    String data [][] = {

        {" 00:00 ", null},
        {" 00:30 ", null},
        {" 01:00 ", null},
        {" 01:30 ", null},
        {" 02:00 ", null},
        {" 02:30 ", null},
        {" 03:00 ", null},
        {" 03:30 ", null},
        {" 04:00 ", null},
        {" 04:30 ", null},
        {" 05:00 ", null},
        {" 05:30 ", null},
        {" 06:00 ", null},
        {" 06:30 ", null},
        {" 07:00 ", null},
        {" 07:30 ", null},
        {" 08:00 ", "START der ganzen Mühsal"},
        {" 08:30 ", null},
        {" 09:00 ", null},
        {" 09:30 ", null},
        {" 10:00 ", null},
        {" 10:30 ", null},
        {" 11:00 ", null},
        {" 11:30 ", null},
        {" 12:00 ", null},
        {" 12:30 ", null},
        {" 13:00 ", null},
        {" 13:30 ", null},
        {" 14:00 ", null},
        {" 14:30 ", null},
        {" 15:00 ", null},
        {" 15:30 ", null},
        {" 16:00 ", null},
        {" 16:30 ", null},
        {" 17:00 ", null},
        {" 17:30 ", null},
        {" 18:00 ", "Und nu is allet am Ende"},
        {" 18:30 ", null},
        {" 19:00 ", null},
        {" 19:30 ", null},
        {" 20:00 ", null},
        {" 20:30 ", null},
        {" 21:00 ", null},
        {" 21:30 ", null},
        {" 22:00 ", null},
        {" 22:30 ", null},
        {" 23:00 ", null},
        {" 23:30 ", null}
    };


    
    // set public variable 'rowCount'
    public void setRowCount(int rows){
        
        fireTableStructureChanged();
        rowCount = rows;

    }

    // gets value of variable 'rowCount'
    public int getRowCount(){

        return rowCount;
    }

    // set public variable 'columnCount'
    public void setColumnCount(int cols){

        fireTableStructureChanged();
        columnCount = cols;
    }
    // gets value of variable 'columnCount'
    public int getColumnCount(){

        return columnNames.length;
    }

    // gets value of variable 'columnCount'
    public String getColumnName(int column){

        return (String) columnNames[column];
    }


    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {

        data [rowIndex][columnIndex] = (String)aValue;
        fireTableDataChanged();
    }

    public Object getValueAt(int rowIndex, int columnIndex){

        return (String) data [rowIndex][columnIndex];
    }

    public boolean isCellEditable(int rowIndex, int columnIndex) {

        if (columnIndex > 0){
                
            return true;
        }

        else {

            return false; 
        }
    }
}

Wo klemmts denn bei mir so fürchterlich?

Gruß

Bib
 
Hallo Bib.

Java:
class MyColumnModel extends DefaultTableColumnModel {
        public MyColumnModel(int columnCount){
            super();   //instanz. DefaultTableColumnModel
            for (int i = 0; i < columnCount; i++)
                this.addColumn(new TableColumn(i));  // hier war ein kleiner Fehler: index i
       }

DefaultTableColumnModel nach seiner Instanziierung enthält noch keine TableColumn Objekten.

Gruß Attila
 
Zuletzt bearbeitet:
Hallo Attila,

danke für die Rückmeldung. Auf die Sache mit dem '(i)' hätteich auch kommen sollen. Brumpf, Grummel.
Tut natürlich gleich richtig.

Ich hab aber immer noch den Knoten im Kopf was das Verständnis vom DefaultColumModel angeht. In diesem werden im Konstruktor ja nur ein paar Standards gesetzt ohne das Instanzen von Columns gebildet werden. Für mein Verständnis ist dies der Job vom TableModel.
Das ColumnModel setzt Defaults für einige Parameter und stellt die Methoden zur Bearbeitung von Columns bereit. Hier will ich weitere Methoden implementieren um meine Tabelle anzupassen.
Aber wenn zusätzlich zum Konstruktor eine weitere Methode in die ColumnModel-Klasse einfüge , dann meckert der Kompiler mit dem Hinweis 'method not found, location Interface ColumnModel'.
Wie kann das sein, dass er hier im Interface sucht, wenn doch getColumnModel() die richtige echte Klasse zurückgibt?

Hier habe ich noch ein massives Verständnisproblem, obwohl ich mich heute auch schon wieder geraume Zeit durch die Modelklassen geackert habe.

Danke für die Mühe!

Und noch als Nachtrag: die Spaltenköpfe fehlen auch. Wenn hier die Columns instanziiert werden müssen dann wohl auch die Spaltenköpfe.

Bib
 
Zuletzt bearbeitet:
Hallo Attila,

noch einmal vielen Dank für die viele Mühe. Ich habe inzwischen eine Lösung ohne externes ColumnModel erarbeitet, die ich für alle Interessierten auch anfüge.
Vom Prinzip her funktioniert es nun so, dass ich in einer Klasse JTable erweitere und in dieser Klasse dann alle zusätzlichen, allgemeinen Utility Methoden für Tabellen implementiere. Hier sind dann auch die Methoden zu finden, die ich eigentlich in das externe ColumnModel auslagern wollte.
Diese Klasse wird dann wiederum von der/den Klasse/n erweitert die dann tatsächlich als Componenten herhalten sollen wie z.B. DayViewTable.
Das TableModel und CellRenderer bleiben in eigenen Klassen, lediglich die Funktionalität des ColumnModels wird in die Tabelle direkt übernommen.

Hier nun der Code: (Die Methoden sind noch nicht sauber durchgetestet, also bitte Vorsicht bei der Übernahme)

Hier nun die "Standarderweiterung" von JTable:

Java:
public class WarpTable extends JTable {



    // Constructor initializes the TableModel as well
    public WarpTable(){

             
        this.setDragEnabled(true);

        this.setFillsViewportHeight(true);

     }


    // Additional methods extending the JTable functionality

    
    // gets the current width of the table
    int getCurrentTableWidth(){

        int width = this.getColumnModel().getTotalColumnWidth();
        
        // TESTER
        System.out.println("Total column width = " + width);
        
      return width;
    }

    // gets the current width of the table
    int getCurrentTableHeight(){

        int height = this.getSize().height;

        // TESTER
        System.out.println("Tableheight = " + height);

      return height;
    }


    // Methods working on Columns

    // Sets width of first column according to headerwidth
    public void adjustFirstColToHeaderWidth(){
    
    TableColumn firstCol = this.getColumnModel().getColumn(0);
    int w = this.getColumnHeaderWidth(firstCol);
    firstCol.setWidth(w);
   
    }


    // Just sets the width of the given column
    public void setColWidth(int col, int width){

        this.getColumnModel().getColumn(col).setWidth(width);
   
    }
    
    
    // sets width of second column
    // Take care, can't be called from within  the constructor, for table is not yet initialized
    public void setColTwoWidth(WarpTable t){
    
        // makes second column occupy remaining space
        int tableWidth = t.getCurrentTableWidth();
        System.out.println("getCurrentTableWidth = " + t.getCurrentTableWidth());
        Component c = t.getParent();
        JViewport jvp = (JViewport)c;
        JScrollPane scp = (JScrollPane)jvp.getParent();
        int scpWidth = scp.getVerticalScrollBar().WIDTH;
        int colTwoWidth = tableWidth - scpWidth - t.getColumnModel().getColumn(0).getWidth();
        t.getColumnModel().getColumn(1).setWidth(colTwoWidth);
    
    }
    
    

    // Adjusts the columnwidth to match the width of a given String
    public void adjustWidthToPattern(int col, String pattern ){

        int length = pattern.length();
        // ToDo: Get Font, getFontMetrics amount of pixels needed
        
        this.getColumnModel().getColumn(col).setWidth(length);

    }

    // gets the widest cell entry and adjusts column width to match this cells width
    public void setColumnWidthToMatchWidestCell(TableColumn tc){

        int headerWidth = getColumnHeaderWidth(tc);
        int colWidth = getWidestCell(tc);
        // colon stand for an 'else' here
        int width = headerWidth > colWidth ? headerWidth : colWidth;

        // sets minimal width of column to match header width
        tc.setMinWidth(this.getColumnHeaderWidth(tc));
        // sets reasonable value for maximum width
        tc.setMaxWidth(width + 10);
        // finaly set the columns width
        tc.setPreferredWidth(width);
        
    }


    public void adjustWidthToColumnHeader(TableColumn tc){

        int headerWidth = getColumnHeaderWidth(tc);

        int width = headerWidth;

        // sets minimal width of column to match header width
        tc.setMinWidth(this.getColumnHeaderWidth(tc));
        // sets reasonable value for maximum width
        tc.setMaxWidth(width + 10);
        // finaly set the columns width
        tc.setPreferredWidth(width);
    }


    // Thanks to Remo Hartwig for writing about this subject on foonews.info,
    int getColumnHeaderWidth(TableColumn tc){

            int width = 0;
            TableCellRenderer tcr = tc.getHeaderRenderer();

            if(tcr == null) {
                JTableHeader jth = getTableHeader();
                tcr = jth.getDefaultRenderer();
        }
            try {

            Component c = tcr.getTableCellRendererComponent(
            this, tc.getHeaderValue(), false, false, 0, 0);
            width = c.getPreferredSize().width;

        }
            catch (Exception e) {}

          
        return width;
     }


    // Thanks to Remo Hartwig for writing about this subject on foonews.info
    int getWidestCell(TableColumn tc) {

            int index = tc.getModelIndex();
            int width = 0;
            int maxWidth = 0;
            int l = getRowCount();

                for(int i = 0; i < l; i++) {
                TableCellRenderer tcr = getCellRenderer(i, index);

            try {

                Component c = tcr.getTableCellRendererComponent(this,
                getValueAt(i, index), false, false, i, index);
                width = c.getPreferredSize().width;
                maxWidth = width > maxWidth ? width : maxWidth;
            }

            catch (Exception e) {}

            }

        return maxWidth;

        }


}


Und hier die Klasse mit der Spezialisierung, (DayViewTable):

Java:
public class WarpDayViewTable extends WarpTable {



    // Constructor initializes the TableModel as well
    public WarpDayViewTable() {

        // sets the TableModel from inner class
        this.setModel(new warp.Tables.WarpDayViewTableModel());

        // adjusts width of first column
        this.adjustWidthToColumnHeader(this.getColumnModel().getColumn(0));

        Font f = new Font("Tahoma",Font.BOLD ,11);
        this.getTableHeader().setFont(f);

        Color bg = new Color(255,255,204);
        this.setBackground(bg);

        this.setDragEnabled(true);

        this.setFillsViewportHeight(true);

     }

Und zum guten Schluss das TableModel für die DayViewTable:

Java:
class WarpDayViewTableModel extends AbstractTableModel {


    // Constructor, fire-command makes the table redraw itself from scratch
    public WarpDayViewTableModel(){

        // TODO: Get data from database first and fill array

        fireTableStructureChanged();
        // TESTER
        System.out.println("Table Model called.");


    }

    // Variables defininig the table structure

    String columnNames[] = {"ZEIT","EREIGNIS"};
    public int rowCount = 48;
    public int columnCount = 2;


    // Variables holding the table Data
    String data [][] = {

        {" 00:00 ", null},
        {" 00:30 ", null},
        {" 01:00 ", null},
        {" 01:30 ", null},
        {" 02:00 ", null},
        {" 02:30 ", null},
        {" 03:00 ", null},
        {" 03:30 ", null},
        {" 04:00 ", null},
        {" 04:30 ", null},
        {" 05:00 ", null},
        {" 05:30 ", null},
        {" 06:00 ", null},
        {" 06:30 ", null},
        {" 07:00 ", null},
        {" 07:30 ", null},
        {" 08:00 ", "START der ganzen Mühsal"}, // TESTVALUE
        {" 08:30 ", null},
        {" 09:00 ", null},
        {" 09:30 ", null},
        {" 10:00 ", null},
        {" 10:30 ", null},
        {" 11:00 ", null},
        {" 11:30 ", null},
        {" 12:00 ", null},
        {" 12:30 ", null},
        {" 13:00 ", null},
        {" 13:30 ", null},
        {" 14:00 ", null},
        {" 14:30 ", null},
        {" 15:00 ", null},
        {" 15:30 ", null},
        {" 16:00 ", null},
        {" 16:30 ", null},
        {" 17:00 ", null},
        {" 17:30 ", null},
        {" 18:00 ", "Und nu is allet am Ende"}, // TESTVALUE
        {" 18:30 ", null},
        {" 19:00 ", null},
        {" 19:30 ", null},
        {" 20:00 ", null},
        {" 20:30 ", null},
        {" 21:00 ", null},
        {" 21:30 ", null},
        {" 22:00 ", null},
        {" 22:30 ", null},
        {" 23:00 ", null},
        {" 23:30 ", null}
    };



    // set public variable 'rowCount'
    public void setRowCount(int rows){

        fireTableStructureChanged();
        rowCount = rows;

    }

    // gets value of variable 'rowCount'
    public int getRowCount(){

        return rowCount;
    }

    // set public variable 'columnCount'
    public void setColumnCount(int cols){

        fireTableStructureChanged();
        columnCount = cols;
    }

    // gets value of variable 'columnCount'
    public int getColumnCount(){

        return columnNames.length;
    }

    // gets value of variable 'columnCount'
    @Override
    public String getColumnName(int column){

        return (String) columnNames[column];
    }


    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {

        data [rowIndex][columnIndex] = (String)aValue;
        fireTableDataChanged();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex){

        return (String) data [rowIndex][columnIndex];
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {

        if (columnIndex > 0){

            return true;
        }

        else {

            return false;
        }
     }
    }


Ich hoffe die Informationen sind hilfreich für jemand der ein ähnliches Problem hat.
Viel Erfolg und noch einmal herzlichen Dank an Attila.

Bib
 

Zurück
Oben