2

What I want to know is, how can I create GUI elements using swing inside a Jython class so that they can be referenced from outside the class, and I can use statements like button.setText("Hello") on an object that was created inside another class. For example:

foo.py:

 from javax.swing import *
 class Test():

    def __init__(self):
        frame = JFrame("TEST")
        button = JButton("Hey")
        frame.add(button)
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        frame.setSize(300,200)
        frame.show()

and then I have another file called somethingelse.py:

from foo import *
run = Test()

If I were to want to change the button text by using run.button.setText("Message"), how could I organise the Test() class such that I could change the text from the second file, somethingelse.py.

1 Answer 1

1

Your code is throwing away the references it has to the controls, so you can't access them from anywhere - frame and button are local variables, and disappear once __init__ returns.

You should (minimally) make them object members:

class Test():

    def __init__(self):
        self.frame = JFrame("TEST")
        self.button = JButton("Hey")
        self.frame.add(button)
        # ...

You can then say:

from foo import *
run = Test()
run.button.setText("Message")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.