Adjust columns according to available JTable size

2

I have a JTable where the user can hide and then display one or more columns again. I found a code that adjusts the column according to the size of the "value" from Camp". I call this method as soon as populo to 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);
        }

    }

In the event of JRadioButton , where the user hides or shows the column again, I have this code:

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();
        }

    } 

What I wanted now was that when a column was hidden, the rest of the columns would be adjusted according to the remaining size of the JTable so that it does not occur as shown below. And also that instead of passing the value to the column size, when I display it again in the jRadioButton event, which is adjusted according to the size of the field value, the same happens when I call the defaultSize() (I only get this when loading the table the first time).

Reducedcodesample:

importjava.awt.Component;importjava.awt.event.ItemEvent;importjavax.swing.JTable;importjavax.swing.table.DefaultTableModel;importjavax.swing.table.TableCellRenderer;importjavax.swing.table.TableColumn;importjavax.swing.table.TableColumnModel;/****@authorLockDown*/publicfinalclassNovoJFrameextendsjavax.swing.JFrame{/***CreatesnewformNovoJFrame*/publicNovoJFrame(){initComponents();loadtable();}publicvoidloadtable(){DefaultTableModelmodel=(DefaultTableModel)jTable1.getModel();model.setNumRows(0);model.addRow(newObject[]{"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                   
}
    
asked by anonymous 07.07.2016 / 19:20

1 answer

1

After analyzing your code, I noticed that JTable uses the maximum width value of each column as

08.07.2016 / 02:23