我有一个JTextField,由于Swing内置支持,因此使用Cntl-V自动粘贴。但我还需要一个popupmenu来帮助用户不熟悉快捷键。以下代码
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);
}
}
答案 0 :(得分:1)
注意DefaultEditorKit.pasteAction
是Action
,"paste-from-clipboard"
的名称可能会有所帮助。可以更容易直接设置菜单项Action
:
JMenuItem pasteMenuItem = new JMenuItem(new DefaultEditorKit.PasteAction());