-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathToolBarFrame.java
78 lines (65 loc) · 2.4 KB
/
ToolBarFrame.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
package toolBar;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* A frame with a toolbar and menu for color changes.
*/
public class ToolBarFrame extends JFrame {
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
private JPanel panel;
public ToolBarFrame() {
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// add a panel for color change
panel = new JPanel();
add(panel, BorderLayout.CENTER);
// set up actions
Action blueAction = new ColorAction("Blue", new ImageIcon(
ClassLoader.getSystemResource("img/blue-ball.gif")), Color.BLUE);
Action yellowAction = new ColorAction("Yellow", new ImageIcon(
ClassLoader.getSystemResource("img/yellow-ball.gif")), Color.YELLOW);
Action redAction = new ColorAction("Red", new ImageIcon(
ClassLoader.getSystemResource("img/red-ball.gif")), Color.RED);
Action exitAction = new AbstractAction("Exit", new ImageIcon(
ClassLoader.getSystemResource("img/exit.gif"))) {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
};
exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit");
// populate toolbar
JToolBar bar = new JToolBar();
bar.add(blueAction);
bar.add(yellowAction);
bar.add(redAction);
bar.addSeparator();
bar.add(exitAction);
add(bar, BorderLayout.NORTH);
// populate menu
JMenu menu = new JMenu("Color");
menu.add(yellowAction);
menu.add(blueAction);
menu.add(redAction);
menu.add(exitAction);
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
setJMenuBar(menuBar);
}
/**
* The color action sets the background of the frame to a given color.
*/
private class ColorAction extends AbstractAction {
public ColorAction(String name, ImageIcon icon, Color c) {
putValue(Action.NAME, name);
putValue(Action.SMALL_ICON, icon);
putValue(Action.SHORT_DESCRIPTION, name + " background");
putValue("Color", c);
}
public void actionPerformed(ActionEvent event) {
Color c = (Color) getValue("Color");
panel.setBackground(c);
}
}
}