我有一个包含以下内容的输入 file-file.txt
M1 100 100 400.89 400.72 400 400 450.89 450.72
M2 100 100 440.56 440.82
M3 100 200 300.52 330.75
200 200 320.53 340.34
300 300 400.43 350.25
我编写了一个程序来绘制一个矩形。但是我无法同时为 M1、M2 和 M3 绘制它。每行中的四个双精度值代表一个矩形的 2 个坐标。如果我的文件是
M1 = [ 100 100 400.89 400.72;
400 400 450.89 450.72 ]
M2 = [100 100 440.56 440.82 ]
M3 = [100 200 300.52 330.75;
200 200 320.53 340.34;
300 300 400.43 350.25]
我写的代码是:
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
import java.math.*;
import java.text.DecimalFormat.*;
class Rectangles extends JComponent
{
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
try
{
File x=new File("file.txt");
Scanner sc=new Scanner(x);
while(sc.hasNext())
{
String s=sc.next();
if(s.equals("M1"))
{
while(sc.hasNext())
{
double x1=sc.nextDouble();
double y1=sc.nextDouble();
double x3=sc.nextDouble();
double y3=sc.nextDouble();
double x2=x3;
double y2=y1;
double x4=x1;
double y4=y3;
double a=x1;
double b=y1;
double c1=Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
double d1=Math.sqrt((x4-x1)*(x4-x1)+(y4-y1)*(y4-y1));
double c=c1;
double d=d1;
g2.setPaint(Color.blue);
g2.draw(new Rectangle2D.Double(a,b,c,d));
g2.fill(new Rectangle2D.Double(a,b,c,d));
}
}
}}
catch(Exception e)
{
System.out.println("reported Exception");
}
}
}
public class eighth
{
public static void main(String[] args)throws IOException
{
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(60, 60, 900, 900);
window.getContentPane().add(new Rectangles());
window.setVisible(true);
}
}
如何同时画出M1、M2、M3型的三个矩形?