// // 2点を通る2次曲線 // // 2001/ 2/13 宍戸 輝光 // import java.awt.*; import java.awt.event.*; public class P2line extends java.applet.Applet implements ActionListener, MouseListener { TextField fa,fy,fp[]=new TextField[2]; Button btDraw,btClear; Panel p1,p2; Label la,lp,ly; double a,b,c; int np; Image img; Graphics g_img; Point pt[]=new Point[2]; boolean draw=false; public void init() { fa=new TextField(3); fa.setText("1"); fp[0]=new TextField(8); fp[1]=new TextField(8); fy=new TextField(18); la=new Label("a="); lp=new Label("Points"); ly=new Label("y="); btDraw=new Button("Draw!"); btDraw.addActionListener(this); btClear=new Button("Clear!"); btClear.addActionListener(this); p1=new Panel(); p1.add(la); p1.add(fa); p1.add(lp); p1.add(fp[0]); p1.add(fp[1]); p1.add(btDraw); p2=new Panel(); p2.add(ly); p2.add(fy); p2.add(btClear); setLayout((LayoutManager)null); add(p1); p1.setBounds(0,408,400,31); add(p2); p2.setBounds(0,440,400,31); img=createImage(100,100); g_img=img.getGraphics(); pt[0]=new Point(); pt[1]=new Point(); addMouseListener(this); clear(); } private void clear() { pt[0].x=999; pt[1].x=999; np=0; draw=false; repaint(); } public void mousePressed(MouseEvent e) {} public void mouseClicked(MouseEvent e) { // マウスクリック int x=(int)((e.getX()-4)/4); int y=(int)((e.getY()-4)/4); if (x<0 || x>99 || y<0 || y>99 || np>1) return; if (np==1 && pt[0].x==x-50) return; y=99-y; pt[np].x=x-50; pt[np].y=y-50; fp[np].setText(String.valueOf(pt[np].x)+","+String.valueOf(pt[np].y)); np++; repaint(); } public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void actionPerformed(ActionEvent e) { if (e.getSource()==btDraw) { // Drawボタン if (np!=2) return; draw=true; repaint(); } if (e.getSource()==btClear) { // Clearボタン clear(); } } private double func(double x) { // 2次曲線の関数 return a*x*x+b*x+c; } public void paint(Graphics g) { int x,y,xx,yy; double x1=pt[0].x,x2=pt[1].x,y1=pt[0].y,y2=pt[1].y; g_img.setColor(Color.white); g_img.fillRect(0,0,100,100); if (draw) { g_img.setColor(Color.red); // 入力されたaの値を取得 a=Double.valueOf(fa.getText()).doubleValue(); b=(y1-y2-a*x1*x1+a*x2*x2)/(x1-x2); c=y1-a*x1*x1-b*x1; if (c<0) // TextFiledに2次曲線の式を表示 fy.setText(String.valueOf(a)+"x2+"+String.valueOf(b) +"x"+String.valueOf(c)); else fy.setText(String.valueOf(a)+"x2+"+String.valueOf(b) +"x"+"+"+String.valueOf(c)); // 2次曲線を描画 xx=0; yy=99-((int)func(-50)+50); for (x=0;x<100;x++) { y=99-((int)func(x-50)+50); g_img.fillRect(x,y,1,1); if (Math.abs(yy)<10000) g_img.drawLine(xx,yy,x,y); xx=x; yy=y; } } g_img.setColor(Color.blue); for (int i=0;i<2;i++) // 指定された点を表示 if (pt[i].x!=999) g_img.fillRect(pt[i].x+50,99-(pt[i].y+50),1,1); g.drawImage(img,4,4,400,400,this); g.setColor(Color.gray); g.drawLine(4,204,404,204); g.drawLine(204,4,204,404); g.setColor(Color.black); g.drawRect(4,4,400,400); } }