Caros amigos,
Tambem sou iniciante e com a ajuda de vcs tenho conseguido
muito...
e depois de batalhar bastante consegui fazer uma aplicacao que responde
muitas perguntas de iniciantes
e acho que deixando aqui vou ajudar muita gente... como tambem tenho conseguido muita ajuda
de vcs estou disponibilizando um exemplo bem simples mas com quase todas as respostas
as duvidas para quem quer trabalhar com um JTable..
nao sei se estou usando a maneira correta de programar em java
mas esta aplicacao funciona
e se alguem tiver alguma coisa ou sugestao para que eu melhor a minha
maneira de programar
desde ja agradeco...
mas esta aplicacao funciona e vcs podem analisar ela ai...
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public class SwingExemplo20Tables {
static JFrame tela = new JFrame("Manutenção em Tabelas");
static JTable tabela = new JTable();
static JLabel lb1 = new JLabel("Código");
static JLabel lb2 = new JLabel("Nome");
static JLabel lb3 = new JLabel("Salário");
static JTextField CpoCodigo = new JTextField();
static JTextField CpoNome = new JTextField();
static JTextField CpoSalario = new JTextField();
static String[] colunas = new String[] { "Código", "Nome", "Salário" };
// static String[][] dados = new String[][] { {} }; //se fizer assim ja
// insere uma linha
static String[][] dados;
@SuppressWarnings("serial")
/*
* Observe bem as duas declaracoes de "modelo" a primeira que esta como
* comentario ele deixa todas as colunas da tabela editaveis
*
* a segunda que nao esta como comentario ela bloqueia para edicao as
* colunas 0 e 1.. deixando editar apenas a coluna 2
*/
// static DefaultTableModel modelo = new DefaultTableModel(dados, colunas);
static DefaultTableModel modelo = new DefaultTableModel(dados, colunas) {
public boolean isCellEditable(int row, int column) {
if (column < 2) {
return false;
}
return true;
}
};
static JScrollPane scrots = new JScrollPane(tabela);
static JButton BotInclui = new JButton("Inclui");
static JButton BotExclui = new JButton("Exclui");
static JButton BotSeleciona = new JButton("Seleciona");
public static void main(String[] args) {
tela.setBounds(0, 0, 800, 600);
tela.setLayout(null);
tabela.setModel(modelo);
tabela.setBounds(5, 10, 300, 300);
lb1.setBounds(5, 400, 200, 20);
lb2.setBounds(5, 450, 200, 20);
lb3.setBounds(5, 500, 200, 20);
CpoCodigo.setBounds(80, 400, 300, 20);
CpoNome.setBounds(80, 450, 300, 20);
CpoSalario.setBounds(80, 500, 300, 20);
scrots.setBounds(10, 50, 500, 300);
BotInclui.setBounds(500, 400, 100, 20);
BotInclui.setActionCommand("BotInclui");
BotExclui.setBounds(500, 450, 100, 20);
BotExclui.setActionCommand("BotExclui");
BotSeleciona.setBounds(500, 500, 100, 20);
BotSeleciona.setActionCommand("BotSeleciona");
ActionListener ac = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if ("BotInclui".equals(e.getActionCommand())) {
inserelinha();
}
if ("BotExclui".equals(e.getActionCommand())) {
excluilinha();
}
if ("BotSeleciona".equals(e.getActionCommand())) {
selecionalinha();
}
}
};
BotInclui.addActionListener(ac);
BotExclui.addActionListener(ac);
BotSeleciona.addActionListener(ac);
tabela.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tela.add(lb1);
tela.add(lb2);
tela.add(lb3);
tela.add(scrots);
tela.add(CpoCodigo);
tela.add(CpoNome);
tela.add(CpoSalario);
tela.add(BotInclui);
tela.add(BotExclui);
tela.add(BotSeleciona);
tela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tela.setVisible(true);
/*
* as linhas abaixo e para dar focus no campo cpocodigo
*/
SwingUtilities.invokeLater(new Runnable() {
public void run() {
CpoCodigo.requestFocus();
}
});
/*
* as linhas abaixo fazem com que as colunas da tabela sejam utilizadas
* para ordenar a tabela
*/
RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(modelo);
tabela.setRowSorter(sorter);
tabela.getRowSorter().toggleSortOrder(0);
tabela.getRowSorter().toggleSortOrder(1);
tabela.getRowSorter().toggleSortOrder(2);
}
static void inserelinha() {
// System.out.println("inclusao");
if (!ValidaTela()) {
return;
}
modelo.addRow(new Object[] { CpoCodigo.getText(), CpoNome.getText(),
CpoSalario.getText() });
CpoCodigo.setText("");
CpoNome.setText("");
CpoSalario.setText("");
}
static void excluilinha() {
int linha = tabela.getSelectedRow();
if (linha < 0) {
JOptionPane.showMessageDialog(null, "Primeiro Selecione a Linha",
"Erro", JOptionPane.ERROR_MESSAGE);
return;
}
modelo.removeRow(linha);
}
static boolean ValidaTela() {
if (CpoCodigo.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Campo Codigo Não Preenchido",
"Erro", JOptionPane.ERROR_MESSAGE);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
CpoCodigo.requestFocus();
}
});
return false;
}
if (CpoNome.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Campo Nome Não Preenchido",
"Erro", JOptionPane.ERROR_MESSAGE);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
CpoNome.requestFocus();
}
});
return false;
}
if (CpoSalario.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Campo Salario Não Preenchido",
"Erro", JOptionPane.ERROR_MESSAGE);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
CpoNome.requestFocus();
}
});
return false;
}
return true;
}
static void selecionalinha() {
int linha = tabela.getSelectedRow();
if (linha < 0) {
JOptionPane.showMessageDialog(null, "Nenhuma Linha Selecionada",
"Erro", JOptionPane.ERROR_MESSAGE);
return;
}
CpoCodigo.setText(modelo.getValueAt(linha, 0).toString());
CpoNome.setText(modelo.getValueAt(linha, 1).toString());
CpoSalario.setText(modelo.getValueAt(linha, 2).toString());
System.out.println(tabela.getRowCount());
int c = tabela.getRowCount();
tabela.removeRowSelectionInterval(0, c - 1);
}
}