import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Ellipse2D;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.TitledBorder;
public class ClipArea extends JFrame {
MyCanvas canvas;
JRadioButton clipButton, clipFurButton;
public ClipArea() {
super();
Container contentPane = getContentPane();
canvas = new MyCanvas();
contentPane.add(canvas);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
clipButton = new JRadioButton("Clip", true);
clipButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
canvas.clip = true;
canvas.clipFurther = false;
canvas.repaint();
}
});
clipFurButton = new JRadioButton("Clip Further");
clipFurButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
canvas.clipFurther = true;
canvas.repaint();
}
});
ButtonGroup group = new ButtonGroup();
group.add(clipButton);
group.add(clipFurButton);
panel.add(clipButton);
panel.add(clipFurButton);
contentPane.add(BorderLayout.SOUTH, panel);
// 4. Add a window listener to close the frame properly.
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
pack();
setVisible(true);
}
public static void main(String arg[]) {
new ClipArea();
}
}
class MyCanvas extends JPanel{
boolean clip = true;
boolean clipFurther = false;
MyCanvas() {
setSize(300, 300);
setBackground(Color.white);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
int w = getSize().width;
int h = getSize().height;
if (clip) {
Ellipse2D e = new Ellipse2D.Float(w / 4.0f, h / 4.0f, w / 2.0f,
h / 2.0f);
g2.setClip(e);
g2.setColor(Color.yellow);
g2.fillRect(0, 0, w, h);
}
if (clipFurther) {
Rectangle r = new Rectangle(w / 2, h / 2, w / 2, h / 2);
g2.clip(r);
g2.setColor(Color.green);
g2.fillRect(0, 0, w, h);
}
}
}
|