Differences between revisions 8 and 9
Revision 8 as of 2007-09-16 23:11:16
Size: 13467
Editor: GregMoore
Comment: Added several examples and content
Revision 9 as of 2007-09-16 23:36:01
Size: 14317
Editor: GregMoore
Comment: more content and examples
Deletions are marked like this. Additions are marked like this.
Line 19: Line 19:

Below there are several examples that cover various swing components, some time in the past I found a jython script that showed off a number of components on the Georgia Tech web site, being that the web, due to its nature is in a constant state of flux, I have provideded a copy of the SwingSampler with the permission of the professor who believes he is the author.

In March 2007, Anton Vredegoor asked the Jython mailing list for help converting [http://leepoint.net/notes-java/examples/components/editor/nutpad.html Java Simple Editor] and Jeff Emanuel provided complete conversion to jython. Here is the JyhtonNutpad that was posted.

The Jython Mailing list is a great source of help. If you have questions or problems the mailing list is a good place to look for help but there is no substute for RTFM or google searches before hand.

Swing Examples in Jython

DocumentationAndEducation

TableOfContents


Using Java Swing with Jython is a lot of fun and makes it really easy to develop a nice UI in much less code then a similar Java app. All of the examples below work with Jython 2.2 and a 1.5 (or greater) JVM is strongly recommended.

Some of these, maybe all but it not tested, will work using jdk/jre <1.5. You will need to change the code frame.contentPane.add instead of frame.add

Most of the examples below use import * its bad form and the methods should be specified but since these are simple examples this ensures that every thing thats needed is loaded. When you are just experimenting with code using something like from javax.swing import * makes things easier instead of specifing each method or package.

Below there are several examples that cover various swing components, some time in the past I found a jython script that showed off a number of components on the Georgia Tech web site, being that the web, due to its nature is in a constant state of flux, I have provideded a copy of the SwingSampler with the permission of the professor who believes he is the author.

In March 2007, Anton Vredegoor asked the Jython mailing list for help converting [http://leepoint.net/notes-java/examples/components/editor/nutpad.html Java Simple Editor] and Jeff Emanuel provided complete conversion to jython. Here is the JyhtonNutpad that was posted.

The Jython Mailing list is a great source of help. If you have questions or problems the mailing list is a good place to look for help but there is no substute for RTFM or google searches before hand.

Hello, World!

These are some ways of creating a simple frame with the title 'Hello, World!' on it.

{{{from javax.swing import JFrame JFrame('Hello, World!', defaultCloseOperation=JFrame.EXIT_ON_CLOSE, size=(300, 300), locationRelativeTo=None).show()}}}

{{{from javax.swing import JFrame f = JFrame('Hello, World!', defaultCloseOperation=JFrame.EXIT_ON_CLOSE, size=(300, 300), locationRelativeTo=None) f.show()}}}

JButton and Button events

Just a simple example.

"""
A simple example that shows button event handling

Greg Moore
Sept 2007
"""

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

class Example:
  def setText(self,event):
      self.label.text = 'Button clicked.'

  def __init__(self):
    frame = JFrame("Jython Example JButton")
    frame.setSize(100, 100)
    frame.setLayout(BorderLayout())
    self.label = JLabel('Hello from Jython')
    frame.add(self.label, BorderLayout.NORTH)
    button = JButton('Click Me',actionPerformed=self.setText)
    frame.add(button, BorderLayout.SOUTH)
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
    frame.setVisible(True)

if __name__ == '__main__':
        Example()

JTextField

"""
Swing JTextField example in Jyhton.

Creates 2 text fields and clicking the button copies text in one textfield
to the other. 

Greg Moore
Sept 2007
"""

from javax.swing import *
from java.lang import *

class Example:

  def copyText(self,event):
      self.textfield2.text = self.textfield1.text

  def __init__(self):
        # These lines setup the basic frame, size.
        # the setDefaultCloseOperation is required to completely exit the app
        # when you click the close button
    frame = JFrame("Jython JText Field Example")
    frame.setSize(200, 150)
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)

    # Create Panel and add swing components and show it.
    pnl = JPanel()
    frame.add(pnl)
    self.textfield1 = JTextField('Type something here',15)
    pnl.add(self.textfield1)
    self.textfield2 = JTextField('and click Copy', 15)
    pnl.add(self.textfield2)
    copyButton = JButton('Copy',actionPerformed=self.copyText)
    pnl.add(copyButton)
    frame.pack()
    frame.setVisible(True)

if __name__ == '__main__':
  #start things off.
  Example()

JRadioButton

"""
Swing JRadioButton example in Jyhton.

Creates radio buttons and event handler

Greg Moore
Sept 2007
"""

# Using import * is bad form but since this is just a example I'll take the
# easy way out instead of specifing each package.
from javax.swing import *
from java.awt import *


class RadioButtonExample:
  def radioBtnbCheck(self,event):
    # Process the events and update the label
    statusText = ""
    if self.radioBtn1.isSelected():
      statusText = "Radio Button 1 is selected "
    if self.radioBtn2.isSelected():
      statusText = statusText + "Radio Button 2 is selected "
    self.rbStatusLabel.text = statusText

  def __init__(self):
        # These lines setup the basic frame, size and layout
        # the setDefaultCloseOperation is required to completely exit the app
        # when you click the close button
    frame = JFrame("Jython Example JRadioButton")
    frame.setSize(400, 150)
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
    frame.setLayout(BorderLayout())

    # create 2 panels the top one containing radio buttons and the bottom one
    # has the label and button. add them to the frame and show it.
    rbPanel = JPanel()
    frame.add(rbPanel,BorderLayout.NORTH)
    self.radioBtn1 = JRadioButton('Radio Button 1')
    self.radioBtn2 = JRadioButton('Radio Button 2')
    rbPanel.add(self.radioBtn1)
    rbPanel.add(self.radioBtn2)
    rbBtnGroup = ButtonGroup()
    rbBtnGroup.add(self.radioBtn1)
    rbBtnGroup.add(self.radioBtn2)

    panel = JPanel()
    panel.setLayout(BorderLayout())
    frame.add(panel,BorderLayout.SOUTH)
    button = JButton('Check',actionPerformed=self.radioBtnbCheck)
    panel.add(button,BorderLayout.WEST)
    self.rbStatusLabel =JLabel()
    panel.add(self.rbStatusLabel,BorderLayout.EAST)
    frame.pack()
    frame.setVisible(True)

if __name__ == '__main__':
  #start things off.
  RadioButtonExample()

JCheckBox

"""
Swing JCheckBox example in Jyhton.

Creates a couple checkboxes and and event handler

Greg Moore
Sept 2007
"""

# Using import * is bad form but since this is just a example I'll take the
# easy way out instead of specifing each package.
from javax.swing import *
from java.awt import *

class CheckBoxExample:

  def cbEvents(self,event):
        # Process the events and update the label
    cbStatusMsg=""
    if self.chkbox1.isSelected():
      cbStatusMsg = "checkbox1 is selected "
    if self.chkbox2.isSelected():
      cbStatusMsg = cbStatusMsg + "checkbox2 is selected"
    self.cbStatusLabel.text = cbStatusMsg

  def __init__(self):
        # These lines setup the basic frame, size and layout
        # the setDefaultCloseOperation is required to completely exit the app
        # when you click the close button
        frame = JFrame("Jython JCheckBox Example")
        frame.setLayout(BorderLayout())
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
        
        # this could be done with only one JPanel or use different layout
        # create a panel for the checkboxes
        cbPanel = JPanel()
        frame.add(cbPanel,BorderLayout.NORTH)
        self.chkbox1 = JCheckBox('checkbox 1')
        self.chkbox2 = JCheckBox('checkbox 2')
        cbPanel.add(self.chkbox1)
        cbPanel.add(self.chkbox2)

        # create a second panel with the button and label
        panel = JPanel()
        panel.setLayout(BorderLayout())
        frame.add(panel,BorderLayout.SOUTH)
        button = JButton('check',actionPerformed=self.cbEvents)
        panel.add(button,BorderLayout.SOUTH)
        self.cbStatusLabel =JLabel('select one and click button')
        panel.add(self.cbStatusLabel,BorderLayout.CENTER)

        # now that the panels have been added to the frame show our creation
        frame.pack()
        frame.setVisible(True)

if __name__ == '__main__':
  #start things off.
  CheckBoxExample()

JList

"""
Swing JList example in Jyhton.

Creates a simple list of cities and then updates a JLabel based on the
the city selected.

Greg Moore
Sept 2007
"""

# Using import * is bad form but since this is just a example I'll take the
# easy way out instead of specifing each package.
from javax.swing import *
from java.awt import *

class JListExample:

  def listSelect(self,event):
        # Process the events from the list box and update the label
    selected = self.list.selectedIndex
    if selected >= 0:
      cityName = self.data[selected]
      self.label.text = cityName

  def __init__(self):

        # These lines setup the basic frame, size and layout
        # the setDefaultCloseOperation is required to completely exit the app
        # when you click the close button
    frame = JFrame("Jython JList Example")
    frame.setSize(200, 225)
    frame.setLayout(BorderLayout())
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)

    # set up the list and the contents of the list
    # the python typle get converted to a Java vector
    self.data = ('Portland','San Francisco','Madrid','Venice','Starnberg','New York','Paris','London')
    self.list = JList(self.data)
    spane = JScrollPane()
    spane.setPreferredSize(Dimension(100,125))
    spane.getViewport().setView((self.list))

        # a panel is a bit over kill but this is a demo. :)
    panel = JPanel()
    panel.add(spane)
    frame.add(panel,BorderLayout.CENTER)

        # create the button, and city label and the show our work
        # with Jython only one line is needed create a button and attach an
        # event handler.
    btn = JButton('Select',actionPerformed=self.listSelect)
    frame.add(btn,BorderLayout.SOUTH)
    self.label = JLabel(' Select City and click select')
    frame.add(self.label,BorderLayout.NORTH)
    frame.pack()
    frame.setVisible(True)


