Et modificeret eksempel i et GridLayout (ref:
http://eksperten.dk/spm/495415 )
import java.awt.*;
import java.awt.geom.*;
public class DrawGraf extends java.awt.Frame {
public DrawGraf() {
initComponents();
setSize(800,450);
}
private void initComponents() {
setLayout(new GridLayout(1,2));
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
drawArea = new DrawArea(Color.YELLOW);
add(drawArea);
drawArea2 = new DrawArea(Color.ORANGE);
add(drawArea2);
pack();
}
private void exitForm(java.awt.event.WindowEvent evt) {
System.exit(0);
}
public static void main(String args[]) {
new DrawGraf().show();
}
private javax.swing.JPanel buttonPanel;
private DrawArea drawArea, drawArea2;
// Her extender jeg class Canvas, kunne ligeså godt være class Panel
class DrawArea extends java.awt.Canvas{
public DrawArea(Color color){
xP = new int[]{100,125,150,200,250,280};
yP = new int[]{110,130,180,220,250,275};
xdP = new double[xP.length];
ydP = new double[xP.length];
for(int i = 0; i < xP.length; i++){
xdP[i] = (double)xP[i] + 10.25;
ydP[i] = (double)yP[i] + 10.25;
}
this.setBackground(color);
}
public void paint(Graphics g){
g.drawString("Y", 47, 45);
g.drawLine(50, 50, 50, 350); // line Y
g.drawString("X", 355, 354);
g.drawLine(50, 350, 350,350); // line X
for(int i = 50; i < 350; i += 50){
g.drawLine(47, i , 53, i);
g.drawLine(50+i, 353 ,50+ i, 347);
}
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.RED);
// Den lidt simple, med int
g2.drawPolyline(xP, yP, xP.length);
// Den lidt kringlede, med double
Line2D.Double d2 = new Line2D.Double();
g2.setColor(Color.GREEN);
for(int i = 0; i < xP.length - 1; i++){
d2.setLine(xdP[i], ydP[i], xdP[i + 1],ydP[i + 1]);
g2.draw(d2);
}
}
private int[] xP, yP;
private double[] xdP, ydP;
}
}