자바

반응형

깜빡 하면서 실행되지 않는다

최신 버전의 이클립스를 사용하다가 플러그인이 지원을 하지 않아 구 버전(Neon) 이클립스를 받아서 실행하였다

그런데 실행이 되지 않는다. 또 한참을 삽질을 했다.

이 현상을 해결하기 위해 구글링을 해보면 eclipse.ini 파일 수정하라는 얘기가 제일 많이 나온다

-vm 에 자바 경로를 추가해라..

java.se.ee 였나 이거 추가해라.. 등등이 있는데 전혀 해결되지 않았다

결론은 자바 버전이 문제였다

자바를 11.0.2 최신 버전을 설치했었는데 이게 이클립스 구버전에서 지원이 안되는 것이었나보다.

자바를 지우고 구버전 JDK 1.8.0을 설치하였따

그랬더니 단번에 해결..

오늘도 역시나 최신 업데이트는 함부로 하는게 아니라는 진리를 깨달았다..

반응형
반응형

String 배열을 사용해서 콤보박스에 값들을 보여줬었는데

ArrayList를 사용해서 콤보박스에 보여주고 싶었따.

스트링 배열은 String[] account1 = { id,id1,id2}

이런식으로 콤마로 이루어진 값이었는데 ArrayList는 배열마다 각 값을 가지고 있기 때문에 나중에 관리하기 편할 것 같았다.

기존 String 배열(account1)을 콤보박스에 넣었을 때 코드

JComboBox<?> comboBox = new JComboBox<Object>(account1);

ArrayList(account1)를 콤보박스에 넣을 때 코드

JComboBox<?> comboBox = new JComboBox(account1.toArray(new String[account1.size()]));

이렇게 하면 account1 배열의 사이즈만큼 알아서 콤보박스에 값이 노출되었다

반응형
반응형




셀레니움으로 자동화를 하다보면 작업관리자에 chromedriver.exe가 수두룩하게 누적되어 있는 걸 볼 수 있다


이게 쌓이다보면 메모리를 상당히 잡아먹고 있는데 그래서 자동화가 한번 끝나면 프로세스를 종료하도록 하였다.

셀레니움에서 프로레스를 죽이는 기능이 있다고 하는데 이제 사용하지 않는 기능이라고 문서에 나와있었다




그렇다면 다른 방법으로 메소드를 다시 만들었을 것 같은데 아직 찾지 못했고 일단 급한대로 프로세스 죽이는 코드를 적용했다.



python 파이썬

- cmd에서 pip install psutil 로 설치 필수
1
2
3
4
5
6
7
import psutil 
 
for proc in psutil.process_iter():
    # check whether the process name matches
    if proc.name() == PROCNAME:
        proc.kill()
 
cs



java 자바에서 사용


1
Runtime.getRuntime().exec("taskkill /F /IM chromedriver.exe /T");
cs



자동화 코드 이후에 추가해주면 chromedriver.exe가 없어지는 걸 볼 수 있었다.

반응형
반응형

참고링크


http://blog.naver.com/battledocho/220035925900

반응형
반응형

subString 함수사용

subString(시작위치,끝위치);

예를 들어 애국가에서 

하느님이 ~ 우리나라만세 사이에 텍스트를 추출하고 싶다면

String song = "하느님이 보우하사 우리나라만세";

int start = song.indexOf("하느님이"); //하느님이 위치 추출

int end = song.indexOf("우리나라만세"); //우리나라만세 추출

String parseText = song.subString(start,end);

이런 방법도 있다



반응형
반응형




버거킹 영수증을 받아보면 하단에 설문조사코드가 있습니다.


설문을 마치면 단품으로 세트를 먹을 수 있는 코드를 발급받게 되는데요


설문조사를 하는 것도 은근히 시간이 걸리는 것 같아 한번 시도해보았습니다.


Selenium 을 사용하였고 스윙으로 UI를 대충 만들어보았습니다.


설문이 끝나면 발급코드가 표시되는 간단한 프로그램입니다.


자바 환경 설치가 필수로 되어 있어야 하며


C: 또는 D: 드라이브 경로에 

chromedriver.exe가 존재해야 합니다.


chromedriver.exe






시연 영상



http://youtu.be/NtjBOtUwknM



