Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: Java text fields
|
Posted: Mar 21, 2003 5:56 PM
|
|
Here it is in Jython -- http://www.jython.org/, which is Python running in the Java Virtual Machine, with access to Java API.
I wanted to try out some Swing with Jython, so I figured this was a good excuse to do it. Jython works like a charm. I was surprised how easy it was to handle the events (look at where actionPerformed is set). Of course, the splitting up of the string and counting parts is a snap in Python, but as mentioned before, a pure Java approach would probably use a StringTokenizer.
# WordCounter.py
#
# Copyright 2001, by Matt Gerrans.
#
# Requires Jython, which you can find here:
# http://www.jython.org/
# http://www.jython.org/download.html
import os,sys
from javax.swing import JTextField
from javax.swing import JTextArea
from javax.swing import JFrame
from javax.swing import JLabel
from javax.swing import JButton
from javax.swing import JScrollPane
from java.awt.event import ActionEvent
from java.awt.event import ActionListener
from java.awt.event import WindowAdapter
from java.awt.event import WindowEvent
from java.awt import Container
from java.awt import FlowLayout
import java
try:
x = True
except:
True = 1
False = 0
def exit(e):
java.lang.System.exit(0)
class WordCounter:
def __init__(self):
self.inputText = None # Will be a JTextField.
self.outputText = None # Will be a JTextArea.
def showUI(self):
frame = JFrame("Wiz-Bang Word Counting Technology", windowClosing = exit)
pane = frame.getContentPane() # pane is a Container object.
pane.setLayout( FlowLayout() )
pane.add( JLabel("Enter your string:") )
self.inputText = JTextField("This is a sample string for your enjoyment", 30)
pane.add(self.inputText)
goButton = JButton("Parse It!", actionPerformed = self.goButtonPressed )
pane.add(goButton)
pane.add( JLabel( "Results of Parsimony:" ) )
self.outputText = JTextArea(5,50)
pane.add( JScrollPane(self.outputText) )
frame.pack()
frame.setSize( 600, 200 )
frame.setVisible(True)
def goButtonPressed(self,event):
text = self.inputText.getText()
self.inputText.setText("") # Clear it.
chunx = text.split()
if chunx:
chunx.sort( lambda a,b: len(b)-len(a) ) # Sort descending by length.
self.outputText.setText( 'There were %d words the longest one was "%s"' % (len(chunx),chunx[0]) )
else:
self.outputText.setText( 'Nothing much worth looking at in that string')
def main():
WordCounter().showUI()
if '__main__' == __name__:
main()
|
|