文章目录
- 前言
- 界面以及功能实现
前言
本篇文章主要讲java的GUI技术搭建页面和java的时间驱动来监听操作,jsoup分析网页数据,以及用到fastjson来进行json数据交互。
项目结构如下:
效果图:
文章很长,虚耐心阅读。
1.首先搭建界面
**
* @Author: lideng_sinosoft
* @Date: 2020/10/6 16:40
* @Description: 主窗体
*/
@SuppressWarnings("all")
public class Main extends JFrame implements ActionListener {
//应用,取消,退出等按钮
private JButton apply,cancel,exit;
//顶部和底部标签
private JLabel top,buttom;
//类别,清晰度,时间间隔,页面等选择框
private JComboBox type,standardOrHd,timer,pager;
//统一字体
private Font font = new Font("宋体",Font.BOLD,16);
//当前页
private int currentPage = 1;
//总页数
private int totalPage = 0;
//创建定时器
Timer timerTask = new Timer();
public static void main(String[] args) {
//main方法用来启动整个程序
new Main();
}
/**
这个方法主要是用来启动加载页面一些数据的
*/
public void init(){
String typeValue = (String) type.getSelectedItem();
String hdSelectedItem = (String) standardOrHd.getSelectedItem();
JSONArray types = JsonUtil.getTypes();
for(Object object :types){
JSONObject jsonObject = (JSONObject) object;
if (typeValue.equals(jsonObject.getString(Contant.NAME))){
String url = jsonObject.getString(Contant.URL);
String hd = ENUM_PAGE_TYPE.HD.getName().equals(hdSelectedItem) ? ENUM_PAGE_TYPE.HD.getValue() : ENUM_PAGE_TYPE.STANDARD.getValue();
Map<String, String> apply = DownWallPagerUtil.apply(url, hd);
totalPage = Integer.valueOf(apply.get(Contant.TOTAL_PAGE));
currentPage = Integer.valueOf(apply.get(Contant.CURRENT_PAGE));
buttom.setText("共"+totalPage+"页,当前页码:第 "+ currentPage +" 页");
}
}
}
/**在构造方法里面创建组件*/
public Main() {
//布局
this.setLayout(null);
top = new JLabel("<html><a href='http://www.netbian.com'>官网:http://www.netbian.com</a></html>");
top.setFont(font);
top.setSize(300,30);
top.setLocation(100,10);
top.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
//浏览器打开地址
Runtime.getRuntime().exec("cmd.exe /c start " + "http://www.netbian.com");
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void mouseEntered(MouseEvent e) {
//鼠标移入变手形状
top.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); }
});
buttom = new JLabel("共"+totalPage+"页,当前页码:第 "+ currentPage +" 页");
buttom.setFont(font);
buttom.setSize(300,30);
buttom.setLocation(120,280);
buttom.setForeground(Color.red);
createJComboBox();
createButton();
init();
createCurrentPage(200);
this.add(top);
this.add(type); this.add(standardOrHd); this.add(timer);
this.add(pager);
this.add(apply);
this.add(cancel); this.add(exit);
this.add(buttom);
//设置图标
String path = Main.class.getResource("icon.jpg").getPath();
// String path = Thread.currentThread().getContextClassLoader().getResource("resources/icon.jpg").getPath();
Image image = Toolkit.getDefaultToolkit().getImage(path);
this.setIconImage(image);
this.setTitle("彼岸桌面");
this.setSize(450,360);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setVisible(true);
//点击关闭窗口的时候退出程序
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
DownWallPagerUtil.delete();
System.exit(-1);
}
});
}
/**
* @Author: lideng_sinosoft
* @Description:创建下拉选项
* @Date: 2020/10/6
*/
private void createJComboBox(){
JSONArray types = JsonUtil.getTypes();
Vector<String> names = new Vector<>();
for (Object obj: types) {
JSONObject object = (JSONObject) obj;
names.add(object.getString(Contant.NAME));
}
type = new JComboBox(names);
type.setSize(100,30);
type.setLocation(80,60);
type.setFont(font);
standardOrHd = new JComboBox(ENUM_PAGE_TYPE.getNames());
standardOrHd.setSize(100,30);
standardOrHd.setLocation(80,120);
standardOrHd.setFont(font);
JSONArray times = JsonUtil.getTimes();
Vector<String> vector = new Vector<>();
for (Object object:times){
JSONObject jsonObject = (JSONObject) object;
vector.add(jsonObject.getString(Contant.NAME));
}
timer = new JComboBox(vector);
timer.setSize(100,30);
timer.setLocation(80,180);
timer.setFont(font);
}
/**
* @Author: lideng_sinosoft
* @Description:监听
* @Date: 2020/10/6
*/
@Override
public void actionPerformed(ActionEvent e) {
//退出
if (e.getSource() == exit){
timerTask.cancel();
DownWallPagerUtil.delete();
System.exit(-1);
}
//取消
if (e.getSource() == cancel){
timerTask.cancel();
}
//应用
if (e.getSource() == apply){
DownWallPagerUtil.delete();
String typeItem = (String) type.getSelectedItem();
String standard = (String) standardOrHd.getSelectedItem();
String timerItem= (String) timer.getSelectedItem();
String pageItem = pager.getSelectedItem()+"";
if (Integer.valueOf(pageItem)>totalPage){
JOptionPane.showMessageDialog(null, "" +
"您选的页数超出了总页数 ", "错误提示 ", JOptionPane.ERROR_MESSAGE);
}
String url = "";
String stand = "";
Integer time = null;
JSONArray types = JsonUtil.getTypes();
JSONArray times = JsonUtil.getTimes();
for (Object object:types){
JSONObject jsonObject = (JSONObject) object;
if (typeItem.equals(jsonObject.getString(Contant.NAME))){
url = jsonObject.getString(Contant.URL);
}
}
for (Object object:times){
JSONObject jsonObject = (JSONObject) object;
if (timerItem.equals(jsonObject.getString(Contant.NAME))){
time = getTime(jsonObject.getString(Contant.VALUE));
}
}
Vector<String> names = ENUM_PAGE_TYPE.getNames();
for(String name :names){
if (standard.equals(name)){
stand = ENUM_PAGE_TYPE.STANDARD.getValue();
break;
}else{
stand = ENUM_PAGE_TYPE.HD.getValue();
break;
}
}
check(url,stand,time);
Map<String, String> apply = DownWallPagerUtil.apply(url, stand, time, pageItem, timerTask);
totalPage = Integer.parseInt(apply.get(Contant.TOTAL_PAGE));
currentPage = Integer.parseInt(apply.get(Contant.CURRENT_PAGE));
buttom .setText("共"+totalPage+"页,当前页码:第 "+ currentPage +" 页");
if (null !=apply){
JOptionPane.showMessageDialog(null, "应用成功");
}else{
JOptionPane.showMessageDialog(null, "应用失败 ", "错误提示 ", JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* @Author: lideng_sinosoft
* @Description:时间计算
* @Date: 2020/10/7
* @Param [resource]
* @return java.lang.Integer
*/
private Integer getTime(String resource){
int sum = 1;
String[] split = resource.split("-");
for (int i =0; i <split.length;i++){
sum *= Integer.valueOf(split[i]);
}
return sum;
}
/**
* @Author: lideng_sinosoft
* @Description: 入参校验
* @Date: 2020/10/7
*/
private void check(Object... objects){
for (Object object : objects){
if (object instanceof String){
String value = (String) object;
if (null == value || "".equals(value)){
JOptionPane.showMessageDialog(null, "参数为空,请重试! ", "错误提示 ", JOptionPane.ERROR_MESSAGE);
}
}
if (object instanceof Integer){
Integer value = (Integer) object;
if (1 == value || null == value){
JOptionPane.showMessageDialog(null, "参数为空,请重试! ", "错误提示 ", JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
2.下载壁纸
/**
* @Author: lideng_sinosoft
* @Date: 2020/10/6 15:56
* @Description: 下载图片公用方法
*/
public class DownWallPagerUtil {
public static Map<String, String> apply(final String url, final String definition, Integer time, String page, Timer timer) {
Map<String, String> result = new HashMap<>();
try {
if (ENUM_PAGE_TYPE.HD.getValue().equals(definition)){
result = imgHD(url, page);
} else {
result = standard(url,page);
}
ApplyDeskWall.applyDesk(time,timer);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* @Author: lideng_sinosoft
* @Description: 获取高清图片的方法
* @Date: 2020/10/6
* @Param
* @return
*/
public static Map<String,String> imgHD(String url,String page) throws Exception {
Map<String,String> pageMap = new HashMap<>();
Connection connect = "1".equals(page) ? Jsoup.connect(url) : Jsoup.connect(url+"index_"+page+".htm");
Document document = connect.get();
Elements list = document.getElementsByClass("list");
for(Element element :list){
Elements imgs = element.getElementsByTag("a");
for (Element img :imgs){
String href = img.attr("href");
if (href.contains("http")){
continue;
}
Connection hdImg = Jsoup.connect(Contant.URL_HD+href);
Elements pics = hdImg.get().getElementsByClass("pic");
for (Element pic : pics){
Elements bigImgs = pic.getElementsByTag("img");
for (Element bigImg : bigImgs){
String src = bigImg.attr("src");
String endWith = src.substring(src.lastIndexOf("."));
String fileName = UUID.randomUUID().toString();
download(src,endWith,fileName);
}
}
}
}
Elements elements = document.getElementsByClass("page");
String currentPage = "1";
String totalPage = "1";
for(Element element : elements){
Elements element1 = element.getElementsByTag("b");
if (element1.size() == 0){
continue;
}
currentPage = element1.get(0).getElementsByTag("b").get(0).text();
totalPage = element.getElementsByTag("a").get(element.getElementsByTag("a").size() - 2).text();
}
pageMap.put(Contant.CURRENT_PAGE,currentPage);
pageMap.put(Contant.TOTAL_PAGE,totalPage);
return pageMap;
}
/**
* @Author: lideng_sinosoft
* @Description: 获取标清图片的方法
* @Date: 2020/10/6
*/
public static Map<String,String> standard(String url,String page) throws Exception{
Map<String,String> pageMap = new HashMap<>();
Connection connect = "1".equals(page) ? Jsoup.connect(url) : Jsoup.connect(url+"index_"+page+".htm");
Document document = connect.get();
Elements list = document.getElementsByClass("list");
for(Element element : list){
Elements img = element.getElementsByTag("img");
for (Element imgs : img){
String src = imgs.attr("src");
String endWith = src.substring(src.lastIndexOf("."));
String fileName = UUID.randomUUID().toString();
download(src,endWith,fileName);
}
}
Elements elements = document.getElementsByClass("page");
String currentPage = "1";
String totalPage = "1";
for(Element element : elements){
Elements element1 = element.getElementsByTag("b");
if (element1.size()==0){
continue;
}
currentPage = element1.get(0).getElementsByTag("b").get(0).text();
totalPage = element.getElementsByTag("a").get(element.getElementsByTag("a").size() - 2).text();
}
pageMap.put(Contant.CURRENT_PAGE,currentPage);
pageMap.put(Contant.TOTAL_PAGE,totalPage);
return pageMap;
}
/**
* 下载图片
* @param url
*/
public static void download(String url,String endWith,String fileName) throws Exception{
File file = new File(Contant.PATH);
if (!file.exists()){
file.mkdir();
}
URL url2 = new URL(url);
InputStream is = url2.openConnection().getInputStream();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file.getPath()+File.separator+fileName+endWith));
byte[] bs = new byte[2048*2048];
int len = 0;
while((len = is.read(bs,0,bs.length))!=-1){
bos.write(bs,0,len);
bos.flush();
}
if(is != null) is.close();
if(bos != null) bos.close();
}
/**
* 删除文件
* @return
*/
public static boolean delete (){
try{
File sourceFile = new File("d:/img/");
if (!sourceFile.exists()){
sourceFile.mkdir();
}else{
if(sourceFile.isDirectory()){
for (File listFile : sourceFile.listFiles()) {
listFile.delete();
}
}
return sourceFile.delete();
}
}catch(Exception e){
e.printStackTrace();
}
return false;
}
3.设置桌面壁纸
**
* @Author: lideng_sinosoft
* @Date: 2020/10/7 20:04
* @Description: 设置桌面壁纸
*/
@SuppressWarnings("all")
public class ApplyDeskWall {
public static void applyDesk(Integer time,Timer timer) throws Exception {
File file = new File(Contant.PATH);
String[] list = file.list();
final List<String> pathList = new ArrayList<String>();
for (String path:
list) {
String pathImg =file.getPath()+File.separator+path;
pathList.add(path);
}
timer.scheduleAtFixedRate(new TimerTask() {
int index = 0;
@Override
public void run() {
int SPI_SETDESKWALLPAPER = 0x14;
int SPIF_UPDATEINIFILE = 0x01;
int SPIF_SENDWININICHANGE = 0x02;
//设置桌面背景
boolean result = MyUser32.INSTANCE.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0,
file.getPath()+File.separator+pathList.get(index), SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE );
index++;
if (index >= pathList.size()){
index = 0;
}
}
},0,time);
}
private interface MyUser32 extends StdCallLibrary {
MyUser32 INSTANCE = (MyUser32) Native.loadLibrary("user32", MyUser32.class);
boolean SystemParametersInfoA(int uiAction, int uiParam, String fnm, int fWinIni);
}
}
写作不易,麻烦点个赞,谢谢。如果要继续开发迭代的话,可以私聊我,我把代码发给你哦。