2011-10-04 43 views
0

所以,我的問題是,我的教授讓我們製作一個繪畫程序,在該程序中我們選取一個項目並在其上繪製。然而,問題在於他希望我們藉助緩衝圖像,然後在JPanel之上。JPanel的Java Buffered Image,ontop問題

截至目前幾乎所有的工作,你可以選擇我設置的按鈕之一,你可以繪製一個矩形和調整框架的大小。當你這樣做時,矩形的圖像不會消失,並且JPanel將延伸。然而,緩衝圖像不會擴展,你可以在代碼中看到,在我的paintComponent方法中,如果grid == null,我會製作一個緩衝圖像,如果它是,則它會創建一個圖像的寬度和高度。當我嘗試添加對此方法的調用時,由於網格不再等於null,所以不調整其大小。我不知道如何調用緩衝圖像的調整大小。

任何想法都會很棒!

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 

import javax.swing.JPanel; 
import java.awt.event.*; 
import java.awt.image.BufferedImage; 


/** 
* 
* @author Calvin Moss 
*/ 
public class Drawing extends JPanel implements MouseListener 
{ 

    public int x1, x2 ,y1, y2; 
    public static Drawing instance; 

    BufferedImage grid; 
    static Graphics2D gc; 

    Drawing() 
    { 
    setBackground(Color.RED); 
    addMouseListener(this); 
    } 

    public static Drawing getInstance() 
    { 
    if(instance == null) 
     instance = new Drawing(); 
    return instance;  
    } 

    public void paintComponent(Graphics g) 
    {  
    super.paintComponent(g); 
    Graphics2D g2 = (Graphics2D)g; 

    int w = Board.getInstance().getWidth(); 
    int h = Board.getInstance().getHeight(); 
    if(grid == null) 
    { 
     grid = (BufferedImage)(this.createImage(w,h)); 
     gc = grid.createGraphics(); 
     gc.setColor(Color.BLUE); 
     BufferedImage grid; 
     Graphics2D gc; 
    } 
    g2.drawImage(grid, null, 0, 0); 
    check(); 
    } 

    public void draw() 
    { 
    Graphics2D g = (Graphics2D)getGraphics(); 
    int w = x2 - x1; 
    if (w<0) 
     w = w *(-1); 
    int h = y2-y1; 
    if (h<0) 
     h= h*(-1); 

    switch(Main.choice) 
    {  
     case 1: 
     { 
     System.out.println("double gay"); 
     gc.drawLine(x1, y1, x2, y2); 
     repaint(); 
     break; 
     } 
     case 2: 
     { 
     check(); 
     System.out.println("quad gay"); 
     gc.drawRect(x1, y1, w, h); 
     repaint(); 
     break; 
     } 
    } 
    } 

    public void check() 
    { 
    if (x1 > x2) 
    { 
     int z = 0; 
     z = x1; 
     x1 = x2; 
     x2 =z; 
    } 
    if (y1 > y2) 
    { 
     int z = 0; 
     z = y1; 
     y1 = y2; 
     y2 = z; 
    } 
    } 

    public void mouseExited(MouseEvent e){} 
    public void mouseEntered(MouseEvent e){} 

    public void mouseClicked(MouseEvent e){ 
    System.out.println("Gay"); 
    } 

    public void mousePressed(MouseEvent evt) 
    { 
    x1 = evt.getX(); 
    y1= evt.getY(); 
    } 

    public void mouseReleased(MouseEvent evt) 
    { 
    x2 = evt.getX(); 
    y2 = evt.getY(); 
    draw(); 
    } 

} 

回答

1

使BufferedImage成爲桌面的大小,那麼您不必擔心調整大小。或者,將ComponentListener添加到面板。當組件調整大小時,創建一個新的BufferedImage以反映新的面板大小。然後將舊的緩衝圖像繪製到新的圖像上。當然,採用這種方法時,如果面板縮小然後再增長,數據將會丟失。