CSE190L Sample Event Program handout #7
Driver class ColorsMain.java
----------------------------
// Driver class that launches the application
public class ColorsMain {
public static void main(String[] args) {
ColorsFrame frame = new ColorsFrame();
frame.start();
}
}
Panel class ColorsPanel.java
----------------------------
// This class draws a colored panel with some text in it.
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class ColorsPanel extends JPanel {
private boolean textIsBlack;
public ColorsPanel() {
textIsBlack = true;
}
// switches the color uses for the text
public void switchTextColor() {
textIsBlack = !textIsBlack;
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if (textIsBlack)
g2.setPaint(Color.BLACK);
else
g2.setPaint(Color.WHITE);
g2.drawString("Hello world!", 50, 50);
}
}
Frame class ColorsFrame.java
----------------------------
// This class sets up the user interface controls for a program that controls
// a panel with text in it. The user is given buttons to change the panel's
// background color and when the user clicks on the panel, it switches the
// text color.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ColorsFrame {
private JFrame frame;
private ColorsPanel panel;
public ColorsFrame() {
frame = new JFrame();
frame.setTitle("Colorsday fun");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// construct panel and set up a mouse listener to switch its text
// color when the user clicks on the panel
panel = new ColorsPanel();
panel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
panel.switchTextColor();
}
});
frame.add(panel, BorderLayout.CENTER);
// add the panel of buttons at the top of the frame
frame.add(buttonPanel(), BorderLayout.NORTH);
}
public void start() {
frame.setVisible(true);
}
// constructs and returns a panel with three buttons that change the
// background color of the panel.
private JPanel buttonPanel() {
JPanel result = new JPanel();
result.add(makeButton("Yellow", Color.YELLOW));
result.add(makeButton("Blue", Color.BLUE));
result.add(makeButton("Red", Color.RED));
return result;
}
// constructs and returns a JButton with the given text that when pressed
// will set the background color of the panel to the given color
private JButton makeButton(String text, final Color c) {
JButton button = new JButton(text);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.setBackground(c);
}
});
return button;
}
}