A Mardita JTable

3 respostas
Dennys

Amigos Javaneses…

Segue o problema…

Tenho uma JTable onde quero adicionar novas linhas e tal, porém naum consigo… já tentei vários tipos de ADD mas nada funciona… veja um exemplo…

JTable jTable1 = new JTable(1,2);

jTable1.setBounds(10,10,500,500);

jTable1.setFont(new java.awt.Font(Arial, 1, 12));

jTable1.setValueAt(COLUNA1,0,0);

jTable1.setValueAt(COLUNA2,0,1);

Eu gostaria de saber como adicionar linhas em tempo de execução, sem ter precisar usar new JTable(1,2)

Valeu!Thanks!

3 Respostas

L

Dennys,

Para inserir linhas em uma JTable, é preciso criá-la usando um DefaultTableModel. Neste, existe um método para adicionar linhas.
Veja o exemplo abaixo:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;


public class TesteJTable{

  public static void main( String[] args ){

    Frame f = new Frame();
    f.show();

  }

}

class Frame extends JFrame {

  private JTable table;
  private JButton button;
  private DefaultTableModel model;

  public Frame(){
    super();
    this.setTitle( "Frame JTable" );
    this.setSize( 250, 250 );

    this.addWindowListener( new WindowAdapter(){
                              public void windowClosing( WindowEvent e ){
                                System.exit( 0 );
                              }
                            } 
    );

    // criar TableModel com duas colunas e sem linhas
    model = new DefaultTableModel( 0, 2 );

    // criar JTable com TableModel
    table = new JTable( model );

    this.getContentPane().add( table, BorderLayout.CENTER );

    button = new JButton( "Add Row" );
    button.addActionListener( new ActionListener() {
                                public void actionPerformed( ActionEvent e ) {
                                  String[] s = { "", "" };
                                  
                                  // inserir nova linha
                                  model.addRow( s );   
                   
                                }
                              } 
    );

    this.getContentPane().add( button, BorderLayout.SOUTH );

  }

}

Espero que tenha conseguido ajudá-lo.

T+V

Dennys

lerbach,

MUITO OBRIGADO PELA SUA RESPOSTA AJUDOU MUITO!!!

MAS AI VAI OUTRA DÚVIDA…

COMO FAÇO PARA ACESSAR AS PROPRIEDADES DAS COLUNAS?

TIPO GOSTARIA DE AUMENTAR OU DIMINUIR WITH ENTENDE?

VALEU! MUITO OBRIGADO!

Dennys

OPA!

DEI UMA FUÇADA AKI E ENCONTREI A PROPRIEDADE…

TableColumn = JTable.getColumnModel().getColumn(0);
column.setPreferredWidth(70);

VALEU! PELA DICA DE COMO ADICIONAR LINHAS…

THANKS!

Criado 1 de maio de 2003
Ultima resposta 3 de mai. de 2003
Respostas 3
Participantes 2