当我按下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;
}
答案 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