0
I am creating an application where I fill the data of a table through the database, but there are many so I wanted to organize better.
However, the results shown in the table are not constant. The implemented methods behave in different ways even with the same button being pressed.
When I use the alunos_1.json
, that has a page with less than the maximum number of records allowed, the table loads and everything works the way I said, but when I load a json alunos.json
that has a number divisible by the maximum number of records does not work.
Table class
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Teste extends JFrame{
//MAIN METHOD
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
//INITIALIZE JFRAME FORM
teste.Teste form=new teste.Teste();
form.setVisible(true);;
}
});
}
TesteTableModel tableModel = new TesteTableModel();
List<TesteModel> resultado = new ArrayList<TesteModel>();
List<TesteModel> lista = new ArrayList<TesteModel>();
int indiceLista, maxLista, resto, totalPag = 0;
int paginaAtual = 1;
private static final int ITENS_POR_PAG = 5;
private java.awt.Button btnRemover, btnProxima, btnAnterior, btnPrimeira, btnUltima;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane;
private javax.swing.JTable jTable;
private java.awt.ScrollPane scrollPane;
//CONSTRUCTOR
public Teste()
{
scrollPane = new java.awt.ScrollPane();
jScrollPane = new javax.swing.JScrollPane();
jTable = new javax.swing.JTable();
btnRemover = new java.awt.Button();
btnAnterior = new java.awt.Button();
btnProxima = new java.awt.Button();
btnUltima = new java.awt.Button();
btnPrimeira = new java.awt.Button();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(500, 400));
jTable.setModel(tableModel);
jScrollPane.setViewportView(jTable);
scrollPane.add(jScrollPane);
btnRemover.setLabel("Remover");
btnAnterior.setLabel("<");
btnProxima.setLabel(">");
btnUltima.setLabel(">>");
btnPrimeira.setLabel("<<");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(btnRemover, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 293, Short.MAX_VALUE)
.addComponent(btnPrimeira, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnAnterior, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnProxima, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(5, 5, 5)
.addComponent(btnUltima, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(scrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 316, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnRemover, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnAnterior, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnProxima, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnUltima, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnPrimeira, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
btnRemover.getAccessibleContext().setAccessibleName("btnRemover");
pack();
btnRemover.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
tableModel.deletarLinhas();
}
});
btnProxima.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(indiceLista <= lista.size()){
btnAnterior.setEnabled(true);
btnPrimeira.setEnabled(true);
resultado = carregaProximaPagina(lista);
for(TesteModel teste: resultado){
tableModel.addRow(teste);
}
}
}
});
btnAnterior.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0){
if(indiceLista != 0){
btnProxima.setEnabled(true);
btnUltima.setEnabled(true);
resultado = carregaPaginaAnterior(lista);
for(TesteModel teste: resultado){
tableModel.addRow(teste);
}
}
}
});
btnUltima.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
resultado = carregaUltimaPagina(lista);
for(TesteModel teste: resultado){
tableModel.addRow(teste);
}
}
});
btnPrimeira.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
resultado = carregaPrimeiraPagina(lista);
for(TesteModel teste: resultado){
tableModel.addRow(teste);
}
}
});
//Preenche dados iniciais da tabela
lista = tableModel.lerJSON();
paginaAtual = (int) lista.size() / ITENS_POR_PAG;
resto = lista.size() % ITENS_POR_PAG;
System.out.println("\npagina:" + paginaAtual
+ "\nresto:" + resto);
resultado = carregaProximaPagina(lista);
for(TesteModel teste: resultado){
tableModel.addRow(teste);
}
btnAnterior.setEnabled(false);
btnPrimeira.setEnabled(false);
}
private void limparTabela() {
while (jTable.getModel().getRowCount() > 0) {
((TesteTableModel) jTable.getModel()).removeRow(0);
}
}
public List<TesteModel> carregaProximaPagina(List<TesteModel> testes){
limparTabela();
List<TesteModel> resultado = new ArrayList<TesteModel>();
if(resto > 0){
if(paginaAtual > 0){
indiceLista = maxLista;
maxLista += ITENS_POR_PAG;
for(int i = indiceLista; i < maxLista; i++){
resultado.add(testes.get(i));
}
System.out.println("\nindiceLista:" + indiceLista
+ "\nmaxLista:" + maxLista
+ "\npagina:" + paginaAtual);
} else {
indiceLista = maxLista;
maxLista += resto;
for(int i = indiceLista; i < maxLista; i++){
resultado.add(testes.get(i));
}
btnProxima.setEnabled(false);
btnUltima.setEnabled(false);
System.out.println("\nindiceLista:" + indiceLista
+ "\nmaxLista:" + maxLista
+ "\npagina:" + paginaAtual);
}
}
paginaAtual--;
return resultado;
}
public List<TesteModel> carregaPaginaAnterior(List<TesteModel> testes){
limparTabela();
List<TesteModel> resultado = new ArrayList<TesteModel>();
if(paginaAtual == 0){
maxLista = indiceLista;
indiceLista = maxLista - ITENS_POR_PAG;
for(int i = indiceLista; i < maxLista; i++){
resultado.add(testes.get(i));
}
System.out.println("\nindiceLista:" + indiceLista
+ "\nmaxLista:" + maxLista
+ "\npagina:" + paginaAtual);
} else {
if(paginaAtual == ((int) testes.size() / ITENS_POR_PAG)){
btnAnterior.setEnabled(false);
btnPrimeira.setEnabled(false);
}
indiceLista -= ITENS_POR_PAG;
maxLista -= ITENS_POR_PAG;
for(int i = indiceLista; i < maxLista; i++){
resultado.add(testes.get(i));
}
System.out.println("\nindiceLista:" + indiceLista
+ "\nmaxLista:" + maxLista
+ "\npagina:" + paginaAtual);
}
paginaAtual++;
return resultado;
}
public List<TesteModel> carregaPrimeiraPagina(List<TesteModel> testes){
limparTabela();
List<TesteModel> resultado = new ArrayList<TesteModel>();
totalPag = (int) lista.size() / ITENS_POR_PAG;
indiceLista = 0;
maxLista = ITENS_POR_PAG;
for(int i = indiceLista; i < maxLista; i++){
resultado.add(testes.get(i));
}
System.out.println("\nindiceLista:" + indiceLista
+ "\nmaxLista:" + maxLista
+ "\npagina:" + paginaAtual);
return resultado;
}
public List<TesteModel> carregaUltimaPagina(List<TesteModel> testes){
limparTabela();
List<TesteModel> resultado = new ArrayList<TesteModel>();
totalPag = (int) lista.size() / ITENS_POR_PAG;
if(resto != 0) {
indiceLista = ITENS_POR_PAG * totalPag;
maxLista = indiceLista + resto;
for(int i = indiceLista; i < maxLista; i++){
resultado.add(testes.get(i));
}
paginaAtual = 0;
System.out.println("\nindiceLista:" + indiceLista
+ "\nmaxLista:" + maxLista
+ "\npagina:" + paginaAtual);
} else {
indiceLista = ITENS_POR_PAG * totalPag;
maxLista = indiceLista + ITENS_POR_PAG;
for(int i = indiceLista; i < maxLista; i++){
resultado.add(testes.get(i));
}
System.out.println("\nindiceLista:" + indiceLista
+ "\nmaxLista:" + maxLista
+ "\npagina:" + paginaAtual);
}
return resultado;
}
}
Testetablemodel
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import jdk.nashorn.internal.parser.JSONParser;
import org.json.JSONObject;
public class TesteTableModel extends AbstractTableModel {
private List<TesteModel> dados = new ArrayList<>();
private String[] colunas = {"Selecionar", "Nome"};
public Class<?> getColumnClass(int columnIndex) {
return columnIndex == 0 ? Boolean.class : super.getColumnClass(columnIndex);
}
@Override
public String getColumnName(int column){
return colunas[column];
}
@Override
public int getColumnCount() {
return colunas.length;
}
@Override
public int getRowCount() {
return dados.size();
}
@Override
public Object getValueAt(int linha, int coluna) {
switch(coluna){
case 0:
return dados.get(linha).getSelecionado();
case 1:
return dados.get(linha).getNome();
}
return null;
}
public void setValueAt(Object valor, int linha, int coluna) {
TesteModel tm = dados.get(linha);
switch (coluna) {
case 0:
tm.setSelecionado(new Boolean((Boolean) valor));
break;
}
fireTableDataChanged();
}
public void addRow(TesteModel tm) {
this.dados.add(tm);
this.fireTableDataChanged();
}
public void removeRow(int linha){
this.dados.remove(linha);
this.fireTableRowsDeleted(linha, linha);
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 0;
}
public void deletarLinhas() {
for (int i = getRowCount() - 1; i >= 0; i--) {
if (dados.get(i).getSelecionado()) {
removeRow(i);
}
}
}
public String lerArquivo() {
String linha = "";
try {
FileReader arq = new FileReader("C:\\Users\\maily\\Documents\\NetBeansProjects\\Teste\\src\\teste\\alunos_1.json");
BufferedReader lerArq = new BufferedReader(arq);
linha = lerArq.readLine();
/*while (linha != null) {
System.out.printf(linha);
linha = lerArq.readLine(); // lê da segunda até a última linha
}*/
arq.close();
} catch (IOException e) {
System.err.printf("Erro na abertura do arquivo: %s.\n",
e.getMessage());
}
//System.out.println(linha);
return linha;
}
public List<TesteModel> lerJSON() {
String str = lerArquivo();
Type type = new TypeToken<List<TesteModel>>(){}.getType();
Gson gson = new GsonBuilder().create();
List<TesteModel> lista = gson.fromJson(str, type);
for(TesteModel teste: lista){
System.out.println(teste.getSelecionado());
System.out.println(teste.getNome());
}
return lista;
}
}
Model class
public class TesteModel {
private Boolean select;
private String name;
public Boolean getSelecionado() {
return select;
}
public void setSelecionado(Boolean selecionado) {
this.select = selecionado;
}
public String getNome() {
return name;
}
public void setNome(String nome) {
this.name = nome;
}
}
json students.
[{"select": "false", "name": "Ana 01"}, {"select": "false", "name": "João"}, {"select": "false", "name": "Laura"}, {"select": "false", "name": "Bruno"}, {"select": "false", "name": "Carina"}, {"select": "false", "name": "José 02"}, {"select": "false", "name": "Maria"}, {"select": "false", "name": "Renato"}, {"select": "false", "name": "Paula"}, {"select": "false", "name": "Juliano"}, {"select": "false", "name": "Júlio 03"}, {"select": "false", "name": "Amanda"}, {"select": "false", "name": "André"}, {"select": "false", "name": "Tales"},{"select": "false", "name": "Pedro"}, {"select": "false", "name": "João 04"}, {"select": "false", "name": "Laura"}, {"select": "false", "name": "Bruno"}, {"select": "false", "name": "Carina"},{"select": "false", "name": "Pedro"}, {"select": "false", "name": "João 05"}, {"select": "false", "name": "Laura"}, {"select": "false", "name": "Bruno"}, {"select": "false", "name": "Carina"},{"select": "false", "name": "Pedro"}, {"select": "false", "name": "João 06"}, {"select": "false", "name": "Laura"}, {"select": "false", "name": "Bruno"}, {"select": "false", "name": "Carina"},{"select": "false", "name": "Pedro"}]
alunos_1.json
[{"select": "false", "name": "Ana 01"}, {"select": "false", "name": "João"}, {"select": "false", "name": "Laura"}, {"select": "false", "name": "Bruno"}, {"select": "false", "name": "Carina"}, {"select": "false", "name": "José 02"}, {"select": "false", "name": "Maria"}, {"select": "false", "name": "Renato"}, {"select": "false", "name": "Paula"}, {"select": "false", "name": "Juliano"}, {"select": "false", "name": "Júlio 03"}, {"select": "false", "name": "Amanda"}, {"select": "false", "name": "André"}, {"select": "false", "name": "Tales"},{"select": "false", "name": "Pedro"}, {"select": "false", "name": "João 04"}, {"select": "false", "name": "Laura"}, {"select": "false", "name": "Bruno"}, {"select": "false", "name": "Carina"},{"select": "false", "name": "Pedro"}, {"select": "false", "name": "João 05"}, {"select": "false", "name": "Laura"}, {"select": "false", "name": "Bruno"}, {"select": "false", "name": "Carina"},{"select": "false", "name": "Pedro"}, {"select": "false", "name": "João 06"}, {"select": "false", "name": "Laura"}, {"select": "false", "name": "Bruno"}, {"select": "false", "name": "Carina"},{"select": "false", "name": "Pedro"}, {"select": "false", "name": "Bruno"}, {"select": "false", "name": "Carina"},{"select": "false", "name": "Joselino RESTO"}]
Gson’s lib may be lowland here.
@Lys is a lot for an objective answer, I would need a tutorial (that does not fit in the proposal of this site here). The ideal would be you at least [Edit] and give more details of what you have, the structures, so that we can help. Help us to help you, and we will guide you through here until you get a possible question to answer.
– Bacco
For example, you can post a basic code without the paging part, but with the structures you already have ready, simplifying a little. When you learn with little data, you will surely know with more data.
– Bacco
It depends on how you load the data. If you bring all the data from the table at once, I think it’s a waste of time making pagination, not worth the effort because it will be just visual, the performance and memory cost will be the same.
– user28595
In the final application, data will be loaded from a JSON.
– lys
@Lys edited the comment.
– user28595
I will bring at once yes reading from JSON, but it is a requirement that this table has pagination.
– lys
@Lys vejo q vc is still using absolute layout and due to this, it is not possible to make paging efficiently, because of the line size. I suggest you read my tip of your last reply and switch to relative layouts, so it’s easy to implement
– user28595
Or can I suggest a General solution and you look and study how to adapt to your code.
– user28595
Why use joptionpane to show table? The purpose of this component is not well for this.
– user28595
I’m sorry, but I’m not using Joptionpane anywhere. I’m trying to recreate with some relative layout so that I can get the help I need.
– lys
Sorry, I mistook it for an old code here. Just one last doubt, Voce will rescue all table data in one time, but wants to display them by paging?
– user28595
I need them to appear for example, 10 records at a time. So, I think it’s smarter to slowly rescue and store the index that I stopped to continue after.
– lys
Then you would need to present a [mcve] how Voce retrieves data from its actual table, as the example will be based on the data already in the table. Without seeing and testing the actual implementation Voce recovers the data has no way to suggest anything that will suit you.
– user28595
Let’s go continue this discussion in chat.
– user28595