if __name__ == '__main__':
        #start things off.
        JListExample()

JComboBox

under construction

Here are a couple of combo box examples. one requires a button click and the other is more dynamic ComboboxExample.

"""
Swing JComboBox example in Jyhton.

Creates a simple comboBox of cities and then updates a JLabel based on the
the city selected after button click.

Greg Moore
Sept 2007

"""

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

class JComboBoxExample:

  def cbSelect(self,event):
    selected = self.cb.selectedIndex
    if selected >= 0:
      data = self.data[selected]
      self.label.text = data + " selected"

  def __init__(self):
    frame = JFrame("Jython JComboBox Example")
    frame.setSize(200, 250)
    frame.setLayout(BorderLayout())

    self.data = ('Portland','San Francisco','Madrid','Venice','Starnberg','New York','Paris','London')
    self.cb = JComboBox(self.data)

    pnl = JPanel()
    pnl.add(self.cb)

    frame.add(pnl,BorderLayout.NORTH)

    btn = JButton('click me',actionPerformed=self.cbSelect)
    frame.add(btn,BorderLayout.SOUTH)
    self.label = JLabel('Select a city then click button')
    frame.add(self.label,BorderLayout.CENTER)
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
    frame.setVisible(True)

if __name__ == '__main__':
        JComboBoxExample()

