How do I define size of columns?

2

I have a query screen, and I would like to set the size of the columns because some columns take up more space than necessary. I thought that if I made a comparison with the title of the column, although it might not be the most oriented way to do this, I would be able to do several ifs, defining the sizes I wanted.

To reinforce the understanding, the problem would be as follows, I would have for example columns like, Code, Country, Acronym and Status. Code would not have to have a column greater than 50, while parents in the minimum should have 80. acronym and status at most 60.

Below, I'll put a very simple example, just for understanding.

System Screen:

package telas;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class TelaSistema extends JFrame implements ActionListener {

    public static JDesktopPane jdp = new JDesktopPane();
    public JMenuBar jmb = new JMenuBar();
    public JMenu jmCadastros = new JMenu("Cadastros");
    public JMenuItem jmiE = new JMenuItem("Uma tela qualquer");

    public TelaSistema() {
        setExtendedState(MAXIMIZED_BOTH);
        setTitle("Sistema");
        getContentPane().add(jdp);
        setJMenuBar(jmb);
        jmb.add(jmCadastros);
        adicionaJMenuItem(jmCadastros, jmiE);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    private void adicionaJMenuItem(JMenu menu, JMenuItem item) {
        menu.add(item);
        item.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == jmiE) {
            TelaCadastroA a = new TelaCadastroA();
            jdp.add(a);
        }
    }

    public static void main(String args[]) {
        TelaSistema telaSistema = new TelaSistema();
    }
}

Registration Form:

package telas;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;

public class TelaCadastroA extends JInternalFrame implements ActionListener {

    public JButton jbConsultar = new JButton("Consultar");
    public JPanel jpBotoes = new JPanel();

    public TelaCadastroA() {
        super("");
        adicionaBotao(jbConsultar);
        setSize(500, 500);
        getContentPane().add("South", jpBotoes);
        jpBotoes.setLayout(new GridLayout(1, 1));
        Dimension tamanhoTela = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((tamanhoTela.width - getWidth()) / 2, ((tamanhoTela.height - getHeight())) / 2);
        setVisible(true);
    }

    private void adicionaBotao(JButton botao) {
        jpBotoes.add(botao);
        botao.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == jbConsultar) {
            consultar();
        }
    }

    public void consultar() {
        TelaConsultar.getTela("Consulta", new String[]{
            "Código", "Pais", "Sigla", "Status"
        }, new DefaultTableCellRenderer[]{null, null, new CellRenderMonetario(), null}, this);
    }

    class CellRenderMonetario extends DefaultTableCellRenderer {

        private DecimalFormat df = new DecimalFormat(",##0.00");

        @Override
        public Component getTableCellRendererComponent(JTable tabela, Object valor, boolean isSelected, boolean temFocu, int linha, int coluna) {
            if (valor == null) {
                valor = 0;
            }

            if (valor instanceof String) {
                setText(df.format(Double.parseDouble((String) valor)) + " ");
            } else {
                setText(df.format(valor) + " ");
            }
            setHorizontalAlignment(SwingConstants.RIGHT);
            return this;
        }
    }
}

Query screen:

package telas;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

public class TelaConsultar extends JInternalFrame implements InternalFrameListener, MouseListener {

    private static TelaConsultar telaConsultar = null;
    private String sql;
    private String[] titulos;
    private TelaCadastroA tela;
    private JTable tabela;
    private JScrollPane jsp;
    private DefaultTableModel dtm = new DefaultTableModel();
    private String proc;

