views:

236

answers:

1

Jython 2.5

I'm trying to bind a method to the focusGained event of a JText control, but all the examples that I found are Java samples, not Jython. Here's the code, I want to run a custom method when each text control gains focus (to select all the control's text, for instance)

from javax.swing import *
from java.awt import *

class Test(JFrame):
    def __init__(self):
        JFrame.__init__(self,
                        'JDesktopPane and JInternalFrame Demo',
                        size=(600, 300),
                        defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        self.desktop = JDesktopPane()
        self.contentPane.add(JScrollPane(self.desktop)) # This is the same as self.getContentPane().add(...)

        frame = JInternalFrame("Frame", 1, 1, 1, 1, size=(400, 400), visible=1)
        panel = JPanel()

        self.label = JLabel('Hello from Jython')
        panel.add(self.label)

        self.textfield1 = JTextField('Type something here',15)
        # self.textfield1.addFocusListener(event.FocusListener())  # ???

        panel.add(self.textfield1)

        self.textfield2 = JTextField('and click Copy', 15)
        panel.add(self.textfield2)

        copyButton = JButton('Copy',actionPerformed=self.noAction)
        panel.add(copyButton)

        frame.add(panel)
        frame.pack()
        self.desktop.add(frame)

        frame.setSelected(1)
        frame.moveToFront()

    def noAction (self, event):
        pass

if __name__ == '__main__':
    test = Test()
    test.setLocation(100, 100)
    test.show()
+1  A: 

I was just trying to figure this out yesterday myself...tested and works:

from javax.swing import *
from java.awt import *

class Test(JFrame):
    def __init__(self):
        JFrame.__init__(self,
                        'JDesktopPane and JInternalFrame Demo',
                        size=(600, 300),
                        defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        self.desktop = JDesktopPane()
        self.contentPane.add(JScrollPane(self.desktop)) # This is the same as self.getContentPane().add(...)

        frame = JInternalFrame("Frame", 1, 1, 1, 1, size=(400, 400), visible=1)
        panel = JPanel()

        self.label = JLabel('Hello from Jython')
        panel.add(self.label)

        self.textfield1 = JTextField('Type something here',15,focusGained=self.myOnFocus)


        panel.add(self.textfield1)

        self.textfield2 = JTextField('and click Copy', 15)
        panel.add(self.textfield2)

        copyButton = JButton('Copy',actionPerformed=self.noAction)
        panel.add(copyButton)

        frame.add(panel)
        frame.pack()
        self.desktop.add(frame)

        frame.setSelected(1)
        frame.moveToFront()

    def myOnFocus(self,event):
        print "testing..."

    def noAction (self, event):
        pass

if __name__ == '__main__':
    test = Test()
    test.setLocation(100, 100)
    test.show()
Jack
Excellent, thank you!
PabloG