E aí pessoal… to com um probleminha com Jtable… já vi em vários foruns como criar as tabelas e tudo mais… mas não consigo fazer isso usando o net beans… será q alguém pode me ajudar???
passo a passo como faço para criar uma tabela simpes,(que mostre minhas consultas sql ou qualquer outra coisa), no NETBEANS?
Jtable x netbeans
9 Respostas
Não tem jeito amigo, vai ter que programar na mão.
O NetBeans não tem nada pra fazer a ligação entre uma consulta SQL e o table.
Dica: procure aqui no GUJ por JTable e Table Model.
Eu lembrei de um projeto que trás uns componentes Swing pra auxiliar acesso a banco de dados com JDBC.
Você pode adicioná-los ao NetBeans.
Existem outros pacotes de javabeans neste estilo, alguns pagos, mas quem sabe se procurar um pouco mais.
Eu lembrei de um projeto que trás uns componentes Swing pra auxiliar acesso a banco de dados com JDBC.Você pode adicioná-los ao NetBeans.
Existem outros pacotes de javabeans neste estilo, alguns pagos, mas quem sabe se procurar um pouco mais.
Vc já usou ele em agum teste/projetinho?
Eu criei umas classes para trabalho com o JTable. Se liga aí.
- MyTableModel:
import javax.swing.table.AbstractTableModel;
import java.util.Vector;
public class MyTableModel extends AbstractTableModel {
private Vector rows;
private Vector columns;
private int[] editableRows;
private int[] editableColumns;
private boolean respectRowsAndColumnsToEnable;
private boolean allCellsEditable;
private boolean rowsSetted;
private boolean columnsSetted;
/** Creates a new instance of MyTableModel */
public MyTableModel() {
setAttributes(new Vector(1, 1), new Vector(1, 1), false, false);
}
public MyTableModel(Vector columns) {
setAttributes(new Vector(1, 1), columns, false, true);
}
public MyTableModel(Vector rows, Vector columns) {
setAttributes(rows, columns, true, true);
}
private void setAttributes(Vector rows, Vector columns, boolean rowsSetted, boolean columnsSetted) {
setColumns(nonNullVector(columns));
setRows(nonNullVector(rows));
setEditableRows(new int[0]);
setEditableColumns(new int[0]);
setEditableRowsAndColumnsRespected(true);
setAllCellsEditable(false);
this.rowsSetted = rowsSetted;
this.columnsSetted = columnsSetted;
}
private Vector nonNullVector(Vector v) {
return (v != null) ? v : new Vector(1, 1);
}
private Vector justifyRow(Vector row) {
row = nonNullVector(row);
row.setSize(getColumns().size());
return row;
}
private void justifyEditableRows() {
if(getEditableRows() != null) {
if(getEditableRows().length > getRowCount()) {
int[] actualEditableRows = getEditableRows();
this.editableRows = new int[getRowCount()];
for(int i=0; i<getRowCount(); i++) getEditableRows()[i] = actualEditableRows[i];
}
}
}
private void justifyEditableColumns() {
if(getEditableColumns() != null) {
if(getEditableColumns().length > getColumnCount()) {
int[] actualEditableColumns = getEditableColumns();
this.editableColumns = new int[getColumnCount()];
for(int i=0; i<getColumnCount(); i++) getEditableColumns()[i] = actualEditableColumns[i];
}
}
}
public int getRowCount() {
return getRows().size();
}
public int getColumnCount() {
return getColumns().size();
}
public String getColumnName(int col) {
Object id = null;
if(col >< columns.size()) id = columns.elementAt(col);
return (id == null) ? super.getColumnName(col) : id.toString();
}
public Class getColumnClass(int col) {
return getValueAt(0, col).getClass();
}
public Object getValueAt(int row, int col) {
Object value = ((Vector) getRows().elementAt(row)).elementAt(col);
if(value != null) return value;
return new String();
}
public void setValueAt(Object value, int row, int col) {
try {
if(value != null) ((Vector) getRows().elementAt(row)).setElementAt(value, col);
else ((Vector) getRows().elementAt(row)).setElementAt(new String(), col);
}
catch(ArrayIndexOutOfBoundsException aioobe) {
((Vector) getRows().elementAt(row)).addElement(new String());
};
fireTableCellUpdated(row, col);
}
public boolean isCellEditable(int row, int col) {
if(areAllCellsEditable()) {
return true;
}
else if(areEditableRowsAndColumnsRespected()) {
boolean editableRow = false, editableColumn = false;
if(getEditableRows().length > 0) {
for(int i=0; i<getEditableRows().length; i++) {
if(row == getEditableRows()[i]) {
editableRow = true;
break;
}
}
};
if(getEditableColumns().length > 0) {
for(int i=0; i<getEditableColumns().length; i++) {
if(col == getEditableColumns()[i]) {
editableColumn = true;
break;
}
}
};
return (editableRow || editableColumn);
};
return false;
}
public void removeData() {
rows.removeAllElements();
fireTableDataChanged();
}
public void clear() {
rows.removeAllElements();
columns.removeAllElements();
fireTableStructureChanged();
}
public Vector getRows() {
return rows;
}
public void setRows(Vector rows) {
this.rows = nonNullVector(rows);
rowsSetted = true;
if(columnsSetted)
for(int i=0; i><getRows().size(); i++) justifyRow((Vector) getRows().elementAt(i));
justifyEditableRows();
fireTableStructureChanged();
}
public Vector getColumns() {
return columns;
}
public void setColumns(Vector columns) {
this.columns = nonNullVector(columns);
columnsSetted = true;
justifyEditableColumns();
fireTableStructureChanged();
}
public void setRowsAndColumns(Vector rows, Vector columns) {
setColumns(columns);
setRows(rows);
}
public int[] getEditableRows() {
return editableRows;
}
public void setEditableRows(int[] editableRows) {
this.editableRows = editableRows;
if((getRows() != null) && rowsSetted) justifyEditableRows();
}
public int[] getEditableColumns() {
return editableColumns;
}
public void setEditableColumns(int[] editableColumns) {
this.editableColumns = editableColumns;
if((getColumns() != null) && columnsSetted) justifyEditableColumns();
}
public boolean areEditableRowsAndColumnsRespected() {
return respectRowsAndColumnsToEnable;
}
public void setEditableRowsAndColumnsRespected(boolean respectRowsAndColumnsToEnable) {
this.respectRowsAndColumnsToEnable = respectRowsAndColumnsToEnable;
}
public boolean areAllCellsEditable() {
return allCellsEditable;
}
public void setAllCellsEditable(boolean allCellsEditable) {
this.allCellsEditable = allCellsEditable;
}
}
- MyTableCellRenderer:
import javax.swing.JLabel;
import javax.swing.JCheckBox;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.Component;
import java.awt.Color;
import java.awt.Font;
public class MyTableCellRenderer extends DefaultTableCellRenderer {
private JLabel label;
private JCheckBox checkBox;
private JLabel createLabel() {
JLabel l = new JLabel();
l.setOpaque(true);
l.setFont(new java.awt.Font("arial", Font.PLAIN, 12));
return l;
}
public Component getTableCellRendererComponent (
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
if(value instanceof String) {
label = createLabel();
label.setText(String.valueOf(value));
if(isSelected) label.setBackground(new Color(158, 185, 214));
else label.setBackground(Color.WHITE);
return label;
}
else if(value instanceof Boolean) {
JCheckBox checkBox = new JCheckBox();
checkBox.setSelected(((Boolean) value).booleanValue());
checkBox.setHorizontalAlignment(JCheckBox.CENTER);
if(isSelected) checkBox.setBackground(new Color(158, 185, 214));
else checkBox.setBackground(table.getBackground());
return checkBox;
}
else {
label = createLabel();
label.setBackground(Color.WHITE);
return label;
}
}
}
- MyTableCellEditor:
import javax.swing.JTextField;
import javax.swing.JCheckBox;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import javax.swing.AbstractCellEditor;
import java.awt.Component;
import java.awt.Color;
public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor {
private JTextField textField;
private JCheckBox checkBox;
private int flag;
private final static int BOOLEAN = 0;
private final static int TEXT = 1;
private final static int NONE = 2;
private JTextField createTextField(JTable t, Object o, boolean is, int r, int c) {
TableCellEditor tce = t.getDefaultEditor(o.getClass());
JTextField tf = (JTextField) tce.getTableCellEditorComponent(t, o, is, r, c);
if(is) tf.setBackground(Color.WHITE);
return tf;
}
public Object getCellEditorValue() {
switch(flag) {
case TEXT:
return textField.getText();
case BOOLEAN:
return checkBox.isSelected();
default:
return new String();
}
}
public Component getTableCellEditorComponent (
JTable table, Object value, boolean isSelected, int row, int col) {
if(value instanceof String) {
flag = TEXT;
textField = createTextField(table, value, isSelected, row, col);
return textField;
}
else if(value instanceof Boolean) {
flag = BOOLEAN;
checkBox = new JCheckBox();
checkBox.setSelected(((Boolean) value).booleanValue());
checkBox.setHorizontalAlignment(JCheckBox.CENTER);
if(isSelected) checkBox.setBackground(table.getBackground());
return checkBox;
}
else {
flag = NONE;
String text = new String();
textField = createTextField(table, text, isSelected, row, col);
textField.setText(text);
return textField;
}
}
}
É só setar em setModel(), renderer e editor e preencher com vetores…
>
indique as colunas do MyTableModel como um vetor e as linhas (dados) como um vetor de vetores.
- Teste:
Vector columnsOfAlunoTable = new Vector(1, 1);
columnsOfAlunoTable.add("Remover?");
columnsOfAlunoTable.add("Matrícula");
columnsOfAlunoTable.add("Nome");
atm = new MyTableModel(columnsOfAlunoTable); //preenche as colunas;
alunoTable.setModel(atm);
alunoTable.getColumn("Remover?").setCellEditor(new MyTableCellEditor());
alunoTable.getColumn("Remover?").setCellRenderer(new MyTableCellRenderer());
alunoTable.getColumn("Matrícula").setCellEditor(new MyTableCellEditor());
alunoTable.getColumn("Matrícula").setCellRenderer(new MyTableCellRenderer());
alunoTable.getColumn("Nome").setCellEditor(new MyTableCellEditor());
alunoTable.getColumn("Nome").setCellRenderer(new MyTableCellRenderer());
alunoTable.getColumnModel().getColumn(0).setMaxWidth(70);
alunoTable.getColumnModel().getColumn(1).setMaxWidth(160);
Não tem jeito amigo, vai ter que programar na mão.
O NetBeans não tem nada pra fazer a ligação entre uma consulta SQL e o table.
Dica: procure aqui no GUJ por JTable e Table Model.
Ok... mas onde eu digito (crio a tabela no net beans).. tem que usar o componente Jtable.. alterar as propriedades..´.???
por favor me ajudem???
Não tem jeito amigo, vai ter que programar na mão. O NetBeans não tem nada pra fazer a ligação entre uma consulta SQL e o table. Dica: procure aqui no GUJ por JTable e Table Model.Ok... mas onde eu digito (crio a tabela no net beans).. tem que usar o componente Jtable.. alterar as propriedades..´.???
por favor me ajudem???
Ajudar tudo bem.... Dar o codigo de mão beijada... 150$ a hora...
Dicas:
- Primeiro, pegue um tutorial sobre JTable. APrenda sobre ela. Tem bons tutoriais por ai pra saber como funciona. Se não conhecer, pegue um tutorial basico ( aqui do GUJ ) e vc vai entender como funciona a JTable.
- Depois, pegue esse TableModel que o nosso amigo postou aqui, e vc vai entender o que é e onde colocar.
- QUando tiver ideia do que é uma JTable, com certeza vc vai saber onde colocar no seu codigo.
- Com relação ao Netbeans, se vc clicar e arrastar a JTable na sua tela ( GUI ) ele vai criar a JTable no seu codigo bunitinho, e dai eh so alterar seu codigo pra fazer ela funcionar.
Não tem segredo véio, é só seguir estes passos, eu 'agarantio'....
flw!
Eu lembrei de um projeto que trás uns componentes Swing pra auxiliar acesso a banco de dados com JDBC.Você pode adicioná-los ao NetBeans.
Existem outros pacotes de javabeans neste estilo, alguns pagos, mas quem sabe se procurar um pouco mais.Vc já usou ele em agum teste/projetinho?
Fiz pequenos testes uma vez. Infelizmente, ainda não participei de projetos Java para desktop.
Só pra comentar sobre o swingset:
Tem um Bean de conection JDBC (indica driver, url, aí manda um createConnection()), Model pra JTable, JDBCRowSet (indica o Connection e o comando sql, e depois de um execute() ele mantem o ResultSet), e um DataGrid que é um JTable.
A ligação que fiz no teste foi assim assim:
SSConection <-- SSJdbcRowSetImpl <-- SSTableModel <--> SSDataGrid
Ajudar tudo bem.... Dar o codigo de mão beijada... 150$ a hora...
valeu cara! com certeza não é isso que eu quero… eu quero aprender como fazer! se não não estaria pedindo ajuda num fórum… mas como vcs sabem iniciar numa linguagem não é fácil… estou dando os primeiros passos em java… obrigado pela compreensõa e obrigado pela ajuda!
É por isso que muitas pessoas migrama para o C# quando chegam em jTable…