import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Code8_2 extends JFrame{ public static void main(String[] args){ new Code8_2(); } public Code8_2(){ //画面の設定 setSize(500,500); setTitle("Java Programing"); setDefaultCloseOperation(EXIT_ON_CLOSE); //パネルを貼り付ける MyJPanel myJPanel= new MyJPanel(); Container c = getContentPane(); //コンテナの取得 c.add(myJPanel); //パネルを貼る setVisible(true); } public class MyJPanel extends JPanel{ //x座標の変換 public double x_change(double x, double width, double x_min, double x_max){ double new_x; new_x = (x - x_min)/(x_max - x_min) * width; return new_x; } //y座標の変換 public double y_change(double y, double height, double y_min, double y_max){ double new_y; new_y = (y - y_min)/(y_max - y_min) * height; new_y = height - new_y; return new_y; } public MyJPanel(){ } public void paintComponent(Graphics g) { Dimension d; // dを宣言 d=getSize(); g.setColor(new Color(255, 0, 0)); //軸の線分を書く g.drawLine(d.width/2,0,d.width/2,d.height); //y軸 g.drawLine(0,d.height/2,d.width,d.height/2);//x軸 //x軸の文字を書く g.drawString("x",d.width-20,d.height/2-20); g.drawString("y",d.width/2-20,10); g.setColor(Color.black); double x, step=2/100.0; int px1,py1,px2,py2; double x1,x2,y1,y2; //Draw Sin for (x=-3; x<3; x=x+step) { x1=x; y1=Math.sin(x); x2=(x+step); y2=Math.sin((x+step)); px1=(int) x_change(x1, d.width, -3,3); py1=(int) y_change(y1, d.height, -1,1); px2=(int) x_change(x2, d.width, -3,3); py2=(int) y_change(y2, d.height, -1,1); g.drawLine(px1,py1,px2,py2); } //Draw Cos g.setColor(Color.blue); for (x=-3; x<3; x=x+step) { x1=x; y1=Math.cos(x); x2=(x+step); y2=Math.cos((x+step)); px1=(int) x_change(x1, d.width, -3,3); py1=(int) y_change(y1, d.height, -1,1); px2=(int) x_change(x2, d.width, -3,3); py2=(int) y_change(y2, d.height, -1,1); g.drawLine(px1,py1,px2,py2); } } } }