How to change the size of the rows of the vertical grid of a JTable?

2

How do I change the size of the vertical grid lines of a JTable?

Ex:

jTable.setRowHeight(30); 

This method changes the width of the line.

Is there any other similar to this that changes the vertical grid width of the columns?

Below an image to illustrate what I want to change the width.

Edit:

I'mdoingitanywaybutitdidnotworkoutwhatI'mdoingwrong?

publicclassGuiPrincipalextendsJFrame{//variaveisparausodaJTableprivateJTabletable;privatefinalStringcolunas[]={"Nome:", "Idade:", "Sexo:"};
    private final String dados[][] = {
        {"Jack", "19", "Masculino"},
        {"Eddie", "56", "Masculino"},
        {"Gina", "34", "Feminino"},
        {"Klaus", "18", "Masculino"},
        {"Erika", "20", "Feminino"},
        {"Roberto", "29", "Masculino"},
        {"Maria", "30", "Feminino"}};

    /*Construtor da classe ,
          antes de executar o metodo main(),
          irá construir o JFrame e a JTable*/
    public GuiPrincipal() {
        setLayout(new FlowLayout());//tipo de layout
        setSize(new Dimension(700, 300));//tamanho do Formulario
        setLocationRelativeTo(null);//centralizado
        setTitle("Exemplo JTable");//titulo
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//setando a ação padrão de fechamento do Formulário,
        // neste caso  irá fechar o programa

        //instanciando a JTable
        table = new JTable(dados, colunas);
        table.setPreferredScrollableViewportSize(new Dimension(700, 300));//barra de rolagem
        table.setFillsViewportHeight(true);

        //adicionando a tabela em uma barra de rolagem, ficará envolta , pela mesma 
        JScrollPane scrollPane = new JScrollPane(table);

        table.setDefaultRenderer(String.class, new Renderer());
        add(scrollPane);
    }

    //este é o método onde é executado nosso programa
    public static void main(String[] args) {
        new GuiPrincipal().setVisible(true);
    }

}

And below is the renderer class.

public class Renderer extends DefaultTableCellRenderer {

    javax.swing.border.Border padding = BorderFactory.createEmptyBorder(50, 50, 50, 50);

    @Override
    public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus,
            int row, int column) {
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
                row, column);
        setBorder(BorderFactory.createCompoundBorder(getBorder(), padding));
        return this;
    }
}
    
asked by anonymous 10.05.2018 / 21:38

2 answers

2

Based on the SOEn linked responses at the end of this post, I was able to do the following:

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer; 
import javax.swing.table.DefaultTableCellRenderer;

public class GuiPrincipal extends JFrame {
    // variaveis para uso da JTable
    private JTable table;
    private final String colunas[] = { "Nome:", "Idade:", "Sexo:" };
    private final String dados[][] = { { "Jack", "19", "Masculino" }, { "Eddie", "56", "Masculino" },
            { "Gina", "34", "Feminino" }, { "Klaus", "18", "Masculino" }, { "Erika", "20", "Feminino" },
            { "Roberto", "29", "Masculino" }, { "Maria", "30", "Feminino" } };

    /*
     * Construtor da classe , antes de executar o metodo main(), irá construir o
     * JFrame e a JTable
     */
    public GuiPrincipal() {
        setLayout(new FlowLayout());// tipo de layout
        setSize(new Dimension(700, 300));// tamanho do Formulario
        setLocationRelativeTo(null);// centralizado
        setTitle("Exemplo JTable");// titulo
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// setando a ação padrão de fechamento do Formulário,
        // neste caso irá fechar o programa

        // instanciando a JTable
        table = new JTable(dados, colunas) {

            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {

                JComponent component = (JComponent) super.prepareRenderer(renderer, row, column);
                component.setBorder(BorderFactory.createMatteBorder(0, 2, 0, 2, Color.red));

                return component;
            }
        };

        table.setShowVerticalLines(false);
        table.setIntercellSpacing(new Dimension(0, 0));

        DefaultTableRenderer renderer = new DefaultTableRenderer() {

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {

                JComponent comp = (JComponent) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                comp.setBackground(getBackground());
                comp.setBorder(BorderFactory.createMatteBorder(0, 2, 0, 2, Color.red));
                return comp;
            }
        };

        table.getTableHeader().setDefaultRenderer(renderer);


        table.setPreferredScrollableViewportSize(new Dimension(700, 300));// barra de rolagem
        table.setFillsViewportHeight(true);

        // adicionando a tabela em uma barra de rolagem, ficará envolta , pela mesma
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
    }

    // este é o método onde é executado nosso programa
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new GuiPrincipal().setVisible(true));
    }
}

Changes I've made:

  • First I changed how the table would draw lines within the prepareRenderer() ", it is used when the table is still being built. I could create a renderer and apply after the table is created too, but this way I believe it is better because it avoids table redrawing.

  • Within prepareRenderer() , set the new border to MatteBorder because it is more flexible and lets me define both the color and width of each border separately. So I set only the size of the vertical borders.

  • Do not just customize the construction of the borders between columns, as the table will still display the grid anyway. So I deactivate the rows of the vertical grid and remove the spacing left by it with the methods setShowVerticalLines() " and setIntercellSpacing() " respectively. That way, only the horizontal grid will be displayed.

  • The above changes only change the grid between cells, the table header is treated separately. To change it, I've created a standard renderer and apply the same border inside this renderer, and then apply the whole header using getTableHeader().setDefaultRenderer(renderer) .

  • Always start graphics applications based on the swing api within the event-dispatch-thread . The links below can explain why you should do this and what consequences you do not do it this way:

The end result looks like this:

References:

11.05.2018 / 15:00
0

If you want spacing within the cell, you can use a border in the cell. Note that you can use different sizes for left, right, up, and down;

In the example the spacing was placed 10 on the left and right.

DefaultTableCellRenderer r = new DefaultTableCellRenderer() {

    Border padding = BorderFactory.createEmptyBorder(0, 10, 0, 10);
    @Override
    public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus,
            int row, int column) {
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
                row, column);
        setBorder(BorderFactory.createCompoundBorder(getBorder(), padding));
        return this;
    }       
    
10.05.2018 / 22:16