如何在按下按钮时从文本字段返回字符串?

时间:2017-04-26 16:17:58

标签: java

当我按下fileName按钮时,我想从enterFileName文本字段返回字符串saveFileNameBtn。我尝试在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;
}   

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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,您甚至可以使用Anonymous ActionListener类的Lambda表达式进一步简化代码。

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

    return fileName;
}

可以在这篇文章中找到类似的示例:(忽略final问题)Accessing Variable within JButton ActionListener