实现进度条
最近碰到一个问题,需要在子线程中导数据,但数据的总量不是很清楚,针对此情况,做一个来回滚动的进度条,另外,进度条一直在屏幕中间,会影响其它操作,也顺带做了一个拖拽功能,以备后用。
public class ProgressBar extends MouseAdapter{
JFrame frame=null;
JProgressBar progressbar;
JTextField txtCaption;
boolean isDragged;
Point loc;
Point tmp;
/**
*
* @param m_Caption
*/
public ProgressBar(String m_Caption){
InitProgress(m_Caption);
}
private void InitProgress(String m_Caption){
frame=new JFrame(m_Caption);
frame.setSize(350, 50);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
frame.setLocation((screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2);
Container contentPanel=frame.getContentPane();
progressbar = new JProgressBar();
progressbar.setOrientation(JProgressBar.HORIZONTAL);
progressbar.setIndeterminate(true);
progressbar.setBackground(Color.WHITE);
progressbar.setForeground(new Color(0,0,192));
progressbar.addMouseListener((MouseListener) this);
progressbar.addMouseMotionListener((MouseMotionListener) this);
txtCaption=new JTextField(m_Caption);
txtCaption.setBackground(Color.WHITE);
txtCaption.setForeground(Color.BLUE);
txtCaption.setEditable(false);
txtCaption.addMouseListener((MouseListener) this);
txtCaption.addMouseMotionListener((MouseMotionListener) this);
contentPanel.add(txtCaption,BorderLayout.NORTH);
contentPanel.add(progressbar,BorderLayout.CENTER);
frame.setUndecorated(true);
}
/**
* 进度条开始记录数据导入进度。
*/
public void begin(){
frame.setVisible(true);
}
/**
* 数据导入结束,关闭进度条。
*/
public void end(){
frame.dispose();
}
/**
* 内部使用方法。
*/
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
isDragged=true;
tmp=new Point(e.getX(),e.getY());
frame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
System.out.println("Press");
}
/**
* 内部使用方法。
*/
public void mouseReleased(MouseEvent e) {
isDragged=false;
loc=new Point(frame.getLocation().x+e.getX()-tmp.x,frame.getLocation().y + e.getY() - tmp.y);
frame.setLocation(loc);
frame.setCursor(new Cursor(Cursor.MOVE_CURSOR));
System.out.println("Release");
}
/**
* 内部使用方法。
*/
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
if(isDragged){
loc=new Point(frame.getLocation().x+e.getX()-tmp.x,frame.getLocation().y + e.getY() - tmp.y);
frame.setLocation(loc);
}
System.out.println("drag");
}
}