【发布时间】:2019-04-17 23:30:37
【问题描述】:
我通常不编写 java GUI 应用程序,但我需要一个简单的实用程序,并且我设法使用 Swing 和 AWT 编写它。该实用程序需要打开和保存文件,主要用于Macos。 Apple recommends 使用 AWT 的 FileDialog 而不是 Swing 文件选择器,因为 FileDialog 的作用更像是原生 Macos 文件对话框。所以我就是这么做的。
完成的实用程序工作正常,除了我无法解决的一件事。保存文件的对话框包括一个用于输入文件名的文本框。右键单击文本框会显示一个带有复制和粘贴选项的菜单。但是相关的击键(Cmd-C、Cmd-V)没有任何作用。
下面的程序演示了这个问题:
import java.awt.BorderLayout;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Scratch extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
JButton saveButton;
FileDialog fd;
public Scratch(Frame aFrame) {
super(new BorderLayout());
fd = new FileDialog(aFrame, "Save", FileDialog.SAVE);
saveButton = new JButton("Save a File...");
saveButton.addActionListener(this);
this.add(saveButton);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == saveButton) {
fd.setVisible(true);
String file = fd.getFile();
System.out.println(file);
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Scratch");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Scratch(frame));
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
当您运行它时,它会打开一个带有保存按钮的窗口。单击该按钮会打开一个带有“另存为”字段的 FileDialog。您可以在该字段中输入内容,也可以右键单击该字段并从弹出菜单中选择“复制”或“粘贴”。但是您不能使用 Cmd-V 粘贴到该字段中 - 似乎没有任何键击绑定到复制或粘贴操作。
有没有一种直接的方法可以将击键绑定到FileDialog 内的文件名框?
【问题讨论】: