2016-12-16 88 views
-1

所以我有一個在其中有一個BufferedImage的面板,並且我想在該圖像上畫一條線,將它重疊。在java中的圖像上繪製一條線

我曾嘗試下面的例子,我從谷歌發現,但它似乎並沒有工作:

public class Main { 
private JFrame frame = new JFrame(); 
private JLayeredPane lpane = new JLayeredPane(); 
private JPanel panel1 = new JPanel(); 
private JPanel panel2 = new JPanel(); 
public Main() 
{ 
    frame.setPreferredSize(new Dimension(600, 400)); 
    frame.setLayout(new BorderLayout()); 
    frame.add(lpane, BorderLayout.CENTER); 
    lpane.setBounds(0, 0, 600, 400); 
    panel1.add(image); 
    panel1.setBounds(0, 0, 600, 400); 
    panel1.setOpaque(true); 
    panel2.add(linedraw1); 
    panel2.setBounds(200, 100, 100, 100); 
    panel2.setOpaque(true); 
    lpane.add(panel1, new Integer(0), 0); 
    lpane.add(panel2, new Integer(1), 0); 
    frame.pack(); 
    frame.setVisible(true); 
} 


/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) { 
    new Main(); 
} 

} 

下面的代碼只是顯示一個空白的圖形用戶界面,我嘗試添加一個單獨的面板框,但當我這樣做時,只有新的面板顯示,沒有別的。 任何想法?

在此先感謝。

回答

0

創建一個擴展JPanel的自定義面板。在該面板中繪製圖像和線條,並將其添加到UI中。

下面是一個樣本,讓你開始

public class Main { 
    private JFrame frame = new JFrame(); 
    private JLayeredPane lpane = new JLayeredPane(); 
    private JPanel panel1 = new MyPanel("C:\\Users\\PATH\\Pictures\\Image.png"); 
    private JPanel panel2 = new JPanel(); 
    public Main() 
    { 
     frame.setPreferredSize(new Dimension(600, 400)); 
     frame.setLayout(new BorderLayout()); 
     frame.add(lpane, BorderLayout.CENTER); 
     lpane.setBounds(0, 0, 600, 400); 
     panel1.setBounds(0, 0, 600, 400); 
     panel1.setOpaque(true); 
//  panel2.add(linedraw1); 
     panel2.setBounds(200, 100, 100, 100); 
     panel2.setOpaque(false); 
     lpane.add(panel1, new Integer(0), 0); 
     lpane.add(panel2, new Integer(1), 0); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    // This is your custom panel 
    class MyPanel extends JPanel { 
     private static final long serialVersionUID = -4559408638276405147L; 
     private String imageFile; 

     public MyPanel(String imageFile) { 
      this.imageFile = imageFile; 
     } 
     @Override 
     protected void paintComponent(Graphics g) { 
      // Add your image here 
      Image img = new ImageIcon(imageFile).getImage(); 
      g.drawImage(img, 0, 0, this); 

      //Add your lines here 
      g.setColor(Color.black); 
      g.drawLine(0, 0, g.getClipBounds().width, g.getClipBounds().height); 
      g.setColor(Color.red); 
      g.drawLine(0, g.getClipBounds().height, g.getClipBounds().width, 0); 
     } 
    } 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     new Main(); 
    } 

}