-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWorldFrame.java
632 lines (568 loc) · 19.2 KB
/
WorldFrame.java
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
/*
* AP(r) Computer Science GridWorld Case Study:
* Copyright(c) 2002-2006 College Entrance Examination Board
* (http://www.collegeboard.com).
*
* This code is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @author Julie Zelenski
* @author Chris Nevison
* @author Cay Horstmann
*/
package info.gridworld.gui;
import info.gridworld.grid.Grid;
import info.gridworld.grid.Location;
import info.gridworld.world.World;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* The WorldFrame displays a World and allows manipulation of its occupants.
* <br />
* This code is not tested on the AP CS A and AB exams. It contains GUI
* implementation details that are not intended to be understood by AP CS
* students.
*/
public class WorldFrame<T> extends JFrame
{
private GUIController<T> control;
private GridPanel display;
private JTextArea messageArea;
private ArrayList<JMenuItem> menuItemsDisabledDuringRun;
private World<T> world;
private ResourceBundle resources;
private DisplayMap displayMap;
private Set<Class> gridClasses;
private JMenu newGridMenu;
private static int count = 0;
/**
* Constructs a WorldFrame that displays the occupants of a world
* @param world the world to display
*/
public WorldFrame(World<T> world)
{
this.world = world;
count++;
resources = ResourceBundle
.getBundle(getClass().getName() + "Resources");
try
{
System.setProperty("sun.awt.exception.handler",
GUIExceptionHandler.class.getName());
}
catch (SecurityException ex)
{
// will fail in an applet
}
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent event)
{
count--;
if (count == 0)
System.exit(0);
}
});
displayMap = new DisplayMap();
String title = System.getProperty("info.gridworld.gui.frametitle");
if (title == null) title = resources.getString("frame.title");
setTitle(title);
setLocation(25, 15);
URL appIconUrl = getClass().getResource("GridWorld.gif");
ImageIcon appIcon = new ImageIcon(appIconUrl);
setIconImage(appIcon.getImage());
makeMenus();
JPanel content = new JPanel();
content.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
content.setLayout(new BorderLayout());
setContentPane(content);
display = new GridPanel(displayMap, resources);
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new
KeyEventDispatcher()
{
public boolean dispatchKeyEvent(KeyEvent event)
{
if (getFocusOwner() == null) return false;
String text = KeyStroke.getKeyStrokeForEvent(event).toString();
final String PRESSED = "pressed ";
int n = text.indexOf(PRESSED);
if (n < 0) return false;
// filter out modifier keys; they are neither characters or actions
if (event.getKeyChar() == KeyEvent.CHAR_UNDEFINED && !event.isActionKey())
return false;
text = text.substring(0, n) + text.substring(n + PRESSED.length());
boolean consumed = getWorld().keyPressed(text, display.getCurrentLocation());
if (consumed) repaint();
return consumed;
}
});
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewport(new PseudoInfiniteViewport(scrollPane));
scrollPane.setViewportView(display);
content.add(scrollPane, BorderLayout.CENTER);
gridClasses = new TreeSet<Class>(new Comparator<Class>()
{
public int compare(Class a, Class b)
{
return a.getName().compareTo(b.getName());
}
});
for (String name : world.getGridClasses())
try
{
gridClasses.add(Class.forName(name));
}
catch (Exception ex)
{
ex.printStackTrace();
}
Grid<T> gr = world.getGrid();
gridClasses.add(gr.getClass());
makeNewGridMenu();
control = new GUIController<T>(this, display, displayMap, resources);
content.add(control.controlPanel(), BorderLayout.SOUTH);
messageArea = new JTextArea(2, 35);
messageArea.setEditable(false);
messageArea.setFocusable(false);
messageArea.setBackground(new Color(0xFAFAD2));
content.add(new JScrollPane(messageArea), BorderLayout.NORTH);
pack();
repaint(); // to show message
display.setGrid(gr);
}
public void repaint()
{
display.setGrid(world.getGrid());
String message = getWorld().getMessage();
if (message == null)
message = resources.getString("message.default");
messageArea.setText(message);
messageArea.repaint();
display.repaint(); // for applet
super.repaint();
}
/**
* Gets the world that this frame displays
* @return the world
*/
public World<T> getWorld()
{
return world;
}
/**
* Sets a new grid for this world. Occupants are transferred from
* the old world to the new.
* @param newGrid the new grid
*/
public void setGrid(Grid<T> newGrid)
{
Grid<T> oldGrid = world.getGrid();
Map<Location, T> occupants = new HashMap<Location, T>();
for (Location loc : oldGrid.getOccupiedLocations())
occupants.put(loc, world.remove(loc));
world.setGrid(newGrid);
for (Location loc : occupants.keySet())
{
if (newGrid.isValid(loc))
world.add(loc, occupants.get(loc));
}
display.setGrid(newGrid);
repaint();
}
/**
* Displays an error message
* @param t the throwable that describes the error
* @param resource the resource whose .text/.title strings
* should be used in the dialog
*/
public void showError(Throwable t, String resource)
{
String text;
try
{
text = resources.getString(resource + ".text");
}
catch (MissingResourceException e)
{
text = resources.getString("error.text");
}
String title;
try
{
title = resources.getString(resource + ".title");
}
catch (MissingResourceException e)
{
title = resources.getString("error.title");
}
String reason = resources.getString("error.reason");
String message = text + "\n"
+ MessageFormat.format(reason, new Object[]
{ t });
JOptionPane.showMessageDialog(this, message, title,
JOptionPane.ERROR_MESSAGE);
}
// Creates the drop-down menus on the frame.
private JMenu makeMenu(String resource)
{
JMenu menu = new JMenu();
configureAbstractButton(menu, resource);
return menu;
}
private JMenuItem makeMenuItem(String resource, ActionListener listener)
{
JMenuItem item = new JMenuItem();
configureMenuItem(item, resource, listener);
return item;
}
private void configureMenuItem(JMenuItem item, String resource,
ActionListener listener)
{
configureAbstractButton(item, resource);
item.addActionListener(listener);
try
{
String accel = resources.getString(resource + ".accel");
String metaPrefix = "@";
if (accel.startsWith(metaPrefix))
{
int menuMask = getToolkit().getMenuShortcutKeyMask();
KeyStroke key = KeyStroke.getKeyStroke(KeyStroke.getKeyStroke(
accel.substring(metaPrefix.length())).getKeyCode(),
menuMask);
item.setAccelerator(key);
}
else
{
item.setAccelerator(KeyStroke.getKeyStroke(accel));
}
}
catch (MissingResourceException ex)
{
// no accelerator
}
}
private void configureAbstractButton(AbstractButton button, String resource)
{
String title = resources.getString(resource);
int i = title.indexOf('&');
int mnemonic = 0;
if (i >= 0)
{
mnemonic = title.charAt(i + 1);
title = title.substring(0, i) + title.substring(i + 1);
button.setText(title);
button.setMnemonic(Character.toUpperCase(mnemonic));
button.setDisplayedMnemonicIndex(i);
}
else
button.setText(title);
}
private void makeMenus()
{
JMenuBar mbar = new JMenuBar();
JMenu menu;
menuItemsDisabledDuringRun = new ArrayList<JMenuItem>();
mbar.add(menu = makeMenu("menu.file"));
newGridMenu = makeMenu("menu.file.new");
menu.add(newGridMenu);
menuItemsDisabledDuringRun.add(newGridMenu);
menu.add(makeMenuItem("menu.file.quit", new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}));
menu.add(makeMenuItem("menu.file.save", new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
world.getClass().getMethod("save",null).invoke(world);
}
catch(Exception ex){}
}
}));
menu.add(makeMenuItem("menu.file.load", new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
world.getClass().getMethod("load",null).invoke(world);
}
catch(Exception ex){}
}
}));
mbar.add(menu = makeMenu("menu.view"));
menu.add(makeMenuItem("menu.view.up", new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
display.moveLocation(-1, 0);
}
}));
menu.add(makeMenuItem("menu.view.down", new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
display.moveLocation(1, 0);
}
}));
menu.add(makeMenuItem("menu.view.left", new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
display.moveLocation(0, -1);
}
}));
menu.add(makeMenuItem("menu.view.right", new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
display.moveLocation(0, 1);
}
}));
JMenuItem viewEditMenu;
menu.add(viewEditMenu = makeMenuItem("menu.view.edit",
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
control.editLocation();
}
}));
menuItemsDisabledDuringRun.add(viewEditMenu);
JMenuItem viewDeleteMenu;
menu.add(viewDeleteMenu = makeMenuItem("menu.view.delete",
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
control.deleteLocation();
}
}));
menuItemsDisabledDuringRun.add(viewDeleteMenu);
menu.add(makeMenuItem("menu.view.zoomin", new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
display.zoomIn();
}
}));
menu.add(makeMenuItem("menu.view.zoomout", new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
display.zoomOut();
}
}));
mbar.add(menu = makeMenu("menu.help"));
menu.add(makeMenuItem("menu.help.about", new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
showAboutPanel();
}
}));
menu.add(makeMenuItem("menu.help.help", new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
showHelp();
}
}));
menu.add(makeMenuItem("menu.help.license", new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
showLicense();
}
}));
setRunMenuItemsEnabled(true);
setJMenuBar(mbar);
}
private void makeNewGridMenu()
{
newGridMenu.removeAll();
MenuMaker<T> maker = new MenuMaker<T>(this, resources, displayMap);
maker.addConstructors(newGridMenu, gridClasses);
}
/**
* Sets the enabled status of those menu items that are disabled when
* running.
* @param enable true to enable the menus
*/
public void setRunMenuItemsEnabled(boolean enable)
{
for (JMenuItem item : menuItemsDisabledDuringRun)
item.setEnabled(enable);
}
/**
* Brings up a simple dialog with some general information.
*/
private void showAboutPanel()
{
String html = MessageFormat.format(resources
.getString("dialog.about.text"), new Object[]
{ resources.getString("version.id") });
String[] props = { "java.version", "java.vendor", "java.home", "os.name", "os.arch", "os.version", "user.name", "user.home", "user.dir" };
html += "<table border='1'>";
for (String prop : props)
{
try
{
String value = System.getProperty(prop);
html += "<tr><td>" + prop + "</td><td>" + value + "</td></tr>";
}
catch (SecurityException ex)
{
// oh well...
}
}
html += "</table>";
html = "<html>" + html + "</html>";
JOptionPane.showMessageDialog(this, new JLabel(html), resources
.getString("dialog.about.title"),
JOptionPane.INFORMATION_MESSAGE);
}
/**
* Brings up a window with a scrolling text pane that display the help
* information.
*/
private void showHelp()
{
JDialog dialog = new JDialog(this, resources
.getString("dialog.help.title"));
final JEditorPane helpText = new JEditorPane();
try
{
URL url = getClass().getResource("GridWorldHelp.html");
helpText.setPage(url);
}
catch (Exception e)
{
helpText.setText(resources.getString("dialog.help.error"));
}
helpText.setEditable(false);
helpText.addHyperlinkListener(new HyperlinkListener()
{
public void hyperlinkUpdate(HyperlinkEvent ev)
{
if (ev.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
try
{
helpText.setPage(ev.getURL());
}
catch (Exception ex)
{
}
}
});
JScrollPane sp = new JScrollPane(helpText);
sp.setPreferredSize(new Dimension(650, 500));
dialog.getContentPane().add(sp);
dialog.setLocation(getX() + getWidth() - 200, getY() + 50);
dialog.pack();
dialog.setVisible(true);
}
/**
* Brings up a dialog that displays the license.
*/
private void showLicense()
{
JDialog dialog = new JDialog(this, resources
.getString("dialog.license.title"));
final JEditorPane text = new JEditorPane();
try
{
URL url = getClass().getResource("GNULicense.txt");
text.setPage(url);
}
catch (Exception e)
{
text.setText(resources.getString("dialog.license.error"));
}
text.setEditable(false);
JScrollPane sp = new JScrollPane(text);
sp.setPreferredSize(new Dimension(650, 500));
dialog.getContentPane().add(sp);
dialog.setLocation(getX() + getWidth() - 200, getY() + 50);
dialog.pack();
dialog.setVisible(true);
}
/**
* Nested class that is registered as the handler for exceptions on the
* Swing event thread. The handler will put up an alert panel and dump the
* stack trace to the console.
*/
public class GUIExceptionHandler
{
public void handle(Throwable e)
{
e.printStackTrace();
JTextArea area = new JTextArea(10, 40);
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
area.setText(writer.toString());
area.setCaretPosition(0);
String copyOption = resources.getString("dialog.error.copy");
JOptionPane pane = new JOptionPane(new JScrollPane(area),
JOptionPane.ERROR_MESSAGE, JOptionPane.YES_NO_OPTION, null,
new String[]
{ copyOption, resources.getString("cancel") });
pane.createDialog(WorldFrame.this, e.toString()).setVisible(true);
if (copyOption.equals(pane.getValue()))
{
area.setSelectionStart(0);
area.setSelectionEnd(area.getText().length());
area.copy(); // copy to clipboard
}
}
}
}