forked from dr-cs/intro-oop-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathColorBox.java
More file actions
91 lines (76 loc) · 2.74 KB
/
ColorBox.java
File metadata and controls
91 lines (76 loc) · 2.74 KB
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
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class ColorBox extends JFrame implements ActionListener {
JPanel colorPanel;
public ColorBox() {
super("Color, Box, and Nesting Demo");
// Set up button panel
JButton redButton = new JButton("Red");
redButton.addActionListener(this);
redButton.setEnabled(false);
JButton whiteButton = new JButton("White");
whiteButton.addActionListener(this);
JButton blueButton = new JButton("Blue");
blueButton.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
buttonPanel.add(redButton);
buttonPanel.add(whiteButton);
buttonPanel.add(blueButton);
// Set up color panel
colorPanel = new JPanel();
colorPanel.setSize(200, 200);
// Set up main application frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(1, 2));
add(buttonPanel);
add(colorPanel);
JMenuBar menuBar = createJMenuBar();
setJMenuBar(menuBar);
}
private JMenuBar createJMenuBar() {
JMenuItem redMenuItem = new JMenuItem("Rot");
redMenuItem.addActionListener(this);
redMenuItem.setActionCommand("Red");
JMenuItem whiteMenuItem = new JMenuItem("Weiss");
whiteMenuItem.addActionListener(this);
JMenuItem blueMenuItem = new JMenuItem("Blau");
blueMenuItem.addActionListener(this);
JMenu colorMenu = new JMenu("Color");
colorMenu.add(redMenuItem);
colorMenu.add(whiteMenuItem);
colorMenu.add(blueMenuItem);
JMenuBar menuBar = new JMenuBar();
menuBar.add(colorMenu);
return menuBar;
}
private JButton createButton(String label, ActionListener listener) {
JButton button = new JButton(label);
button.addActionListener(listener);
return button;
}
public void actionPerformed(ActionEvent e) {
String button = e.getActionCommand();
if (button == "Red") {
colorPanel.setBackground(Color.RED);
} else if (button == "White") {
colorPanel.setBackground(Color.WHITE);
} else if (button == "Blue") {
colorPanel.setBackground(Color.BLUE);
}
}
public static void main(String[] args) {
ColorBox cb = new ColorBox();
cb.pack();
cb.setVisible(true);
}
}