JAVA JPanel会在调整大小时擦除图形

时间:2018-09-06 17:11:31

标签: java swing

我是一名学生,正在从事一项以讲师给班级的代码开头的作业。这不是分配的一部分,但是我注意到的一点是,当调整应用程序的大小或隐藏应用程序然后将其带回到其他窗口的前面时,面板上绘制的图形消失了。为什么会这样?

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication16;

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class JavaApplication16  extends JPanel{

/**
 * Keeps track of the last point to draw the next line from.
 */
private Point lastPoint;

/**
 * Constructs a panel, registering listeners for the mouse.
 */
public JavaApplication16() {
    // When the mouse button goes down, set the current point
    // to the location at which the mouse was pressed.
    addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            lastPoint = new Point(e.getX(), e.getY());
        }
    });

    // When the mouse is dragged, draw a line from the old point
    // to the new point and update the value of lastPoint to hold
    // the new current point.
    addMouseMotionListener(new MouseMotionAdapter() {
        @Override
        public void mouseDragged(MouseEvent e) {
            Graphics g = getGraphics();
            g.drawLine(lastPoint.x, lastPoint.y, e.getX(), e.getY());
            lastPoint = new Point(e.getX(), e.getY());
            g.dispose();
        }
    });
}

/**
 * A tester method that embeds the panel in a frame so you can
 * run it as an application.
 * @param args
 */
public static void main(String[] args) {
    JFrame frame = new JFrame("Simple Sketching Program");
    frame.getContentPane().add(new JavaApplication16(), BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
}
} 

0 个答案:

没有答案