2011-11-10 72 views
1

我已經搜索了一點點,找到解決我的問題,沒有運氣。我會認爲那裏有一個簡單的解決方案。在下面的代碼中,我發現存儲在ArrayList中的點的數量很多,並且想要在ArrayList中給出的每個點處繪製一個形狀(在這個階段矩形將執行的操作並不重要)。代碼如下:在JPanel已知座標上畫一個形狀

public static void main(String[] args){ 
     image = null; 
     try { 
      // Read from a file 
      File file = new File("box.jpg"); 
      image = ImageIO.read(file); 
     } catch (IOException e) { 
      System.out.print("LAAAAMMME!!!!"); 
     } 

     ImagePanel panel = new ImagePanel(image); //Custom JPanel to show a background image 
     panel.setPreferredSize(new Dimension(500, 500)); 

     JFrame frame = new JFrame("Find the Squares"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(500, 500); 
     frame.setResizable(false); 
     frame.setLocationRelativeTo(null); 
     frame.getContentPane().add(panel); 

     frame.validate(); 
     frame.setVisible(true); 
     frame.pack(); 


     ArrayList<Point> points = getCenterPoint(floatarray); 
     for(int x = 0 ; x < points.size(); x++){ 
      //Here I guess is where each point is created and drawn. 
     } 
    } 

有什麼建議嗎?

+0

*「有什麼建議嗎?」*爲了更快地獲得更好的幫助,請將該代碼升級到[SSCCE](http://sscce.org/)。 –

+0

* //這裏我猜是每個點被創建和繪製的地方。*在這裏,我猜你應該在哪裏做[2D Graphics Trail](http://download.oracle.com/javase/tutorial/2d/index。 html)的Java教程。 –

回答

1

將屬性List<Point> list添加到ImagePanel

覆蓋在ImagePanel。使用屬性list中的數據進行繪製。

@Override 
protected void paintComponent(Graphics g) { 
    super.paintComponent(g); 

    g.drawRect(...); 
} 

發送列表從JFrameImagePanel

您可能必須在構建框架後調用frame.setLayout(new FlowLayout())

+0

非常感謝你! – SamRowley

1
class MyTest{ 
public static void main(String[] args){ 
    image = null; 
    try { 
     // Read from a file 
     File file = new File("box.jpg"); 
     image = ImageIO.read(file); 
    } catch (IOException e) { 
     System.out.print("LAAAAMMME!!!!"); 
    } 

    ImagePanel panel = new ImagePanel(image); //Custom JPanel to show a background image 
    panel.setPreferredSize(new Dimension(500, 500)); 

    JFrame frame = new JFrame("Find the Squares"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(500, 500); 
    frame.setResizable(false); 
    frame.setLocationRelativeTo(null); 
    frame.getContentPane().add(panel); 
    frame.add(new MainPanel(Color.Red)); 
    frame.validate(); 
    frame.setVisible(true); 
    frame.pack(); 
    /*ArrayList<Point> points = getCenterPoint(floatarray); 
    for(int x = 0 ; x < points.size(); x++){ 
     //Here I guess is where each point is created and drawn. 
    }*/ 
} 
private class MainPanel extends JPanel { 
    Color color; 

    public MainPanel(Color color) { 
     this.color = color; 
    } 

    public void paintComponent(Graphics g) { 
     int width = getWidth(); 
     int height = getHeight(); 
     g.setColor(color); 
     //g.drawRect(startx,starty,endx,endy); // here you can drawRect as per your value 
    } 
} 
} 

檢查this網站

你需要的座標傳遞給mainPanel中類,所以你可以畫任何你想要繪製面板上的形狀。