셀레니움 부분 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package com.burger.king;
 
import java.io.File;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
 
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import static com.codeborne.selenide.Selenide.*;
import static com.codeborne.selenide.Condition.*;
 
@FixMethodOrder (MethodSorters.NAME_ASCENDING)
 
public class survey {
    private static WebDriver driver;
    
    static String receiptNum="";
    static String url="https://kor.tellburgerking.com";
    
    
    public void inputNumber(String number){
          // 텍스트 필드값 가져오기
        receiptNum = number;
    }
 
 
    @BeforeClass
    public static void setUp() throws Exception {
        
        File file = new File("c:/chromedriver.exe");
        File file2 = new File("d:/chromedriver.exe");
           if(file.isFile()){         
               System.setProperty("webdriver.chrome.driver""c:/chromedriver.exe"); //크롬 드라이버 파일 경로설정
        }else if(file2.isFile()){
            System.setProperty("webdriver.chrome.driver""d:/chromedriver.exe"); //크롬 드라이버 파일 경로설정    
        }else{
            //안내문
            runner.labelIntroduce.setText("C 또는 D드라이브에 chromedriver가 없습니다.\n");
        }
        driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); //응답시간 5초설정
        driver.get(url); 
        
         driver.manage().window().maximize();
    }
    
    public static void login() throws InterruptedException   {
        boolean boo = true;
        WebElement NextButton = driver.findElement(By.id("NextButton"));
        NextButton.click();   
        
        driver.findElement(By.id("CN1")).sendKeys(receiptNum);  //ID
        Thread.sleep(1000);
        driver.findElement(By.id("NextButton")).click();
        
        
        int i = 0;
        while(boo){
            try{
                
                boolean radioButtonHolder = driver.findElements(By.className("radioButtonHolder")).size() > 0;
                boolean checkboxBranded = driver.findElements(By.className("checkboxBranded")).size() > 0;
                boolean radioBranded = driver.findElements(By.className("radioBranded")).size() > 0;
                boolean checkCode = driver.findElements(By.className("ValCode")).size() > 0;
                boolean Next = driver.findElements(By.id("NextButton")).size() > 0;
                 if(radioButtonHolder){
                     driver.findElement(By.className("radioButtonHolder")).click();
                 }
                 else if(checkboxBranded){
                     driver.findElement(By.className("checkboxBranded")).click();
                 }
                 else if(radioBranded){
                     driver.findElement(By.className("radioBranded")).click();
                 }
                 if(Next)
                     driver.findElement(By.id("NextButton")).click();
                 if(checkCode)
                     boo = false;
                 System.out.println(i++);
            }catch (NoSuchElementException e){
                
            }
           
        }
        
        String checkCode = driver.findElement(By.xpath("//*[@id='FNSfinishText']/div/p[2]")).getText();
 
        runner.labelIntroduce.setText(checkCode);
    }
    
 
    @Test
    public static void run() throws Exception {
        login();
        Thread.sleep(500);
    }
 
    @AfterClass
    public static void tearDown() throws Exception {
        driver.quit();
    }
 
}
cs



스윙UI 부분


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package com.burger.king;
 
import javax.swing.*;
 
import com.burger.king.runner;
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
 
