2012-11-06 25 views
1

我有一個輸入文件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

我已經寫了一個程序,繪製rectangle.But我不能把它畫對於M1,M2和M3同時進行。每行中的四個double值表示矩形的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同時的三個矩形?

+2

沒有 '?'在那篇文章中。你的問題是什麼? –

+0

我的問題是如何同時繪製M1,M2和M3三個矩形 – rupa

+0

1)感謝您添加一個問題(但不要忘記添加'?')。 2)現在我看看問題和代碼,我建議你在一個'Rectangles'構造函數中建立'BufferedImage',將它作爲一個類屬性存儲,然後讀取/解析輸入文件並將它們繪製到圖像上。以「JLabel」顯示圖像。無需擴展任何內容,它可能會解決您的問題。 –

回答

2
  • 閱讀Filepaint(),準備在此之前,

  • 因爲paint()可能被解僱每秒幾次,然後FILEIO可以凍結整個GUI

    一)從MouseKeyBoard事件

    b)JComponent內部觸發事件,當需要repaint()

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

  • 把所有Char S IN到ListArrayList

  • 內部paintComponent()到循環內陣列通過使用Graphics2D.drawString()


  • 爲什麼有painting in JComponent困擾,就把StringJLabelJTextArea

  • 變化BackGround

  • JLabel必須setOpaque(true),因爲JLabel是透明

+0

您能否通過編寫您想要的建議來詳細解釋我。謝謝! – rupa

+0

任何人都可以寫代碼..? – rupa