2011-06-05 49 views
1

我是一名高中生,我正在为我的计算机科学课的最终项目工作。我的任务是制作一个简单的绘画应用程序,但是我遇到了一些问题。这些包括:当窗口大小调整时,被绘制的图像被擦除,并且我可以在窗口中绘制菜单。JFrame菜单正在绘制完毕,图形在JFrame上消失调整大小

我相信我正在绘制菜单,因为我正在使用JFrame本身的图形对象。但是我找不到任何替代品。我试图制作单独的组件,甚至使用BufferedImage,但我的尝试都没有成功。

这里是我的代码:

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.event.MouseEvent; 
import java.awt.event.MouseMotionListener; 

import javax.swing.*; 

public class Paint implements MouseMotionListener{ 

private JFrame window; 
private drawingComponent pComp; 
private int xPos; //xPos of mouse; 
private int yPos; //yPos of mouse; 
private Color color; // new color 
private JTextArea sizeBox; 

private int brushShape = 0; 

public static void main(String[] args) { 
    Paint paint = new Paint(); 
    paint.ImplementGUI(); 
} 

public Paint() { 
    this.pComp = new drawingComponent(); 
    this.window = new JFrame("JPaint"); 
    this.window.setSize(500, 500); 
    this.window.setVisible(true); 
    this.window.addMouseMotionListener(this); 
    this.window.add(this.pComp); 
} 

public void ImplementGUI() { 
    JMenuBar menu = new JMenuBar(); 
    JMenu brush = new JMenu("Brush Settings"); 
    JMenu brushShape = new JMenu("Shape"); 
    brush.setSize(100,100); 
    brush.add(brushShape); 
    menu.add(brush); 
    menu.setSize(window.getWidth(), 20); 
    menu.setVisible(true); 

    this.sizeBox = new JTextArea("Brush Size:"); 
    this.sizeBox.setText("20"); 
    brush.add(this.sizeBox); 

    this.window.setJMenuBar(menu); 
} 

public void mouseDragged(MouseEvent pMouse) { 
    if (pMouse.isShiftDown() == true) { 
     this.pComp.paint(this.window.getGraphics(), pMouse.getX(), pMouse.getY(), 
         window.getBackground(), Integer.parseInt(sizeBox.getText())); 
    } 
    else { 
     this.pComp.paint(this.window.getGraphics(), pMouse.getX(), pMouse.getY(), 
         color, Integer.parseInt(sizeBox.getText())); 
    } 
} 

public void mouseMoved(MouseEvent pMouse) { 
} 

} 

class drawingComponent extends JComponent { 
    public void paint(Graphics g, int x, int y, Color color, int size) { 
     g.setColor(color); 
     g.fillOval(x-(size/2), y-(size/2), size, size); // 10 is subtracted from 
     // coordinates so the mouse pointer is at the exact middle of the brush. 
    } 
} 

我怎样才能解决这个问题?

回答

0

切勿使用getGraphics()方法进行绘画。效果只是暂时的,因为你已经注意到了。

自定义绘画是通过覆盖paintComponent()方法而不是paint()方法来完成的。

有关如何在面板上绘制多个对象的几个示例,请参阅Custom Painting Approaches

0

camickr是对的。调整窗口大小时,ImplementGUI组件将重新绘制,因此将调用ImplementGUI.paintComponent()来重新绘制组件的整个表面,并且您在mouseDragged()中绘制的内容将会丢失。