
package com.han;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Graphics_5 extends JFrame {
public Graphics_5() {
// TODO Auto-generated constructor stub
getContentPane().add(new CanvasPanel());
}
class CanvasPanel extends JPanel {
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
Shape[] shapes = new Shape[4];
shapes[0] = new Ellipse2D.Double(5, 5, 100, 100);
shapes[1] = new Rectangle2D.Double(110, 5, 100, 100);
shapes[2] = new Rectangle2D.Double(15, 15, 80, 80);
shapes[3] = new Ellipse2D.Double(120, 15, 80, 80);
// g2.draw(shapes[0]);
// g2.draw(shapes[1]);
// g2.fill(shapes[2]);
// g2.fill(shapes[3]);
for (Shape shape : shapes) {
Rectangle2D bounds = shape.getBounds2D();
if (bounds.getWidth() == 80)
g2.fill(shape);
else
g2.draw(shape);
// 注意上面的if-else代码块如果有返回值则可以用三元运算符来代替
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Graphics_5 frame = new Graphics_5();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("JFrame");
frame.setSize(300, 200);
frame.setVisible(true);
}
}