I thought I would try to enhance Carl’s code to cope with selecting part of the text in the Text Field, rather than affecting all of the contents at once. Here’s the result:
[code]def doCut(event):
from java.awt import Toolkit
from java.awt.datatransfer import StringSelection
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard()
clipboard.setContents(StringSelection(event.source.getSelectedText()),None)
text=event.source.text
sel=event.source.getSelectedText()
pos=event.source.getCaretPosition()
length=len(sel)
test=text[pos:(pos+length)]
if test==sel:
#Caret is at the start of the selected text.
string1=text[:pos]
string2=text[(pos+length):]
else:
#Caret is at the end of the selected text.
string1=text[:(pos-length)]
string2=text[pos:]
event.source.text="%s%s" % (string1,string2)
def doCopy(event):
from java.awt import Toolkit
from java.awt.datatransfer import StringSelection
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard()
clipboard.setContents(StringSelection(event.source.getSelectedText()),None)
def doPaste(event):
from java.awt import Toolkit
from java.awt.datatransfer import DataFlavor
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard()
contents = clipboard.getContents(None).getTransferData(DataFlavor.stringFlavor)
text=event.source.text
sel=event.source.getSelectedText()
pos=event.source.getCaretPosition()
if sel is None:
length=0
else:
length=len(sel)
test=text[pos:(pos+length)]
if test==sel:
#Caret is at the start of the selected text.
string1=text[:pos]
string2=text[(pos+length):]
else:
#Caret is at the end of the selected text.
string1=text[:(pos-length)]
string2=text[pos:]
event.source.text="%s%s%s" % (string1,contents,string2)
sel=event.source.getSelectedText()
if sel is None:
menu = fpmi.gui.createPopupMenu([“Paste”], [doPaste])
else:
menu = fpmi.gui.createPopupMenu([“Cut”,“Copy”,“Paste”], [doCut, doCopy, doPaste])
menu.show(event)
[/code]
The only problem I can see is that when the operation is finished, the default behaviour is for the whole of the Text Field contents to be highlighted. Is there a way to stop this? I also found that I can’t access the getSelectedText() function for the Text Area component. Is this possible?
Of course, Carl is now going to point out the Java functions that can do all this in just 2 lines
Al