최근 포토로그


[JAVA] ProgressBar 쉽게 구현하기.(ProgressMonitorInputStream 와 Scanner 를 이용) App Programming

막히거나 모르는 사항에 대해서는 아래 메일로 문의주세요.
tobby48@naver.com


한글 사이트에서는 사용법이 없어서 구글 및 api 을 삽질했다.


ProgressMonitorInputStream 는 우리가 JAVA에서 힘들게 JProgressBar 클래스를 만들어서 스레드로 돌리는 골치아픈 문제를 jdk 내부에서 자동으로 구현해 주는 클래스이다.

먼저 중요한 부분은 ProgressMonitorInputStream 와 Scanner 클래스 객체를 정의하는 것이다. 나머지는 아래 코드의 빨간색 부분만 참고하면 쉽게 구현할 수 있다.

ProgressMonitorInputStream 의 마지막 생성자 파라미터로 InputStream 객체를 넣어줘야한다.
그러면 자동으로 InputStream 객체를 추적하여 프로그레스바를 생성하게 된다.

보통의 스레드 메소드처럼 public void run() 아래에 프로그레스바가 추적할 실행코드를 넣고,
EventQueue.invokeLater(new Runnable() {
                        public void run() {}
}
이 부분에 실행코드가 끝난 뒤에 실행할 코드를 넣어준다.



아래코드는 회사에서 파싱을 위해 간단히 코딩해본 코드로써, gz파일을 추적하는 프로그레스바를 생성하는 코드이다.
빨간색 부분을 유념해서 보시면 된다.

Runnable readRunnable = new Runnable() {
                String jobResult = new String();

                public void run() {

                    while (iterator.hasNext()) {
                        UposList uposList = iterator.next();
                        final String fileName = uposList.getFilePath();

                        FileInputStream fileIn = null;
                        try {
                            fileIn = new FileInputStream(fileName);
                        } catch (FileNotFoundException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                        ProgressMonitorInputStream progressIn = new ProgressMonitorInputStream(
                                null, "Analysis " + fileName, fileIn);

                        GZIPInputStream zis = null;
                        try {
                            zis = new GZIPInputStream(progressIn);
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                        final Scanner in = new Scanner(zis);
                        try {
                            /*  여기에 Scanner 객체에 의해 ProgressBar가 추적하게 되는 코드를 넣어준다. */
                            jobResult += uposList.uposAddFromFile(new File(
                                    fileName), in, keyValue, startValue,
                                    endValue, gainPropertyValue);
                            in.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    // set content pane in the event dispatch thread
                    EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            uposPane.getJtextArea().setText("");
                            uposPane.getJtextArea().append(jobResult);
                            uposPane.getJtextArea().validate();
                        }
                    });
                }
            };




uposList.uposAddFromFile(new File(fileName), in, keyValue, startValue, endValue, gainPropertyValue)
이 함수의 내용은

        StringBuffer jobResult = new StringBuffer();
        jobResult.append("TC : " + getTcNumber() + "\n");
        boolean establish = false;
       
        while (in.hasNextLine()) {
           
            String data = in.nextLine();
           
            if(data.length()<15)
                continue;
           
            String uposNumber = getUposNumber(data);

            if(uposNumber == null){
                continue;
            }

            /* 한 라인씩 읽어온다. 읽어오게 되면, ProgressBar는 전체 라인수에 대해서 %를 표시하게 된다. */
            data = in.nextLine();
            StringBuffer sb = new StringBuffer();
            boolean stat = false;
           
            while((!data.equals(""))&&(data!=null)){
                sb.append(data + "\n");
               
                String key[] = getUposPerperty(data);
                if(key[0].equals(keyValue)){
                    if((Integer.parseInt(key[1]) >= startValue) &&
                            (Integer.parseInt(key[1]) <= endValue)){
                        stat = true;

                    }
                }
                if((!establish) && key[0].equals("establishmentCause")){
                    if(gainPropertyValue.contains("establishmentCause")){
                        jobResult.append("establishmentCause : " + key[1] + "\n");
                        establish = true;
                    }
                }
                data = in.nextLine();
            }
           
            if(stat){
                String[] splitPropertyList = sb.toString().split("\n");
               
                for(int i=0; i<splitPropertyList.length; i++){
                    String value[] = getUposPerperty(splitPropertyList[i]);
                    if(!gainPropertyValue.isEmpty()){
                        Object gainValue[] = gainPropertyValue.toArray();
       
                        for(int j=0; j<gainValue.length; j++){
                            if(value[0].equals((String)gainValue[j]))
                                jobResult.append(value[0] + " : " + value[1] + "\n");
                        }
                    }else
                        jobResult.append(value[0] + " : " + value[1] + "\n");
                }
            }
        }
       
        return jobResult.toString();
    }


출처 : 내 손

덧글

댓글 입력 영역