2013-05-09 2 views
0

현재 내 GUI에 코드를 연결하려고합니다. 내 코드를 위반하지 않고 ActionListener에서 텍스트를 호출 할 수있는 방법을 찾을 수 없습니다. findAndReplace()에 몇 가지 사항이 있습니다. 내 GUI에서 작동하도록 노력해야합니다 ...하지만 지금은 ActionListener를 설명하려고합니다.ActionListener 내에서 호출

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.Collections; 

import javax.swing.*; 



public class HangmanPanel extends JPanel { 
    static Boolean FOUND; 
    private static final long serialVersionUID = -5793357804828609325L; 

    public static String answerKey() { 
     //get random array element 
     String array[] = new String[10]; 
     array[0] = "hamlet"; 
     array[1] = "mysts of avalon"; 
     array[2] = "the iliad"; 
     array[3] = "tales from edger allan poe"; 
     array[4] = "the children of hurin"; 
     array[5] = "the red badge of courage"; 
     array[6] = "of mice and men"; 
     array[7] = "utopia"; 
     array[8] = "chariots of the gods"; 
     array[9] = "a brief history of time"; 

     ArrayList<String> list = new ArrayList<String>(Arrays.asList(array)); 
     Collections.shuffle(list); 
     String s = list.get(0); 
     return s; 
    } 

    public StringBuilder dashReplace(String s) { 
     //replace non-white space char with dashes and creates StringBuilder Object 
     String tW = s.replaceAll("\\S", "-"); 
     System.out.print(tW + "\n"); 
     StringBuilder AnswerKey = new StringBuilder(tW); 
     return AnswerKey; 
    } 





    public HangmanPanel(){ 
     this.setLayout(null); 

     JLabel heading = new JLabel("Welcome to the Hangman App"); 
     JButton Button = new JButton("Ok"); 
     //get input 
     Button.addActionListener(new input()); 

     JLabel tfLable = new JLabel("Please Enter a Letter:"); 


     JLabel AnswerKey = new JLabel(dashReplace(answerKey()).toString()); 

     JTextField text = new JTextField(10); 


     heading.setSize(200, 50); 
     tfLable.setSize(150, 50); 
     text.setSize(50, 30); 
     Button.setSize(60, 20); 
     AnswerKey.setSize(200, 100); 

     heading.setLocation(300, 10); 
     tfLable.setLocation(50, 40); 
     text.setLocation(50, 80); 
     Button.setLocation(100, 85); 
     AnswerKey.setLocation(100,85); 

     this.add(heading); 
     this.add(tfLable); 
     this.add(text); 
     this.add(Button); 
     this.add(AnswerKey); 
    } 
    public class input implements ActionListener{ 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      // can't access text 
      sc = text.getText(); 
      char ch = sc.charAt(0); 
      findAndReplace(s, AnswerKey, input, ch); 
     } 


    } 
    public static int findAndReplace(String s, StringBuilder AnswerKey, String sc, 
      char ch) { 
     //find position of user input and replace 
     int pos = -1; 
     FOUND = false; 
     while(true){ 
     pos = s.indexOf(sc, pos+1); 
     if(pos < 0){ 

      break; 
     }else{ 
      FOUND = true; 
      AnswerKey.setCharAt(pos, ch); 
     } 

     } 
     System.out.println(AnswerKey); 
     return pos; 
    } 

} 
+1

1) 일반적인 학습하십시오 당신은이 같은 이벤트 리스너를 추가하는 익명의 내부 클래스를 사용할 수 있습니다

클래스, 메소드 및 속성 이름에 대한 Java 명명 규칙] (http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#73307) (특히 이름에 사용 된 사례) 일관되게 사용하십시오. 2) Java GUI는 다른 플랫폼 해상도와 다른 PLAF 사용으로 작동해야 할 수도 있습니다. 따라서 구성 요소의 정확한 배치에 도움이되지 않습니다. 견고한 GUI의 경우 대신 레이아웃 관리 또는 레이아웃 조합을 사용하여 레이아웃 패딩 및 공백 테두리를 사용하여 구성 요소를 구성합니다. 3) 한 줄의 공백으로 충분하다. –

답변

1

먼저 소문자 클래스 이름 대문자 변수 이름을 사용하지 않는, 예를 들어

는 코드 읽기가 정말 어렵습니다. 마지막으로

Button.addActionListener(new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     // can't access text 
     sc = text.getText(); 
     char ch = sc.charAt(0); 
     findAndReplace(s, AnswerKey, input, ch); 
    } 
}); 

마크 text 변수 익명의 클래스에 액세스하기 위해 :

final JTextField text = new JTextField(10); 
+0

이 작업은 정상입니다 ...하지만이 메서드 앞에 괄호에 오류가 있습니다 ... – Sage1216

+0

@ Sage1216 : 클래스 필드를 여러 방법으로 텍스트 필드에 액세스해야 할 수도 있으므로 여전히 더 좋을 것입니다. 프로그램. –

+0

어떤 종류의 오류가 있습니까? – hoaz

3

텍스트 JTextField를 변수는 생성자 내부에 선언하고 클래스 "범위"를 가지고 있지 않기 때문에 클래스의 다른 방법에 보이지이다. 이 변수는 클래스 전체에 가시성을 부여하기 위해 생성자가 아니라 클래스에서 선언하여 클래스 필드로 만들어야합니다. 모든

public class HangmanPanel extends JPanel { 
    private static final long serialVersionUID = -5793357804828609325L; 
    private Boolean found; // this should not be static nor capitalized 
    private JTextField text; // declare your class field 

    // .... etc... 

    public HangmanPanel() { 
     this.setLayout(null); // *** don't do this. Use layout managers. 

     // ... etc 

     // JTextField text = new JTextField(10); 
     text = new JTextField(10);