class runner extends Thread{
    Simulator simul = new Simulator();
    public static    JLabel labelIntroduce;
    public static survey survey = new survey();
    public  static  JTextField tf_receiptNum;
    public static JLabel submit,number;
    public boolean check = true
    public void run(){
        // 텍스트 필드값 가져오기
        String receiptNum = tf_receiptNum.getText();
        try {
            survey.setUp();
        } catch (Exception e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        survey.inputNumber(receiptNum);
        try {
            survey.run();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
    
}
 
class JPanel033 extends JPanel{        
    runner thread = new runner();
    
    // 클래스 멤버 필드 설정
    private    JLabel name;
    private    JLabel id;
            
    
    private    JButton buttonSave;
    private    JButton buttonStop;
    public boolean check = true
    
    public JPanel033() {         
        
        setLayout(null);
        
        // 라벨
        name = new JLabel("by. yonoo");
        name.setSize(10020);   
        name.setLocation(20);
        
        id = new JLabel("설문조사코드: ");
        id.setBounds(10,30,100,20);
        
        // 텍스트 필드
        runner.tf_receiptNum = new JTextField();             
        runner.tf_receiptNum.setBounds(100,30,200,20);
        
        thread.labelIntroduce = new JLabel("=");
        thread.labelIntroduce.setBounds(10,50,280,20);
       
            
        // 버튼        
        buttonSave = new JButton("시작");
        buttonSave.setBounds(80,80,100,20);
        buttonSave.addActionListener(new EventHandlerSave());   
        
        buttonStop = new JButton("정지");
        buttonStop.setBounds(220,80,100,20);
        buttonStop.addActionListener(new EventHandlerStop());   
        
        add(name);
        add(thread.labelIntroduce);
        
        add(id);
        add(thread.tf_receiptNum);
        
        add(buttonSave);
        add(buttonStop);
        
    }
    
    class EventHandlerSave implements ActionListener{     // 
        public void actionPerformed(ActionEvent e){
//            try {
//                thread.start();    
//            } catch (Exception e1) {
//                // TODO Auto-generated catch block
//                e1.printStackTrace();
//            }
            
            if(check){
                thread.start();    
            }else{
                runner thread = new runner();
                thread.start();    
                check = true;
            }
        }
    }   
    class EventHandlerStop implements ActionListener{     // 
        public void actionPerformed(ActionEvent e){
            check = false;
            System.out.println(check);
            thread.interrupt();
            System.out.println("정지!");
//            System.exit(1);
            
        }
    } 
    
}
 
 
public class Simulator extends JFrame{
    
    public JPanel033 jpanel03 = null;
   
    public static void main(String[] args) {
        Simulator win = new Simulator();
        
        win.setTitle("BurgerKing Survey Automation");
        win.jpanel03 = new JPanel033();
        
        URL imageURL = Simulator.class.getClassLoader().getResource("burger.png");
        System.out.println(imageURL);
        ImageIcon img = new ImageIcon(imageURL);
        win.setIconImage(img.getImage());
        
        win.add(win.jpanel03);
 
        win.setSize(400,150);
        win.setVisible(true);
        win.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        
        
    }
    
}
 
cs

반응형
반응형




자바에서 프로그램을 만든 뒤 프레임바 아이콘을 바꾸고 싶었다.


바로 요놈을 바꿔주고 싶었다.





그래서 프로젝트 내 이미지 파일을 복사한 뒤 아이콘을 변경하기로 했다.




icon 폴더 생성 후 p.png 파일을 넣었다.


그런다음


ImageIcon img = new ImageIcon("icon/p.png");

        win.setIconImage(img.getImage());



이렇게 코드를 넣어주고 실행하면 변경됐으나 


 Runnable JAR 즉 실행가능한 JAR 파일로 생성하여 실행하면 변경되지가 않았다.


왜 jar 파일로만 생성하면 안되는 걸까해서 찾아본 결과 이미지가 있는 폴더도 같이 묶어주어야 했다.




먼저 프로젝트 우클릭 > properties 에 들어간 뒤 Java Build Path 에 들어간다.


Source 탭에서 Add Folder 를 선택한다.






그런다음 이미지가 있는 폴더를 체크해준다.

여기서는 icon 폴더





적용한 다음 저 위치의 경로를 추출하기 위해 다음 코드를 써준다.


1
2
3
4
 URL imageURL = 클래스명.class.getClassLoader().getResource("p.png");
 ImageIcon img = new ImageIcon(imageURL);
 JFrame객체.setIconImage(img.getImage());
 
cs



이렇게 해주면 프레임바 아이콘이 교체된다.

한번 이클립스에서 실행해보고 적용됐는지 확인해본다.





적용한 다음 프로젝트 우클릭 > Export > Java > Runnable JAR file 선택













Launch configuration 에서 실행될 클래스 지정해주고


Library Handling 에서 두번째 선택한 뒤 finish 해준다.


이유는 모르겠으나 두번째로 해야 적용이 되었다.








그리고 생성된 jar 파일을 실행해보고 아이콘이 바뀌었나 확인해본다.


그럼 어느 컴퓨터를 가도 아이콘은 적용되어 있을 것이다.














반응형
반응형

ImageIcon img = new ImageIcon("이미지경로");

해당프레임.setIconImage(img.getImage());

반응형

+ Recent posts