-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.py
68 lines (56 loc) · 2.16 KB
/
tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from javax.swing import *
from java.awt import *
from javax.swing.tree import DefaultMutableTreeNode
class Example:
def __init__(self):
mCitiesData = ['Memphis', 'Melbourne', 'Milan',
'Marrakech', 'Moscow', 'Munich']
sCitiesData = ['San Francisco', 'Salzburg', 'Santiago',
'Sydney', 'Sandnessjoen', 'Stockholm']
frame = JFrame("Jython JTree Example")
frame.setSize(400, 350)
frame.setLayout(BorderLayout())
root = DefaultMutableTreeNode('Cities')
mCities = DefaultMutableTreeNode('Cities starting with M')
sCities = DefaultMutableTreeNode('Cities starting with S')
root.add(mCities)
root.add(sCities)
#now add the cities starting with M & S
self.addCities(mCities, mCitiesData)
self.addCities(sCities, sCitiesData)
self.tree = JTree(root)
scrollPane = JScrollPane() # add a scrollbar to the viewport
scrollPane.setPreferredSize(Dimension(300,250))
scrollPane.getViewport().setView((self.tree))
panel = JPanel()
panel.add(scrollPane)
frame.add(panel, BorderLayout.CENTER)
btn = JButton('Select', actionPerformed = self.citySelect)
frame.add(btn,BorderLayout.SOUTH)
self.label = JLabel('Select city')
frame.add(self.label, BorderLayout.NORTH)
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
frame.setVisible(True)
self.addCities
def addCities(self, branch, branchData=None):
''' add data to tree branch
requires branch and data to add to branch
'''
# this does not check to see if its a valid branch
if branchData == None:
branch.add(DefaultMutableTreeNode('No valid data'))
else:
for item in branchData:
# add the data from the specified list to the branch
branch.add(DefaultMutableTreeNode(item))
def citySelect(self, event):
selected = self.tree.getLastSelectedPathComponent()
#check to make sure a city is selected
if selected == None:
self.label.text = 'No city selected'
else:
self.label.text = str(selected)
#this is more Jythonic then:
#self.label.text = selected.toString()
if __name__ == '__main__':
Example()