Tenho uma JTable
onde o usuário pode ocultar e depois exibir novamente uma ou mais colunas.
Encontrei um código neste link que ajusta a coluna de acordo com o tamanho do "valor do campo". Chamo este método assim que populo a JTable
.
public void defaultSize(JTable table) {
final TableColumnModel columnModel = table.getColumnModel();
for (int column = 0; column < table.getColumnCount(); column++) {
int width = 250;
for (int row = 0; row < table.getRowCount(); row++) {
TableCellRenderer renderer = table.getCellRenderer(row, column);
Component comp = table.prepareRenderer(renderer, row, column);
width = Math.max(comp.getPreferredSize().width + 1, width);
columnModel.getColumn(column).setPreferredWidth(width);
}
}
No evento do JRadioButton
, onde o usuário oculta ou mostra novamente a coluna, tenho este código:
private void jRadioCodigoItemStateChanged(java.awt.event.ItemEvent evt) {
int width = 80;
if (evt.getStateChange() == ItemEvent.DESELECTED) {
jTableResultado.getColumnModel().getColumn(0).setMinWidth(0);
jTableResultado.getColumnModel().getColumn(0).setMaxWidth(0);
jTableResultado.getColumnModel().getColumn(0).setWidth(0);
jTableResultado.getColumnModel().getColumn(0).setPreferredWidth(0);
defaultSize();
} else if (evt.getStateChange() == ItemEvent.SELECTED) {
jTableResultado.getColumnModel().getColumn(0).setMinWidth(width);
jTableResultado.getColumnModel().getColumn(0).setMaxWidth(width);
jTableResultado.getColumnModel().getColumn(0).setWidth(width);
jTableResultado.getColumnModel().getColumn(0).setPreferredWidth(width);
defaultSize();
}
}
O que eu queria agora era que, quando ocultada uma coluna, o restante das colunas fosse ajustada de acordo com o tamanho restante da JTable
, de forma que não ocorra conforme a imagem abaixo mostra. E também que, ao invés de passar o valor para o tamanho da coluna, ao exibi-la novamente no evento do jRadioButton
, que fosse ajustado de acordo com o tamanho do valor do campo, igual ocorre quando chamo o método defaultSize()
(só consigo isto ao carregar a tabela na primeira vez).
Exemplo reduzido do código:
import java.awt.Component;
import java.awt.event.ItemEvent;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
/**
*
* @author LockDown
*/
public final class NovoJFrame extends javax.swing.JFrame {
/**
* Creates new form NovoJFrame
*/
public NovoJFrame() {
initComponents();
loadtable();
}
public void loadtable() {
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setNumRows(0);
model.addRow(new Object[]{"Rodrigo", "32", "Masculino"});
model.addRow(new Object[]{"Elza", "32", "Feminino"});
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jRadioButton3 = new javax.swing.JRadioButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null},
{null, null, null},
{null, null, null},
{null, null, null}
},
new String [] {
"Nome", "Idade", "Sexo"
}
));
jScrollPane1.setViewportView(jTable1);
jRadioButton1.setText("Nome");
jRadioButton1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jRadioButton1ItemStateChanged(evt);
}
});
jRadioButton2.setText("Idade");
jRadioButton2.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jRadioButton2ItemStateChanged(evt);
}
});
jRadioButton3.setText("Sexo");
jRadioButton3.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jRadioButton3ItemStateChanged(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addGap(292, 292, 292)
.addComponent(jRadioButton1)
.addGap(18, 18, 18)
.addComponent(jRadioButton2)
.addGap(18, 18, 18)
.addComponent(jRadioButton3)
.addGap(0, 375, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jRadioButton1)
.addComponent(jRadioButton2)
.addComponent(jRadioButton3))
.addContainerGap(24, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jRadioButton1ItemStateChanged(java.awt.event.ItemEvent evt) {
int width = 100;
if (evt.getStateChange() == ItemEvent.SELECTED) {
jTable1.getColumnModel().getColumn(0).setMinWidth(0);
jTable1.getColumnModel().getColumn(0).setMaxWidth(0);
jTable1.getColumnModel().getColumn(0).setWidth(0);
jTable1.getColumnModel().getColumn(0).setPreferredWidth(0);
defaultSize(jTable1);
jTable1.revalidate();
} else if (evt.getStateChange() == ItemEvent.DESELECTED) {
jTable1.getColumnModel().getColumn(0).setMinWidth(width);
jTable1.getColumnModel().getColumn(0).setMaxWidth(width);
jTable1.getColumnModel().getColumn(0).setWidth(width);
jTable1.getColumnModel().getColumn(0).setPreferredWidth(width);
defaultSize(jTable1);
jTable1.revalidate();
}
}
private void jRadioButton2ItemStateChanged(java.awt.event.ItemEvent evt) {
int width = 100;
if (evt.getStateChange() == ItemEvent.SELECTED) {
jTable1.getColumnModel().getColumn(1).setMinWidth(0);
jTable1.getColumnModel().getColumn(1).setMaxWidth(0);
jTable1.getColumnModel().getColumn(1).setWidth(0);
jTable1.getColumnModel().getColumn(1).setPreferredWidth(0);
defaultSize(jTable1);
jTable1.revalidate();
} else if (evt.getStateChange() == ItemEvent.DESELECTED) {
jTable1.getColumnModel().getColumn(1).setMinWidth(width);
jTable1.getColumnModel().getColumn(1).setMaxWidth(width);
jTable1.getColumnModel().getColumn(1).setWidth(width);
jTable1.getColumnModel().getColumn(1).setPreferredWidth(width);
defaultSize(jTable1);
jTable1.revalidate();
}
}
private void jRadioButton3ItemStateChanged(java.awt.event.ItemEvent evt) {
int width = 100;
if (evt.getStateChange() == ItemEvent.SELECTED) {
jTable1.getColumnModel().getColumn(2).setMinWidth(0);
jTable1.getColumnModel().getColumn(2).setMaxWidth(0);
jTable1.getColumnModel().getColumn(2).setWidth(0);
jTable1.getColumnModel().getColumn(2).setPreferredWidth(0);
defaultSize(jTable1);
jTable1.revalidate();
} else if (evt.getStateChange() == ItemEvent.DESELECTED) {
jTable1.getColumnModel().getColumn(2).setMinWidth(width);
jTable1.getColumnModel().getColumn(2).setMaxWidth(width);
jTable1.getColumnModel().getColumn(2).setWidth(width);
jTable1.getColumnModel().getColumn(2).setPreferredWidth(width);
defaultSize(jTable1);
jTable1.revalidate();
}
}
public void defaultSize(JTable table) {
final TableColumnModel columnModel = table.getColumnModel();
for (int column = 0; column < table.getColumnCount(); column++) {
int width = 250;
for (int row = 0; row < table.getRowCount(); row++) {
TableCellRenderer renderer = table.getCellRenderer(row, column);
Component comp = table.prepareRenderer(renderer, row, column);
width = Math.max(comp.getPreferredSize().width + 1, width);
columnModel.getColumn(column).setPreferredWidth(width);
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NovoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NovoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NovoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NovoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new NovoJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JRadioButton jRadioButton3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
jTableResultado.revalidade();
logo depois dedefaultSize();
no métodojRadioCodigoItemStateChanged
, para ver se a tabela atualiza.Revalidate()
não teve efeito.