2017-11-04 19 views
0

저는 Java를 처음 접했고 사용자가 서적, 교과서 또는 워크 북을 추가 할 수있는 서점의 기본 표현이라고 생각되는 항목을 작업하고 있습니다. 서점 (arraylist). 이 GUI를 사용해야하며 허용되는 유일한 요소는 JTextArea 및 JTextField입니다. 내 문제는 actionlistener에서 텍스트 필드의 초기 입력은 사용자가 아무 것도 넣지 않아도 나머지 프롬프트에 대한 입력이됩니다.이 문제를 해결할 수있는 방법이 있습니까? 다음은 내 코드 스 니펫입니다.하나의 JTextField 자바에서 입력을 차례로 가져 오는 것

public static void main(String[] args){ 

    BookStore b = new BookStore(); 
    b.setVisible(true); 

} 
String input; 
public BookStore() { 

    super("Bookstore"); 
    setSize(800, 500); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setLayout(new GridLayout(1, 2)); 

    textField = new JTextField(25); 
    panel = new JPanel(); 
    textField.addActionListener(new ActionListener(){ 
     @Override 
     public void actionPerformed(ActionEvent ae) { 
      /* 
       The majority of your code should be written here. 
       Note that this scope has access to the fields textField 
       and textArea. 
      */ 
      //input = textField.getText(); 

      if(Integer.parseInt(textField.getText()) == 1) { 
       bookSubMenu(); 
       textField.setText(null); 
       input = textField.getText(); //this just uses the input already present in the JTextField; how can i fix that 
       if(Integer.parseInt(input) == 1) { 
        textArea.append("Enter the title of the book: "); 
        tempTitle = textField.getText();//This also uses the input from the original getText() without allowing any input to be entered 
        textArea.append(tempTitle); 
        ret = addBook(BT_BOOK, tempTitle); 
       } 
       //getBookInfo(); 
       //textField.setText(""); 
      } 
     } 

답변

0

이 키보드 키를 치면 입력 할 때마다 JTextField로 화재에 대한 이벤트의 actionPerformed. 따라서 입력 한 내용을 처리하기 전에 사용자로부터 완전한 입력을 받아들이는 데 이상적입니다. 이를 염두에두고,이 이벤트 내에서 정수로 입력 텍스트를 변환 겠다는 나쁜 생각은 알파 문자열이 확실히 생산하기 때문에 사용자가 정수 수치 값을 입력 실제로 것을 확실히 알고하지 않는

if(Integer.parseInt(textField.getText()) == 1) { ... } 

a 숫자 형식 예외입니다. 설정할 수있는 플래그 또는 정수 메뉴 유형 선택 변수로 부울 변수를 사용하여

input = textField.getText(); 

// If nothing was entered. 
if (input.trim().equals("") || input.isEmpty()) { 
    textField.setText(null); // In case only whitespaces were entered. 
    // Get out of the event. No sense wasting time here. 
    return; 
} 

// Use the String.matches() method with a Regular Expression. 
// The "\\d+" checks to see if everything within the textfield 
// is a string representation of a integer numerical value. 
if (input.matches("\\d+")) { 

    // CODE RELATED TO NUMERICS GOES HERE 
} 
else { 
    // CODE RELATED TO NON-NUMERICS GOES HERE 
} 

(:이 같은 일을하기 전에 당신은 항목, 변환에 아마도이 같은 유효한지 확인해야합니다 더 좋게) TextField 항목이 무엇인지 항상 알 수 있습니다. 다음과 같이 바뀔 수 있습니다.

public void actionPerformed(ActionEvent ae) { 
    input = textField.getText(); 

    // If nothing was entered. 
    if (input.trim().equals("") || input.isEmpty()) { 
     textField.setText(null); // In case only whitespaces were entered. 
     // Get out of the event. No sense wasting time here. 
     return; 
    } 

    // Use the String.matches() method with a Regular Expression. 
    // The "\\d+" checks to see if everything within the textfield 
    // is a string representation of a integer numerical value. 
    if (input.matches("\\d+")) { 
     // The following Integer variable is declared as class global 
     // and initialized to 0 (same place the String variable named 
     // input was declared). 
     menuItem = Integer.parseInt(textField.getText()); 

     // Note: You can use swicth/case for the following... 
     if(menuItem == 1) { 
      // Code goes here if 1 was entered 
      textArea.append("Enter the title of the book: "); 
     } 
     else if(menuItem == 2) { 
      // Code goes here if 2 was entered. 
     } 
     // etc, etc... 
     else { 
      JOptionPane.showMessageDialog(null, "Invalid Menu Entry Provided!", 
           "Invalid Entry", JOptionPane.WARNING_MESSAGE); 
      menuItem = 0; 
     } 
     textField.setText(null); 
    } 

    // Non-Numerical String entered. 
    else { 
     // Process String data here. 
     // Note: You can use swicth/case for the following... 
     if (menuItem == 1) { 
      tempTitle = textField.getText(); 
      textArea.append(tempTitle + System.lineSeparator()); 
      ret = addBook(BT_BOOK, tempTitle); 
     } 
     else if (menuItem == 2) { 
      // If menuItem 2 is currently active. 
     } 
     // etc, etc... 
     else { 
      JOptionPane.showMessageDialog(null, "Invalid Entry Provided!\nUndetermined location for content!", 
           "Invalid Entry", JOptionPane.WARNING_MESSAGE); 
      menuItem = 0; 
     } 
     textField.setText(null); 
    } 
} 

아이디어를 얻을 수 있습니다. 끝내는 것은 당신에게 달려 있습니다.

+0

고맙습니다. 따라서 본질적으로 actionPerformed는 Enter 키를 누른 후에 한 번만 발생합니다. 그런 다음 하나의 actionPerformed 아래에 하위 메뉴 및 하위 하위 메뉴가있는 메뉴를 가질 수 있습니까? –

+0

예 ... ENTER 키를 누를 때마다 이벤트가 한 번 발생합니다. "그러면 하위 메뉴와 하위 메뉴가있는 하위 메뉴를 하나의 actionPerformed 아래에 둘 수 있을까요?"라고 말하면서 무엇을 의미하는지 확신 할 수 없습니다. ENTER 키가 눌 렸을 때 메뉴 시스템을 표시하려고합니까? – DevilsHnd

+0

예. 예를 들어 주 메뉴에서 1을 선택하면 하위 메뉴가 나타나 사용자에게 교과서 또는 통합 문서를 선택하도록 요청합니다. 통합 문서 옵션을 선택하면 제목, 저자, 가격 등과 같이 사용자에게 책의 세부 정보를 묻는 메시지가 차례로 표시됩니다. 텍스트 필드와 텍스트 영역만으로 가능합니까? –

관련 문제