2011-10-04 93 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以反映新的面板大小。然后将旧的缓冲图像绘制到新的图像上。当然,采用这种方法时,如果面板缩小然后再增长,数据将会丢失。