OOP2

MainWindow.java

1
// No time to go out and search for which modules are needed and which ones I can leave out. A general import of these libraries will do for now.
2
import javax.swing.*;
3
import java.util.*;
4
import java.util.Arrays;
5
6
/**
7
 * MainWindow - Abstraction layer for a window in an MVC architecture. It abstracts a lot of fluff caused by Swing being Swing. It also takes care of the state and layout of the window itself, therefore making 80% of what's most used in simple programs with a GUI possible in just 20% of the time it used to take.
8
 * @author Maarten Vangeneugden - 1438256
9
 */
10
class MainWindow extends AbstractView {
11
	
12
	private JFrame window;
13
14
	/**
15
	 * Constructor. It creates an empty window. Period.
16
	 * @param windowTitle The title of the created window.
17
	 * @param widgets A list of widgets that can be added to the window.
18
	 */
19
	public MainWindow(String windowTitle, List<JComponent> widgets) {
20
21
		super(null, null);
22
		// First, we create the window itself:
23
		JFrame window = new JFrame(windowTitle); // Create the new window.
24
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set its close action. (Laymen's terms: Make it close down when you close it down.)
25
		setWindow(window);
26
27
		// Then, a JPanel:
28
		window.setContentPane(new JPanel());
29
30
		// Then, we add the given widgets to it:
31
		if(widgets != null) {
32
			for (JComponent widget : widgets) {
33
				addWidget(widget);
34
			}
35
		}
36
	}
37
38
	public void makeVisible() {
39
		getWindow().pack();
40
		getWindow().setVisible(true);
41
	}
42
43
	public void setWindow(JFrame window) {
44
		this.window = window;
45
	}
46
47
	public JFrame getWindow() {
48
		return window;
49
	}
50
51
	/**
52
	 * Adds a given widget to the window.
53
	 * It's highly recommended to have the widget's fluff (i.e. Actionlisteners) all prepped before adding.
54
	 * @param widget The widget to be added to the window.
55
	 */
56
	public void addWidget(JComponent widget) {
57
		getWindow().getContentPane().add(widget);
58
	}
59
60
	/**
61
	 * Returns a list containing all widgets in this window.
62
	 * @return A list of widgets.
63
	 */
64
	/*public  getWidgets() {
65
		return Arrays.asList(getWindow().getContentPane().getComponents());
66
	}*/
67
68
	/**
69
	 * Removes the given widget from the window.
70
	 * @param widget The widget that should be removed.
71
	 * @post The given widget is no longer in the window.
72
	 */
73
	public void removeWidget(JComponent widget) {
74
		getWindow().getContentPane().remove(widget);
75
	}
76
77
	public void update(Observable nope, Object no) {}
78
}
79