1

我有一个包含以下内容的输入 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型的三个矩形?

4

1 回答 1

2
  • File在外面阅读paint(),事先准备好,

  • 因为paint()每秒可以触发几次,然后 FIleIO 可以冻结整个 GUI

    a) 来自MouseKeyBoard事件

    b)在需要JComponent时在内部触发事件repaint()

  • 使用paintComponent()代替paint()_JComponent

  • 将所有Chars 放入Listor ArrayList,

  • 内部paintComponent()使用循环内部数组Graphics2D.drawString()


  • 为什么要打扰painting in JComponent,放在或StringJLabelJTextArea

  • 改变BackGround

  • for JLabelhave to setOpaque(true), 因为JLabel是透明的

于 2012-11-06T07:28:35.563 回答