java粘贴菜单项,附加到JTextField时不执行任何操作
我有一个JTextField,因为Swing中内置了支持,所以使用Cntl-V自动粘贴。但我还需要一个弹出菜单来帮助不太熟悉快捷键的用户。下面的代码
import javax.swing.*;
import java.awt.*;
public class TestPopup
{
public static void main(final String[] args)
{
JFrame frame = new JFrame();
JTextField widget = new JTextField(50);
final JPopupMenu popup = new JPopupMenu();
popup.add(widget.getActionMap().get("paste"));
widget.add(popup);
widget.setComponentPopupMenu(popup);
frame.add(widget);
frame.pack();
frame.setVisible(true);
}
}
显示粘贴选项,但选中时不执行任何操作。 此外,注释显示为“粘贴”而不是“粘贴”
我做错了什么
*解决方案*
不用担心,使用DefaultEditorKit让它工作。pasteAction而不是“粘贴”使粘贴工作(我不清楚“粘贴”操作在它存在时的实际作用)
import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
import java.awt.*;
public class TestPopup
{
public static void main(final String[] args)
{
JFrame frame = new JFrame();
JTextField widget = new JTextField(50);
final JPopupMenu popup = new JPopupMenu();
popup.add(widget.getActionMap().get(DefaultEditorKit.pasteAction));
widget.add(popup);
widget.setComponentPopupMenu(popup);
frame.add(widget);
frame.pack();
frame.setVisible(true);
}
}
但这不会解决名称问题,为此我引入了菜单项
import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
import java.awt.*;
public class TestPopup
{
public static void main(final String[] args)
{
JFrame frame = new JFrame();
JTextField widget = new JTextField(50);
final JPopupMenu popup = new JPopupMenu();
JMenuItem pasteMenuItem = new JMenuItem(widget.getActionMap().get(DefaultEditorKit.pasteAction));
pasteMenuItem.setText("Paste");
popup.add(pasteMenuItem);
widget.setComponentPopupMenu(popup);
frame.add(widget);
frame.pack();
frame.setVisible(true);
}
}
# 1 楼答案
注意
DefaultEditorKit.pasteAction
是Action
,"paste-from-clipboard"
的名称,可能会有所帮助。直接设置菜单项的Action
可能更容易: