[java]
package com.manymore13.page;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.security.acl.LastOwnerException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PageNumDemo extends JFrame
{
private int sumPage = 35;//总的页码数,这里作为Demo,就写个固定值
private int currentPage=1; // 默认是第一页
private JPanel pageBtns = new JPanel(); // 存放一系列页码按钮 默认流布局
PageNumDemo()
{
Image image = null;
try
{
image = ImageIO.read((this.getClass().getResource("./image/logo.png")));
} catch (IOException e){
e.printStackTrace();
}
this.setIconImage((Image)image);// 设置窗口左上角的图标,我这里是个快播的图标
this.setTitle("仿网页分页页码"); //设置窗口标题
this.setLayout(new FlowLayout(15,20,20)); //设置JFrame的布局
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 档点击叉叉时,窗口可关闭
this.setVisible(true); // 窗口可见
this.setLocationRelativeTo(null); //窗口居中
setPageBottom(1); //默认显示第一页 ,设置页码布局
this.setSize(850, 118); // 窗口宽高
this.setResizable(true);// 设置窗口可拉伸
}
/**
*
* @param selectNum 你按下的页码数字,例如你按下按钮5,就需要传个整型5
*/
private void setPageBottom(int selectNum)
{
pageBtns.removeAll();
if(selectNum<=0 || selectNum>sumPage){
return;
}
// 这个是显示数字按钮的总个数,不包括首页 尾页等其他按钮
int countNumBtn = 9; // 首页 1 2 3 4 5 6 7 8 9 尾页
int half = countNumBtn/2;
int startNum = 0;
int endNum = 0;
JButton btnFistPage = new JButton("首页");
btnFistPage.setActionCommand("首页");
btnFistPage.setToolTipText("首页");
btnFistPage.setToolTipText("首页");
btnFistPage.addActionListener(new BottomPageButtonAction());
JButton btnLastPage = new JButton("末页");
btnLastPage.setActionCommand("末页");
btnLastPage.addActionListener(new BottomPageButtonAction());
btnLastPage.setToolTipText("共"+sumPage+"页");
Container con = this.getContentPane();
con.invalidate();
pageBtns.add(btnFistPage);
if(selectNum !=1){
JButton btnPrePage = new JButton("上一页");
btnPrePage.setActionCommand("上一页");
btnPrePage.setToolTipText("上一页是第"+(selectNum-1>=1?selectNum-1:1)+"页");
btnPrePage.addActionListener(new BottomPageButtonAction());
pageBtns.add(btnPrePage);
}
// 下面开始计算从左至右数字键(JButton)上的text
int minBtnNum = selectNum-half;
int maxBtnNum = selectNum+half;
if(minBtnNum>0 && maxBtnNum<=sumPage){
startNum = minBtnNum;
endNum = maxBtnNum;
}else if(minBtnNum<=0){
startNum =1;
endNum = countNumBtn>sumPage?sumPage:countNumBtn;
}else if(maxBtnNum>sumPage){
startNum = sumPage >countNumBtn?sumPage-(countNumBtn-1):1;
endNum = sumPage;
}
for(int i=startNum;i<=endNum;i++){
JButton btn = new JButton();
btn.addActionListener(new BottomPageButtonAction(i));
btn.setActionCommand("数字");
btn.setToolTipText("第"+i+"页");
btn.setText(i+"");
if(i==selectNum){
btn.setBackground(Color.red);
}else{  
补充:Web开发 , 其他 ,