import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Code8_2_impove extends JFrame{ public static void main(String[] args){ new Code8_2_impove(); } public Code8_2_impove(){ //画面の設定 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 px,py, last_px,last_py; double x1,x2,y1,y2; last_px=-1; last_py=-1; //Draw Sin for (x=-3; x<3; x=x+step) { x1=x; y1=Math.sin(x); px=(int) x_change(x1, d.width, -3,3); py=(int) y_change(y1, d.height, -1,1); if (last_px > 0){ g.drawLine(last_px,last_py,px,py); } last_px = px; last_py = py; } //Draw Cos g.setColor(Color.blue); last_px=-1; last_py=-1; for (x=-3; x<3; x=x+step) { x1=x; y1=Math.cos(x); px=(int) x_change(x1, d.width, -3,3); py=(int) y_change(y1, d.height, -1,1); if (last_px>0){ g.drawLine(last_px,last_py,px,py); } last_px = px; last_py = py; } } } }