[RESOLVIDO] Fazer texto caber em cúlula de JTable

8 respostas
J

Boa noite pessoal,

Gostaria de perguntar se alguém sabe alguma forma de fazer com um texto grande caixa em uma célula de jtable, tipo… não aumentando a largura da coluna, fazendo que nem acontece no word ou no excel. Ex. ao invés de :


| textotextotextotextotextotextotextotextotexto…| -> Texto grande que não cabe na célula

isto:


| textotextotextotextotextotextotextotextotexto | -> Texto grande que cabe na célula

textotextotexto

Mais ou menos que nem se fosse um jtextarea ou numa tabela no html.

Obrigado a todos pela ajuda,

Juba

8 Respostas

L

Oi,

Se eu entendi bem, a opção setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS) faz isso para você.

Tchauzin!

E

Pelo que imagino, o carinha quer que se o texto for muito grande, ele ou invada a célula seguinte, como no Excel, ou então que haja uma quebra de linha (no caso do Excel você precisa formatar a célula para que ele quebre as linhas.

Ambas essas coisas não estão prontas no JTable, que não tem nem 1% dos recursos do Excel.

(O grande problema do JTable é que todo mundo acha que dá para fazer qualquer coisa que o Excel faz com um JTable :frowning: )

L

entanglement:
Pelo que imagino, o carinha quer que se o texto for muito grande, ele ou invada a célula seguinte, como no Excel, ou então que haja uma quebra de linha (no caso do Excel você precisa formatar a célula para que ele quebre as linhas.

Ambas essas coisas não estão prontas no JTable, que não tem nem 1% dos recursos do Excel.

(O grande problema do JTable é que todo mundo acha que dá para fazer qualquer coisa que o Excel faz com um JTable :frowning: )

Oi,

É. Se for isso… =/

Tchauzin!

J

Boa noite amigos

É realmente o que eu queria era fazer que nem se faz no excel, quando a gente configura a uma célula para ajustar o tamanho do texto para caber em uma célula. Como vocês disseram o JTable não é o excel, é muito mais divertido, dando uma “googleada” consegui o seguinte código, se alguém também precisar, que resolveu o meu problema:

import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.TableCellRenderer;

public class TabelaTextAreaRenderer extends JTextArea implements TableCellRenderer{
	// This method is called each time a cell in a column
    // using this renderer needs to be rendered.
	
	public  TabelaTextAreaRenderer(){
		setLineWrap(true);
		setWrapStyleWord(true);
		
	}
	
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
        // 'value' is value contained in the cell located at
        // (rowIndex, vColIndex)

        if (isSelected) {
            // cell (and perhaps other cells) are selected
        }

        if (hasFocus) {
            // this cell is the anchor and the table has the focus
        }
        // Configure the component with the specified value
        setText(value.toString());

        // Set tool tip if desired
        setToolTipText((String)value);

        // Since the renderer is a component, return itself
        return this;
    }

}

Este código transforma uma célula de um JTable em uma TextArea ou qualquer outro componente que quizer.

Obrigado pela ajuda pessoal.

Juba

D

Jubarius:
Boa noite amigos

É realmente o que eu queria era fazer que nem se faz no excel, quando a gente configura a uma célula para ajustar o tamanho do texto para caber em uma célula. Como vocês disseram o JTable não é o excel, é muito mais divertido, dando uma “googleada” consegui o seguinte código, se alguém também precisar, que resolveu o meu problema:

import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.TableCellRenderer;

public class TabelaTextAreaRenderer extends JTextArea implements TableCellRenderer{
	// This method is called each time a cell in a column
    // using this renderer needs to be rendered.
	
	public  TabelaTextAreaRenderer(){
		setLineWrap(true);
		setWrapStyleWord(true);
		
	}
	
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
        // 'value' is value contained in the cell located at
        // (rowIndex, vColIndex)

        if (isSelected) {
            // cell (and perhaps other cells) are selected
        }

        if (hasFocus) {
            // this cell is the anchor and the table has the focus
        }
        // Configure the component with the specified value
        setText(value.toString());

        // Set tool tip if desired
        setToolTipText((String)value);

        // Since the renderer is a component, return itself
        return this;
    }

}

Este código transforma uma célula de um JTable em uma TextArea ou qualquer outro componente que quizer.

Obrigado pela ajuda pessoal.

Juba

Poxa Muito Obrigado Resolveu um problema meu.

P

oi gente,

sei que este tópico é bem antiguinho, mas estou com o mesmo problema.

ok, se eu criar uma classe como essa que vcs passaram, como faço a chamada para minha tabela?
Não entendi isso.

J

Oi, patyboian

Realmente o tópico é bem antigo e realmente eu não me recordo onde é que está o código onde usei isto. Porém, alguém me corrija se eu estiver errado, se eu não me engano funciona assim:

//Declaração da tua tabela
		JTable tbl = new JTable();
               //
		tbl.getColumnModel().getColumn(/*índice da tua coluna*/).setCellRenderer(/*----> seu cell renderer aqui <----*/);

obs: Estou considerando que você já tenha criado o seu CellRenderer.

Espero ter ajudado,

Inté…

A
public class TextAreaCellRenderer extends JTextArea implements TableCellRenderer {

        public TextAreaCellRenderer() {

            setLineWrap(true);
            setWrapStyleWord(true);
            setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
            setMargin(new java.awt.Insets(5, 5, 5, 5));
        }

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

            // set color & border here              
            this.setText(value.toString());

            setText((value == null) ? "" : value.toString());
            setSize(table.getColumnModel().getColumn(column).getWidth(),
                    getPreferredSize().height);

            if (table.getRowHeight(row) < getPreferredSize().height) {
                table.setRowHeight(row, getPreferredSize().height );
            }

            return this;
        }
    }
Para adicionar na tabela utilize o seguinte código:
for (int i = 0; i < jTable.getColumnCount(); i++) {
            col = jTable.getColumnModel().getColumn(i);
            col.setCellRenderer(new TextAreaCellRenderer());
        }
Criado 7 de junho de 2012
Ultima resposta 16 de jul. de 2015
Respostas 8
Participantes 6