import java.awt.*;
import javax.swing.*;
public class DrawingGraphics {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new GraphicComponent());
f.setSize(300,300);
f.setLocation(200,200);
f.setVisible(true);
}
}
class GraphicComponent extends JPanel {
DrawCircle drawCircle = new DrawCircle();
// Java supplies a graphics context which becomes available
// (non–null) when/after the component becomes visible.
protected void paintComponent(Graphics g) {
// Where does the graphics context it come from?
System.out.println("g = " + g.getClass().getName());
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Now we have a real, live graphics context that we
// can use for custom drawing/graphics.
// Draw a resizable, centered circle:
int w = getWidth();
int h = getHeight();
int diameter = 2*Math.min(w, h)/3;
int x = (w - diameter)/2;
int y = (h - diameter)/2;
drawCircle.drawCircle(g, x, y, diameter, Color.red);
}
}
class DrawCircle {
public DrawCircle() { }
public void drawCircle (Graphics page, int x, int y,
int rad, Color color) {
page.setColor(color);
page.drawOval(x, y, rad, rad);
}
public static void main(String[] args){
final DrawCircle circle = new DrawCircle();
JPanel panel = new JPanel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
circle.drawCircle(g,25,25,50,Color.blue);
}
};
panel.setPreferredSize(new Dimension(100,100));
JOptionPane.showMessageDialog(null, panel, "test", -1);
}
}