2013-03-24 5 views
0

그래서 사용자 입력을 얻기위한 간단한 대화 상자를 만들었지 만 텍스트 필드는 두 번 표시됩니다. 다음은 SSCCE입니다.JOptionPane.showInputDialog에 텍스트 필드가 두 번 표시됩니다. 왜?

public static void main(String[] args) { 
    JTextField fileName = new JTextField(); 
    Object[] message = {"File name", fileName}; 
    String option = JOptionPane.showInputDialog(null, message, "Add New", JOptionPane.OK_CANCEL_OPTION); 
    System.out.println(fileName.getText()); 
} 

enter image description here

여기에 코드 문제점은 무엇입니까?

답변

4

개체도 message[]에 추가하기 때문에 그렇게하고 있습니다.

Object[] message = {"File name", fileName};//sending filename as message

그래서, 나타내는 제 JTextField이주는 InputDialog에서 고유의 하나이며, 다른 하나는 당신이 메시지로 전송되는 자신의 JTextField입니다.

fileName의 내용을 메시지에 보내고 싶습니다. 이 경우 코드는 다음과 같이해야합니다 :

public static void main(String[] args) { 
    JTextField fileName = new JTextField(); 
    Object[] message = {"File name", fileName.getText()};//send text of filename 
    String option = JOptionPane.showInputDialog(null, message, "Add New", JOptionPane.OK_CANCEL_OPTION); 
    System.out.println(fileName.getText()); 
} 

UPDATE
당신이 다음 메시지로 객체 filename를 보낼 필요가없는 입력을 만합니다. 다음과 같이 진행하면됩니다.

public static void main(String[] args) { 
     //JTextField fileName = new JTextField(); 
     Object[] message = {"File name"}; 
     String option = JOptionPane.showInputDialog(null, message, "Add New", JOptionPane.OK_CANCEL_OPTION); 
     if (option == null) 
     System.out.println("Cancell is clicked.."); 
     else 
     System.out.println(option+ " is entered by user"); 
    } 
+0

사실 저는 사용자로부터 의견을 얻고 싶습니다. 그러나 그것은 설명합니다. –

+0

use로부터의 입력 만 원한다면'filename'을 메시지로 보내지 마라. JOptionPane.inputDialog'는 이것을 자동으로 처리한다. –

+0

그럼 사용자가 확인을 클릭했는지 취소했는지 어떻게 확인합니까? –

2

기본적으로 입력 대화 상자에는 텍스트 필드가 있으므로 다른 필드를 추가 할 필요가 없습니다. 이 방법을 사용해보십시오.

String name = JOptionPane.showInputDialog(null, "File name", 
     "Add New", JOptionPane.OK_CANCEL_OPTION); 
System.out.println(name); 
+0

그러면 사용자가 확인을 클릭했는지 취소했는지 어떻게 확인합니까? –

+0

@ user2059238 사용자가 '이름'을 취소하면 'null'이됩니다. 사용자가 아무 것도 입력하지 않고 확인을 클릭 한 경우'if (name == null)'또는 더 나은'if (name == null || name.isEmpty())'를 테스트 할 수 있습니다. – Pshemo

관련 문제