    public TelaConsultar(String tituloJanela, String[] titulosColuna, DefaultTableCellRenderer[] renderizadores, TelaCadastroA tela) {
        super(tituloJanela, true, true, false, false);
        this.sql = sql;
        this.titulos = titulosColuna;
        this.tela = tela;
        tabela = new JTable() {
            @Override
            public boolean isCellEditable(int linha, int coluna) {
                return false;//Esta tabela não pode ser editada pois é uma consulta         
            }
        };
        tabela.setModel(dtm); //Define o modelo da tabela
        tabela.getTableHeader().setReorderingAllowed(false);
        for (int i = 0; i < titulosColuna.length; i++) {
            dtm.addColumn(titulosColuna[i]);
        }
        jsp = new JScrollPane(tabela);
        getContentPane().add(jsp);
        preencher();
        //pack();
        setSize(650, 400);
        setMinimumSize(new Dimension(getWidth(), getHeight()));
        centralizaTelaConsulta();
        setVisible(true);
        tabela.addMouseListener(this);
        addInternalFrameListener(this);

        TableColumnModel tableModel = tabela.getColumnModel();

        if (titulosColuna.equals("Código")) {
            for (int i = 0; i < titulosColuna.length; i++) {
                tableModel.getColumn(i).setMinWidth(30);
                tableModel.getColumn(i).setMaxWidth(50);
            }
        }

        else
        {
            for (int i = 0; i < titulosColuna.length; i++) {
                tableModel.getColumn(i).setMinWidth(100);
            }
        }

        for (int i = 0; i < tableModel.getColumnCount(); i++) {
            if (renderizadores[i] != null) {
                tableModel.getColumn(i).setCellRenderer(renderizadores[i]);
            }

        }
    }

    public static void getTela(String tituloJanela, String[] titulos, DefaultTableCellRenderer[] renderizadores, TelaCadastroA tela) {
        if (telaConsultar == null) {
            telaConsultar = new TelaConsultar(tituloJanela, titulos, renderizadores, tela);
            TelaSistema.jdp.add(telaConsultar);
        }
        TelaSistema.jdp.setSelectedFrame(telaConsultar);
        TelaSistema.jdp.moveToFront(telaConsultar);
    }

    private void preencher() {
        for (int i = 0; i < 10; i++) {
            dtm.addRow(new Object[]{"" + i, "Brasil - " + i});
        }

    }

    public void centralizaTelaConsulta() {
        Dimension tamanhoTela = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((tamanhoTela.width - getWidth()) / 2, ((tamanhoTela.height - getHeight())) / 2);
    }

    @Override
    public void mousePressed(MouseEvent e) {
    }

    @Override
    public void mouseReleased(MouseEvent e) {
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

    @Override
    public void internalFrameOpened(InternalFrameEvent e) {
    }

    @Override
    public void internalFrameClosing(InternalFrameEvent e) {
    }

    @Override
    public void internalFrameClosed(InternalFrameEvent e) {
        TelaSistema.jdp.remove(telaConsultar);
        telaConsultar = null;
    }

    @Override
    public void internalFrameIconified(InternalFrameEvent e) {
    }

    @Override
    public void internalFrameDeiconified(InternalFrameEvent e) {
    }

    @Override
    public void internalFrameActivated(InternalFrameEvent e) {

    }

    @Override
    public void internalFrameDeactivated(InternalFrameEvent e) {
    }

    @Override
    public void mouseClicked(MouseEvent me) {

    }
}
    
asked by anonymous 11.11.2016 / 22:47

1 answer

2

Based on this other answer , I made an adaptation within your code, add it right below TableColumnModel tableModel = tabela.getColumnModel(); :

    for (int i = 0; i < tableModel.getColumnCount(); i++) {
        String columnName = tableModel.getColumn(i).getHeaderValue().toString();

        switch (columnName) {

            case "Código":
                tableModel.getColumn(i).setMaxWidth(50);
                tableModel.getColumn(i).setPreferredWidth(50);
                tableModel.getColumn(i).setMinWidth(50);
                break;
            case "Pais":
                tableModel.getColumn(i).setMaxWidth(Integer.MAX_VALUE);
                tableModel.getColumn(i).setPreferredWidth(80);
                tableModel.getColumn(i).setMinWidth(80);
                break;
            default:
                tableModel.getColumn(i).setMaxWidth(60);
                tableModel.getColumn(i).setPreferredWidth(60);
                tableModel.getColumn(i).setMinWidth(60);

        }
    }

The result was:

SincethePaiscolumnhasaminimumsizebutnotapredefinedmaximumsize,I'vesetittotakethemaximumsizeavailableonthescreen.

Rememberingthatsinceyouarenotmanagingthe LayoutManager of the screen where the table was inserted, it will always tend to fill the width completely, as this is the behavior of the LayoutManager panel internal%%, which is JFrame .

    
11.11.2016 / 22:50