JButton

We touched on buttons in Chapter 11. They're pretty simple, so we'll cover them here. Import the JFrame, JButton, Frame, and Button classes.

>>> from javax.swing import JFrame, JButton
>>> button = JButton("J Button")
>>> frame = JFrame(visible=1)
>>> frame.title = "JFC"
>>> frame.contentPane.add(button)
>>> frame.pack()

Java Event Handling and JButton

To demonstrate Java event handling we'll create a class that implements ActionListener. Then, using addActionListener, we'll register an instance of the Listener class to the button.

Define the Listener class.

 >>> from java.awt.event import ActionListener >>> class ButtonListener(ActionListener): ... def actionPerformed(self, e): ... print e.getSource().getText() + " was clicked" ... ...

Get Python Programming with the Java™ Class Libraries: A Tutorial for Building Web and Enterprise Applications with Jython now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.