Pagination Example
Output Screen :
SQL Query :
mysql> create table posts (userid int,id int primary key,title varchar(80),body varchar(250));
Post.java
package com.deepsingh44.blogspot.model;
public class Post {
private int userId;
private int id;
private String title;
private String body;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
Dao.java
package com.deepsingh44.blogspot.dao;
import java.sql.Connection;
import java.sql.DriverManager;
public class Dao {
public static Connection con;
public static Connection getMyConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
} catch (Exception e) {
System.out.println(e);
}
return con;
}
}
PaginationDemo.java
package com.deepsingh44.blogspot.ui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.BevelBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import org.json.JSONArray;
import com.deepsingh44.blogspot.dao.Dao;
import com.deepsingh44.blogspot.model.Post;
import com.google.gson.Gson;
import javax.swing.JTextField;
import javax.swing.JTable;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.swing.border.LineBorder;
public class PaginationDemo extends JFrame implements ActionListener {
private JPanel contentPane;
private JTable table;
int page = 1;
int perpage = 10;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PaginationDemo frame = new PaginationDemo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
List<JButton> buttons;
public PaginationDemo() {
setTitle("Pagination Tutorial With Live Data");
int rowcount = getAllRowCount();
if (rowcount == 0) {
storeLiveData();
}
int numbuttons = rowcount / perpage;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 586, 464);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
String[] cols = { "Id", "Title", "Body" };
DefaultTableModel dt = new DefaultTableModel(cols, 0);
table = new JTable(dt);
table.setRowHeight(24);
JScrollPane jp = new JScrollPane(table);
jp.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
jp.setBounds(22, 38, 518, 262);
contentPane.add(jp);
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(0, 0, 0)));
panel.setBounds(22, 340, 518, 34);
contentPane.add(panel);
buttons = new ArrayList<>();
for (int i = 1; i <= numbuttons; i++) {
JButton b1 = new JButton(String.valueOf(i));
b1.setActionCommand(String.valueOf(i));
b1.setBackground(Color.RED);
b1.setForeground(Color.WHITE);
b1.addActionListener(this);
panel.add(b1);
buttons.add(b1);
if (b1.getActionCommand().equals("1")) {
call("1");
b1.setBackground(Color.GREEN);
}
}
}
public int getAllRowCount() {
int rowcount = 0;
try (Connection con = Dao.getMyConnection();) {
PreparedStatement ps = con.prepareStatement("select count(*) from posts");
ResultSet rs = ps.executeQuery();
if (rs.next()) {
rowcount = rs.getInt(1);
}
} catch (Exception e) {
System.out.println(e);
}
return rowcount;
}
private List<Post> getData(int start, int perpage) {
List<Post> posts = new ArrayList<>();
try (Connection con = Dao.getMyConnection();) {
PreparedStatement ps = con.prepareStatement("select * from posts limit ?,?");
ps.setInt(1, start);
ps.setInt(2, perpage);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Post post = new Post();
post.setUserId(rs.getInt(1));
post.setId(rs.getInt(2));
post.setTitle(rs.getString(3).toUpperCase(Locale.getDefault()));
post.setBody(rs.getString(4).toUpperCase(Locale.getDefault()));
posts.add(post);
}
} catch (Exception e) {
System.out.println(e);
}
return posts;
}
private void storeLiveData() {
try {
URL url = new URL("https://jsonplaceholder.typicode.com/posts");
HttpURLConnection hr = (HttpURLConnection) url.openConnection();
InputStream im = hr.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(im));
StringBuffer sb = new StringBuffer();
String line = br.readLine();
while (line != null) {
sb.append(line).append("\n");
line = br.readLine();
}
JSONArray jsonArray = new JSONArray(sb.toString());
Gson gson = new Gson();
try (Connection con = Dao.getMyConnection();) {
PreparedStatement ps = con.prepareStatement("insert into posts values(?,?,?,?)");
for (int i = 0; i < jsonArray.length(); i++) {
Post post = gson.fromJson(jsonArray.getJSONObject(i).toString(), Post.class);
ps.setInt(1, post.getUserId());
ps.setInt(2, post.getId());
ps.setString(3, post.getTitle());
ps.setString(4, post.getBody());
ps.addBatch();
}
int i[] = ps.executeBatch();
System.out.println(i.length);
} catch (Exception e) {
System.out.println(e);
}
} catch (Exception e) {
System.out.println(e);
}
}
@Override
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
setBackgroundColor(e.getActionCommand());
b.setBackground(Color.GREEN);
call(b.getActionCommand());
}
private void call(String id) {
DefaultTableModel dt = (DefaultTableModel) table.getModel();
int allrow = dt.getRowCount();
if (allrow > 0) {
deleteAllRow(dt);
}
for (Post post : getData((Integer.parseInt(id) - 1) * perpage, perpage)) {
dt.addRow(new Object[] { post.getId(), post.getTitle(), post.getBody() });
}
}
private void deleteAllRow(DefaultTableModel dt) {
int allrow = dt.getRowCount();
for (int i = allrow - 1; i >= 0; i--) {
dt.removeRow(i);
}
}
private void setBackgroundColor(String id) {
for (JButton b : buttons) {
if (!b.getActionCommand().equals(id)) {
b.setBackground(Color.red);
}
}
}
}
No comments:
Post a Comment