How to change the vertical grid line size of a Jtable?

Asked

Viewed 1,331 times

2

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

Ex:

jTable.setRowHeight(30); 

This method above changes the line width.

Have some other similar to this which changes the vertical grid width of the columns?

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

inserir a descrição da imagem aqui

Edit:

I’m doing so but still it didn’t work what I’m doing wrong?

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);
        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 the class of Nderer.

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;
    }
}
  • Already tried to go in the column and search for setColumnWidth?

  • I don’t want to mess with the size of the column.

  • I can not see the image, what you intend to do? I could not understand without seeing it.

  • There is a separator between the columns of the J table that looks like this | column1| column2 | . What I want is to increase the size of this space so it gets about 5 times wider.Ps: It’s not the size of the column.

  • The solution below did not serve? Despite creating an edge to do this, it kind of "increases" this separator.

  • At least the way I implemented in the above code had no result.

  • In fact, I tested and she really doesn’t do what you want. See if I elaborate something here.

Show 2 more comments

2 answers

1


Based on Soen’s linked responses at the end of this post, I got it as follows:

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:

  • I first changed how the table would draw lines within the method prepareRenderer(), it is used when the table is still being built. Could create a redenderer and apply after the table is created too, but this way I believe it is better because it avoids the redesign of the table.

  • within the prepareRenderer(), defined the new border as MatteBorder for it is more flexible and lets me define both the color and width of each border separately. Thus, I defined only the size of the vertical edges.

  • It is not enough just to customize the construction of the edges between columns, as the table will still display the grid anyway. So, I deactivate the vertical grid lines and remove the spacing left by it with the methods setShowVerticalLines() and setIntercellSpacing() respectively. Thus, only the horizontal grid will be displayed.

  • The modifications mentioned change only the grid between cells, the table header is treated separately. To change it, I created a standard Renderer and apply the same border within this Renderer, and then apply to the entire header using the getTableHeader().setDefaultRenderer(renderer).

  • Always start api-based applications swing within the Event-Dispatch-thread. The links below can explain why one should do so and what consequences if one does not do so:

The end result looks like this:

inserir a descrição da imagem aqui


References:

  • That’s exactly what I wanted. Thank you.

0

If you want spacing within the cell, you can use an edge on 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;
    }       
  • Not on the edges is on the Columns tabs. There where you are pointing the arrow in the image.

  • Adjusted response with full code. Use a tablecellrenderer.

  • It didn’t work, I’m doing something wrong.

Browser other questions tagged

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