import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class JTablePaginada extends JFrame {
private JPanel contentPane, buttonPane;
private JButton btnFirst, btnPrevious, btnNext, btnLast, btnClean;
private JTable table;
private TesteTableModel model;
private static final int ITENS_POR_PAG = 5;
public static void main(String[] args) {
EventQueue.invokeLater(()-> new JTablePaginada().setVisible(true));
}
public JTablePaginada() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(500, 400));
contentPane = new JPanel();
model = new TesteTableModel(JSONUtils.JSONtoList());
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
//o width é um pequeno "workaround pra tabela ficar certinha na tela
//a altura é definida pela quantidade de itens que quer exibir
//mais a altura do cabeçalho
scrollPane.setPreferredSize(new Dimension(getPreferredSize().width - 20, table.getRowHeight() * ITENS_POR_PAG + table.getTableHeader().getPreferredSize().height));
contentPane.add(scrollPane);
this.add(contentPane, BorderLayout.CENTER);
btnClean = new JButton("Remover tudo");
btnFirst = new JButton("<<");
btnFirst.addActionListener(e -> {
JScrollBar bar = scrollPane.getVerticalScrollBar();
bar.setValue(0);
});
btnPrevious = new JButton("<");
btnPrevious.addActionListener(e -> {
int height = table.getRowHeight() * (ITENS_POR_PAG - 1);
JScrollBar bar = scrollPane.getVerticalScrollBar();
bar.setValue(bar.getValue() - height);
});
btnNext = new JButton(">");
btnNext.addActionListener(e -> {
int height = table.getRowHeight() * (ITENS_POR_PAG - 1);
JScrollBar bar = scrollPane.getVerticalScrollBar();
bar.setValue(bar.getValue() + height);
});
btnLast = new JButton(">>");
btnLast.addActionListener(e -> {
JScrollBar bar = scrollPane.getVerticalScrollBar();
bar.setValue(bar.getMaximum());
});
buttonPane = new JPanel();
buttonPane.add(btnFirst);
buttonPane.add(btnPrevious);
buttonPane.add(btnNext);
buttonPane.add(btnLast);
this.add(buttonPane, BorderLayout.SOUTH);
pack();
}
}
#Comentários complementares