2017-04-26 66 views
-1

當我按下saveFileNameBtn按鈕時,我想從enterFileName文本字段返回字符串fileName。我嘗試在inline action listener method中獲取文本,但是當我嘗試返回它時,該變量超出了範圍。如何按下按鈕時從文本字段返回字符串?

String getSaveFileName() 
{ 
    JFrame enterFileNameWin = new JFrame(); 
    JPanel fileNameP = new JPanel(); 
    enterFileNameWin.add(fileNameP); 
    JLabel fileNamePrompt = new JLabel("Enter a name for the file"); 
    TextField enterFileName = new TextField(20); 
    JButton saveFileNameBtn = new JButton("Save"); 

    fileNameP.add(fileNamePrompt); 
    fileNameP.add(enterFileName); 
    fileNameP.add(saveFileNameBtn); 

    enterFileNameWin.setVisible(true); 
    enterFileNameWin.setSize(300, 100); 

    String fileName = enterFileName.getText(); 
    fileName = fileName + ".dat"; 

    saveFileNameBtn.addActionListener((ActionListener) this); 

    return fileName; 
} 

這不起作用,因爲fileName超出了範圍,無法返回。

String getSaveFileName() 
{ 
    JFrame enterFileNameWin = new JFrame(); 
    JPanel fileNameP = new JPanel(); 
    enterFileNameWin.add(fileNameP); 
    JLabel fileNamePrompt = new JLabel("Enter a name for the file"); 
    TextField enterFileName = new TextField(20); 
    JButton saveFileNameBtn = new JButton("Save"); 

    fileNameP.add(fileNamePrompt); 
    fileNameP.add(enterFileName); 
    fileNameP.add(saveFileNameBtn); 

    enterFileNameWin.setVisible(true); 
    enterFileNameWin.setSize(300, 100); 

    saveFileNameBtn.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      String fileName = enterFileName.getText(); 
      fileName = fileName + ".dat"; 

     } 
    }); 
    return fileName; 
} 

回答

0
saveFileNameBtn.addActionListener(new ActionListener(){ 
    public void actionPerformed(ActionEvent ae){ 
     String textFieldValue = enterFileName.getText(); 
     // call another function or do some operations 
    } 
}) 
0

可以定義的ActionListener類的fileName可變外面再使用語法OuterclassName.this引用它。由於我不知道您的班級名稱是什麼,請用該名稱替換Outerclass

String getSaveFileName() { 
    //your other code... 
    String fileName; 
    saveFileNameBtn.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent ae) { 
      Outerclass.this.fileName = enterFileName.getText(); 
     } 
    }); 
    return fileName; 
} 

如果您使用的是Java 8,你甚至可以進一步簡化使用Lambda表達式爲匿名的ActionListener類的代碼。

String getSaveFileName() { 
    //your other code... 
    String fileName; 
    saveFileNameBtn.addActionListener(e->{ Outerclass.this.fileName = enterFileName.getText(); }); 

    return fileName; 
} 

一個類似的例子可以在這個帖子中找到:(忽略final問題)Accessing Variable within JButton ActionListener

相關問題