JTree

This example is a bit long so you here is the JtreeExample

JTable

"""

Swing JTable example in Jyhton.

Creates a simple table.

Greg Moore
Sept 2007


"""

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

class Example:

  def __init__(self):
    frame = JFrame("Jython JTable Example")
    frame.setSize(400, 150)
    frame.setLayout(BorderLayout())

    self.tableData = [
      ['numbers', '67890' ,'This'],
      ['mo numbers', '2598790', 'is'],
      ['got Math', '2598774', 'a'],
      ['got Numbers', '1234567', 'Column'],
      ['got pi','3.1415926', 'Apple'],
       ]
    colNames = ('Col Labels','Go','Here')
    dataModel = DefaultTableModel(self.tableData, colNames)
    self.table = JTable(dataModel)

    scrollPane = JScrollPane()
    scrollPane.setPreferredSize(Dimension(300,100))
    scrollPane.getViewport().setView((self.table))

    panel = JPanel()
    panel.add(scrollPane)

    frame.add(panel, BorderLayout.CENTER)
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
    frame.setVisible(True)

if __name__ == '__main__':
        Example()

JTabbedPane

This create a simple JTabbedPane example. Here is another TabbedExample.

"""

Swing JTabbedPane example in Jyhton.

Greg Moore
Sept 2007

"""

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

class Example:

  def __init__(self):
    frame = JFrame("Jython JTabbedPane Example")
    frame.setSize(400, 300)
    frame.setLayout(BorderLayout())

    tabPane = JTabbedPane(JTabbedPane.TOP)

    label = JLabel("<html><br>This is a tab1</html>")
    panel1 = JPanel()
    panel1.add(label)
    tabPane.addTab("tab1", panel1)

    label2 = JLabel("This is a tab2")

    panel2 = JPanel()
    panel2.add(label2)
    tabPane.addTab("tab2", panel2)

    frame.add(tabPane)
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
    frame.setVisible(True)

if __name__ == '__main__':
        Example()

JSplitPane

This just creates a simple split pane. nothing fancy. :)

"""
Swing JSplitPane example in Jyhton.

Greg Moore
Sept 2007

"""

from javax.swing import *
from java.awt import *
class Example:

  def __init__(self):
    frame = JFrame("Jython JTable Example")
    frame.setSize(400, 300)
    frame.setLayout(BorderLayout())

    splitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT);

    label1 = JLabel("This is a panel1")
    panel1 = JPanel()
    panel1.add(label1)
    splitPane.setLeftComponent(panel1);

    label2 = JLabel("This is a panel2")

    panel2 = JPanel()
    panel2.add(label2)
    splitPane.setRightComponent(panel2);
    splitPane.setDividerLocation(150);

    frame.add(splitPane)
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
    frame.setVisible(True)

if __name__ == '__main__':
    Example()

ADB SwingExamples (last edited 2011-08-07 01:33:32 by h86)