在JavaFX中,可以使用Lambda表达式和命令模式来实现给按钮添加功能。下面是一个示例代码:
首先定义一个接口Command,该接口包含了要执行的操作:
public interface Command {
void execute();
}
然后创建两个类:OpenFileCommand和SaveFileCommand,分别表示打开文件和保存文件的操作。
public class OpenFileCommand implements Command {
private FileChooser fileChooser;
private Stage primaryStage;
public OpenFileCommand(Stage primaryStage) {
this.primaryStage = primaryStage;
fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("Text Files", "*.txt"),
new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"),
new ExtensionFilter("Audio Files", "*.wav", "*.mp3", "*.aac"));
}
@Override
public void execute() {
File selectedFile = fileChooser.showOpenDialog(primaryStage);
if (selectedFile != null) {
System.out.println(selectedFile.getAbsolutePath());
}
}
}
public class SaveFileCommand implements Command {
private Stage primaryStage;
public SaveFileCommand(Stage primaryStage) {
this.primaryStage = primaryStage;
}
@Override
public void execute() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save Resource File");
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("Text Files", "*.txt"),
new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"),
new ExtensionFilter("Audio Files", "*.wav", "*.mp3", "*.aac"));
File selectedFile = fileChooser.showSaveDialog(primaryStage);
if (selectedFile != null) {
System.out.println(selectedFile.getAbsolutePath());
}
}
}
接下来,我们创建一个带有两个按钮的UI,一个用于打开文件,另一个用于保存文件。当用户单击按钮时,将执行相应的操作。
”`java public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Command openCommand = new OpenFileCommand(primaryStage);
Command saveCommand = new SaveFileCommand(primaryStage);
Button openButton = new Button("Open File");
openButton.setOnAction(event -> openCommand.execute());
Button saveButton = new Button("Save File");
saveButton.setOnAction(event -> save