2014-11-08 2 views
0

내 버튼에이 void 메소드를 호출하는 방법에 대한 도움이 정말로 필요합니다. 요점은 요구 사항에 따라 메소드를 무효화해야한다는 것입니다. 그럼, 방법 및 당신이 (이 콘솔에 직접 인쇄 때문에 이상한 요구 사항) 그대로 printIntBinary 방법을 유지하기 위해 강제하는 경우 내가 방법을GUI 단추에서 void 메서드를 호출하는 방법은 무엇입니까?

public static void printIntBinary(int x) { 
    if (x <= 0) { 
    } else { 
     // System.out.println(x % 2) 
     printIntBinary(x/2); 
     System.out.println(x % 2); 
    } 
} 

//Portion of my Gui.. runButton actionListner 
runButton.addMouseListener(new MouseAdapter() { 
    public void mouseClicked(MouseEvent e) { 

     try{ 
      int mm = Integer.parseInt(binaryTextField.getText()); 
      //I'm having problem down here.. Because my method printInBinary is void type 
      binaryOutPut.append(Recurs.printIntBinary(mm)); 
     } catch(IllegalArgumentException ex){ 
      JOptionPane.showMessageDialog(null, "ertyui"); 
     } 
+1

메소드'binaryOutPut.append (...)'는 매개 변수를 취하고 아무 것도 반환하지 않는'Recurs.printIntbinary (mm)'메소드를 호출하므로'void'를 매개 변수로 넣을 수 있습니다 , 작동하지 않습니다. – CoderMusgrove

+0

당신은 무엇을 제안합니까? – Semm

+2

버튼이있는'MouseListener'를 사용하지 말고,'ActionListener'를 사용하십시오. [버튼, 체크 박스, 라디오 버튼 사용법] (http://docs.oracle.com/javase/tutorial/uiswing/components/) button.html) 자세한 내용은 – MadProgrammer

답변

0

전화를 시도하고있는 버튼을 당신은 그 방법의 결과를 잡기 위해 일시적으로 System.out 스트림을 리디렉션 할 수 있습니다 :

public void mouseClicked(MouseEvent e) { 
    try{ 
     int mm = Integer.parseInt(binaryTextField.getText()); 

     // create temporary outputstream and set it to System.out 
     final OutputStream originalOS = System.out; 
     final ByteArrayOutputStream os = new ByteArrayOutputStream(); 
     final PrintStream ps = new PrintStream(os); 
     System.setOut(ps); 

     Recurs.printIntBinary(mm); 
     binaryOutPut.append(os.toString()); 

     //reset System.out 
     System.setOut(originalOS); 
    } catch(IllegalArgumentException ex){ 
     JOptionPane.showMessageDialog(null, "ertyui"); 
    } 
} 

이 그 요구 사항에 대한 더러운 해결 방법입니다.

당신이 공백 (e.q. \r\n)를 방지하기 위해 연결하면

os.toString().replaceAll("\\s", "")os.toString()을 변경, 텍스트 영역에 추가 할 수 있습니다. 당신이 (그것의 반환 타입 제외) 방법 printIntBinary을 변경할 수있는 경우

는, 당신은 다음과 같은 작업을 수행 할 수

public static void printIntBinary(int x, JTextArea binaryOutPut) { 
    if (x > 0) { 
     printIntBinary(x/2); 
     binaryOutPut.append(String.valueOf(x % 2)); 
    } 
} 

당신이 한 줄에 각 숫자를 좋아하는 경우에

binaryOutPut.append(String.valueOf(x % 2) + System.getProperty("line.separator"));를 사용합니다.

관련 문제