Question

I am doing my own Notepad in Java. Basic part is almost done. But i have big problem with JMenuItem which pastes words to JTextPane. It works(pasting), but i want that JMenuItem reacts:

  • when is something in memory(copy - from anywhere) => JMenuItem will be setEnabled(true)
  • when isnt something in memory > JMenuItem will be setEnabled(false)

    private static JMenuItem editPaste; // atribut
    editPaste = new JMenuItem(new DefaultEditorKit.PasteAction()); //in private method
    

I have no idea, what I should listened(listener of what??) for this action. I did not see that anywhere(http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html).

Was it helpful?

Solution

Thanks you for advices and keywords. I win, partly :)

For my case works:

// atributes
private static JMenuItem editPaste;
private static Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); 
// private method
clipboard.addFlavorListener(new ListenerPaste());
editPaste = new JMenuItem(new DefaultEditorKit.PasteAction());
editPaste.setEnabled(false);
// listener 
private static class ListenerPaste implements FlavorListener {
    public void flavorsChanged(FlavorEvent e) {
        checkPaste();
    }
}
// private method
private static void checkPaste() {
    try {
        if(clipboard.getData(DataFlavor.stringFlavor) != null) {
            editPaste.setEnabled(true);
            // JOptionPane.showMessageDialog(null, (String) clipboard.getData(DataFlavor.stringFlavor));
        }
    } catch (UnsupportedFlavorException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
}
// in constructor we check it also
checkPaste();

I do not know, if this is the most appropriate solution, but for me it works. That line which is commented - for real time it doesnt work very well - more: listen to clipboard changes, check ownership? Next source: http://www.avajava.com/tutorials/lessons/how-do-i-get-a-string-from-the-clipboard.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top