É possível congelar a 1a coluna de um JTable (swing) ? [Semi-resolvido]
6 respostas
J
julianostr
Apesar de já ter achado esse assunto aqui (ano passado), o pessoal não continuou o tópico então resolvi criar um novo.
Gostaria de saber se existe uma maneira de congelar apenas a primeira coluna de um JTable (de 6 colunas por exemplo), não permitindo que o usuário arraste ela para outra ordem/posição e permitindo o scroll de rolagem das outras colunas .
Sei que têm como congelar a table inteira, mas apenas 1 coluna não sei…
<< jtable.getTableHeader().setReorderingAllowed(false); >>
Já conversei com um colega sobre isso e ele me disse que eu teria que “customizar” o JTable. Seria isso mesmo?
// Use the table to create a new table sharing// the DataModel and ListSelectionModelJTablefixed=newJTable(main.getModel());fixed.setFocusable(false);fixed.setSelectionModel(main.getSelectionModel());fixed.getTableHeader().setReorderingAllowed(false);
// Remove the fixed columns from the main tablefor(inti=0;i<fixedColumns;i++){TableColumnModelcolumnModel=main.getColumnModel();columnModel.removeColumn(columnModel.getColumn(0));}// Remove the non-fixed columns from the fixed tablewhile(fixed.getColumnCount()>fixedColumns){TableColumnModelcolumnModel=fixed.getColumnModel();columnModel.removeColumn(columnModel.getColumn(fixedColumns));}// Add the fixed table to the scroll panefixed.setPreferredScrollableViewportSize(fixed.getPreferredSize());setRowHeaderView(fixed);setCorner(JScrollPane.UPPER_LEFT_CORNER,fixed.getTableHeader());}publicstaticvoidmain(String[]args){// Build your table normallyJTabletable=newJTable(10,8);table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);JScrollPanescrollPane=newFixedColumnScrollPane(table,1);
Exatamente cara.Se você quer que um componente funcione de um modo customizado para seu aplicativo você provávelmente vai ter que customizá-lo.
Dê uma olhada no código fonte dos Models utilizados pela JTable pra você ver o que eles fazem e o que você provávelmente irá ter que fazer.
DefaultTableMode, JTableHeader, DefaultTableColumnModel…
jorgefrancisco
Olá Juliano…
Já briguei muito com esse problema, pois eu não queria utilizar duas jtable (como no exemplo que você mostrou acima), porém foi o único jeito que consegui (e olha q pesquisei muito ;-))
Realmente ainda não possui um método do tipo: jTable.setCongelar(numCol) hehe…
Estou precisando desse efeito de ‘congelar painéis’ no JTable, mas queria saber se a única solução é criando 2 JTables mesmo, ou se depois de 2 anos temos algum componente mais completo?
É até engraçado, quando me pediram isso pensei comigo em usar 2 JTables, mas achei que seria uma solução meio antiga e que deveria ter algo mais “encapsulado”…
FixedColumnTable fct = new FixedColumnTable(1, scrollPaneBottom);
Onde o scrollPaneBottom é o objeto que contem sua tabela. E o código da classe mágica é esse:
importjava.beans.PropertyChangeEvent;importjava.beans.PropertyChangeListener;importjavax.swing.JScrollPane;importjavax.swing.JTable;importjavax.swing.JViewport;importjavax.swing.event.ChangeEvent;importjavax.swing.event.ChangeListener;importjavax.swing.table.TableColumn;importjavax.swing.table.TableColumnModel;/* * Prevent the specified number of columns from scrolling horizontally in * the scroll pane. The table must already exist in the scroll pane. * * The functionality is accomplished by creating a second JTable (fixed) * that will share the TableModel and SelectionModel of the main table. * This table will be used as the row header of the scroll pane. * * The fixed table created can be accessed by using the getFixedTable() * method. will be returned from this method. It will allow you to: * * You can change the model of the main table and the change will be * reflected in the fixed model. However, you cannot change the structure * of the model. */publicclassFixedColumnTableimplementsChangeListener,PropertyChangeListener{privateJTablemain;privateJTablefixed;privateJScrollPanescrollPane;/* * Specify the number of columns to be fixed and the scroll pane * containing the table. */publicFixedColumnTable(intfixedColumns,JScrollPanescrollPane){this.scrollPane=scrollPane;main=((JTable)scrollPane.getViewport().getView());main.setAutoCreateColumnsFromModel(false);main.addPropertyChangeListener(this);// Use the existing table to create a new table sharing// the DataModel and ListSelectionModelinttotalColumns=main.getColumnCount();fixed=newJTable();fixed.setAutoCreateColumnsFromModel(false);fixed.setModel(main.getModel());fixed.setSelectionModel(main.getSelectionModel());fixed.setFocusable(false);// Remove the fixed columns from the main table// and add them to the fixed tablefor(inti=0;i<fixedColumns;i++){TableColumnModelcolumnModel=main.getColumnModel();TableColumncolumn=columnModel.getColumn(0);columnModel.removeColumn(column);fixed.getColumnModel().addColumn(column);}// Add the fixed table to the scroll panefixed.setPreferredScrollableViewportSize(fixed.getPreferredSize());scrollPane.setRowHeaderView(fixed);scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER,fixed.getTableHeader());// Synchronize scrolling of the row header with the main tablescrollPane.getRowHeader().addChangeListener(this);}/* * Return the table being used in the row header */publicJTablegetFixedTable(){returnfixed;}//// Implement the ChangeListener//@OverridepublicvoidstateChanged(ChangeEvente){// Sync the scroll pane scrollbar with the row headerJViewportviewport=(JViewport)e.getSource();scrollPane.getVerticalScrollBar().setValue(viewport.getViewPosition().y);}//// Implement the PropertyChangeListener//@OverridepublicvoidpropertyChange(PropertyChangeEvente){// Keep the fixed table in sync with the main tableif("selectionModel".equals(e.getPropertyName())){fixed.setSelectionModel(main.getSelectionModel());}if("model".equals(e.getPropertyName())){fixed.setModel(main.getModel());}}}