Java|窗口刷新、图片自动播放问题

之前窗口刷新图片时出现了一点小问题,基本状况是:打开图片后要运用方法setBackGround()加上循环实现图片自动播放的功能,但是图片一直没有刷新,一直停在第一张图片,但是在我发了论坛之后一直没有得到满意的回复。后来我在书上找到了解决方法,根据书上的解决方法成功解决了上述的问题,现在将我解决的方法分享给大家。
在这里插入图片描述
之前的问题大概就是上面这样,为了便于分析问题,我将不同的功能代码写成了几个子程序,但是依旧没有找到问题的关键点。后来我在书上看到说要把绘图的代码单独写到一个线程里去,我根据书里的指示,将画图刷新相关的操作放在了一个线程里面,的确达到了我想要的目的,代码大概如下:

public static void setBackGround(String fileName) {			//刷新窗口后放图片
		if(ImageLabel!=null) {
			win1.remove(photoPane);
		}
		picture = fileName;
		if(!picture.equals(photoName[locality])) {
			findLocal();
		}
		setPhoto(fileName);
		setButton();
		
		win1.invalidate();
		win1.repaint();
		win1.setVisible(true);
	}
	
	public static void setPhoto(String fileName) {				//放图片
		img = downSizeImage.thumbnailImage(fileName, 800, 600, false);
		ImageLabel = new JLabel(img);
		photoPane = new MyPanel();
		photoPane.setLayout(new FlowLayout(FlowLayout.CENTER));
		photoPane.add(ImageLabel);
		win1.setLayout(new BorderLayout());
		win1.add(photoPane,BorderLayout.CENTER);
	}
	
	public static void setButton() {						//设置第一窗口放映图片时的按钮
		buttonPane = new JPanel();
		buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER));
		JButton last,next,auto;
		last = new JButton("<");
		next = new JButton(">");
		auto = new JButton("|>");
		ButtonListener listener = new ButtonListener();
		last.addActionListener(listener);
		next.addActionListener(listener);
		auto.addActionListener(listener);
		buttonPane.add(last);
		buttonPane.add(auto);
		buttonPane.add(next);
		win1.add(buttonPane, BorderLayout.SOUTH);
	}
	
	public static void findLocal() {					//找到当前播放图片在数组中的位置
		for(int i=0; i<photoName.length; i++) {
			if(picture.equals(photoName[i])) {
				locality = i;
				break;
			}
		}
	}
	public static class MyThread extends Thread{		//自动播放线程
		public void run() {
			for(int i=0; i<photoName.length; i++) {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				nextOne();
			}
		}
	}
	public static void nextOne() {					//下一张图片
		locality++;
		if(locality>=photoName.length) {
			locality = 0;
		}
		setBackGround(photoName[locality]);
	}

希望我的一点小经验可以帮到跟我之前一样陷入困境的小伙伴

猜你喜欢

转载自blog.csdn.net/marwi_study/article/details/88727314