Display multiple columns

Asked

Viewed 71 times

1

I am developing a basic program in Java Application (Desktop) that performs a simple registration and displays on another screen through a Jtable the recorded data in the same.

My problem is that there are 24 columns to be displayed in this table, so I cannot view all the data as needed.

Below is the images demonstrating how the table looks.

Note: The individual size of the columns changes (Increases one, decreases the others automatically), but the total size of the column is unchanged.

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

Below is the code of this screen:

    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import controller.CadInternoJpaController;
import java.util.Iterator;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import model.CadInterno;

/**
 *
 * @author Casa
 */
public class JFAltExc extends javax.swing.JFrame {

    /**
     * Creates new form JFAltExc
     */
    public JFAltExc() {

        initComponents();

        readJTable();

    }

    /**
     *
     */
    public void readJTable(){

        DefaultTableModel tableModel = (DefaultTableModel) jtCadInterno.getModel();

        tableModel.setNumRows(0);



        EntityManagerFactory objFactory = Persistence.createEntityManagerFactory("CERVPU");
        EntityManager manager = objFactory.createEntityManager();
        CadInternoJpaController jpa = new CadInternoJpaController(objFactory);
        try{
            for (Iterator<CadInterno> it = jpa.findCadInternoEntities().iterator(); it.hasNext();) {
                CadInterno c = it.next();
                tableModel.addRow(new Object[]{
                    c.getCodigo(),
                    c.getDataEntrada(),
                    c.getDataSaida(),
                    c.getNome(),
                    c.getEndereco(),
                    c.getNumero(),
                    c.getComplemento(),
                    c.getBairro(),
                    c.getCidade(),
                    c.getEstado(),
                    c.getPai(),
                    c.getMae(),
                    c.getDataNasc(),
                    c.getRg(),
                    c.getCpf(),
                    c.getGrauEscolar(),
                    c.getTelefone(),
                    c.getCelular(),
                    c.getEstCivil(),
                    c.getTiposDrogas(),
                    c.getTentParar(),
                    c.getDetParar(),
                    c.getEstPreso(),
                    c.getMotPreso(),
                    c.getDataCriacao()
                });
            }
        } catch (Exception ex)
        {
            //Logger.getLogger(AplicaCliente.class.getName()).log(Level.SEVERE, null, ex);
        }




        jtCadInterno.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        jtCadInterno.getColumnModel().getColumn(0).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(1).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(2).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(3).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(4).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(5).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(6).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(7).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(8).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(9).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(10).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(11).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(12).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(13).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(14).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(15).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(16).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(17).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(18).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(19).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(20).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(21).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(22).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(23).setPreferredWidth(500);
        jtCadInterno.getColumnModel().getColumn(24).setPreferredWidth(500);

        jtCadInterno.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); 
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jtCadInterno = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jtCadInterno.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Data Entrada", "Data Saida", "Nome", "Endereço", "Número", "Complemento", "Bairro", "Cidade", "Estado", "Nome Pai", "Nome Mãe", "Nascido em", "RG", "CPF", "Grau Escolar", "Telefone", "Celular", "Estado Civil", "Drogas Usadas", "Tentou Parar?", "Detalhe de Como Tentou Parar", "Esteve Preso?", "Motivo Pelo Qual Foi Preso", "Cadastrado em"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jtCadInterno.setMaximumSize(new java.awt.Dimension(1272, 503));
        jtCadInterno.setMinimumSize(new java.awt.Dimension(1272, 503));
        jtCadInterno.setPreferredSize(new java.awt.Dimension(1272, 503));
        jScrollPane1.setViewportView(jtCadInterno);

        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()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1270, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(89, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 531, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    /**
     * @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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFAltExc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> {
            new JFAltExc().setVisible(true);
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jtCadInterno;
    // End of variables declaration                   
}

If you look, I’ve set a size of 500 for each field, with the intention of testing, making all fields very large and making room for horizontal scrolling, allowing you to view the contents of all fields, however as it IS NOT WORKING and size does not change, it divides into a smaller size but equaling the size of all fields.

Anything I can post more details.

  • Try this: https://answall.com/questions/165066/comoros

  • I tried, but the fields that did not fit on the screen simply disappeared, but the ones that stayed, was displayed in the correct size.

  • Lucas, this code is not testable. You can edit with a table containing some lines with sample data?

  • I’m sorry, but I don’t understand what you need me to do, could you please explain. Thank you :)

  • There are dependencies in your code. You need connection to your bank, which is impossible. Remove the dependencies of entitymanager and your database, and add 2 or 3 lines manually to serve as an example.

  • @diegofm Funny, as requested, I was creating a trial version, without communication with the database, but it worked correctly. Does it have to do with the process of calling the data to the table?

Show 1 more comment

1 answer

1

You have placed jtCadInterno.setAutoResizeMode(Jtable.AUTO_RESIZE_OFF); 2x in the code, well delete the first one and change the bottom one to "AUTO_RESIZE_ALL_COLUMNS"

You can also do so:

.getColumn(0). setPreferredWidth(100); //Conventional column size .getColumn(0). setMaxWidth(500); //Maximum size it can reach

  • But this will only reduce the size of all columns so that they all appear without scroll. It is with this much column, will not display the content. Soon this solution will not solve the problem pro full.

  • That’s right, it didn’t, because the code put it all together to fit on a screen, but thanks for the attention.

  • @Lucash.Pink did you look at the answer of the question I left the link? I’m pretty sure it meets this problem.

  • @diegofm looked, but the fields that did not fit on the screen simply disappeared, but the ones that stayed, was displayed in the correct size.

  • @OKOL, I tried this second way that you passed, but the fields that did not fit on the screen simply disappeared, but the ones that remained were displayed correctly.

  • @diegofm I tested here, with the AUTO_RESIZE_OFF is the way you want it, but you’ll have to fix each column with the Preferredwidth, to look good right, test there.

  • Of the 24 columns? Then the solution is no longer practical.

  • Boy make a: for(int i=0;i<25;i++){jtCadInterno.getColumnModel().getColumn(i).setPreferredWidth(100);&#xA; } Sorry for the various editions, I started today in the forum kkk

  • Still this sounds kind of gambiarra, force to set the size manually, and if the columns have data you need different size? I think this case needs to analyze the content of the line to define the column size, and not kick a value, because it may not be the value that the column needs.

  • I will mount the FOR and take the size of the largest row of data to set in the parameter, but first wanted to arrange to make it work to later implement these details.

  • @OKOL in mine did not work, I am working with the tools of Java Jframe picking the TABLE component of "Swing Controls"

  • But of course, you are totally correct, so each column will be set to the same size, however you can click on it and increase the size, it will push the others increasing/decreasing the size of the scroll. To perfection you create a class that counts which row has the most characters and based on that you define the size of the columns, but this will be another question. Just explore the possibilities of the Jtable class: https://docs.oracle.com/javase/tutorial/uiswing/components/table.html

  • @Lucash.Pink for table to fit the content, none of this will work, you need to make the code calculate the size needed for the cell. But without a [mcve] I asked you, it’s hard to suggest anything.

  • @OKOL O meu problema é que são 24 colunas para serem exibidos nessa tabela, sendo assim não consigo visualizar todos os dados conforme o necessário. - the doubt is precisely this, according to this sentence of the author of the question, is to adapt the content of the columns.

  • @OKOL I managed to do here, thanks for the help. Abs.

  • @diegofm I managed to do here, thanks for the help. Abs.

  • I will post how the functional code in the question.

Show 12 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.