当前位置: 代码迷 >> J2SE >> JPanel为什么不重绘?该如何解决
  详细解决方案

JPanel为什么不重绘?该如何解决

热度:111   发布时间:2016-04-24 16:36:53.0
JPanel为什么不重绘?
/**
  *  
  */
package   test;

import   java.awt.Container;
import   java.awt.Dimension;
import   java.awt.Graphics;
import   java.awt.Graphics2D;
import   java.awt.Toolkit;
import   java.awt.event.MouseEvent;

import   java.awt.event.MouseMotionListener;
import   java.awt.geom.Line2D;
import   java.awt.geom.Point2D;

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

/**
  *   @author   zjy
  *  
  */
public   class   CrossTest   {

/**
  *   @param   args
  */
public   static   void   main(String[]   args)   {
//   TODO   自动生成方法存根
CrossFrame   frame   =   new   CrossFrame();
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);

}

}

class   CrossFrame   extends   JFrame   {
public   CrossFrame()   {
//   TODO   自动生成构造函数存根
Toolkit   tk   =   Toolkit.getDefaultToolkit();
Dimension   dm   =   tk.getScreenSize();
WIDTH   =   dm.width;
HEIGHT   =   dm.height;

setTitle( "CrossTest ");
setSize(WIDTH   /   2,   HEIGHT   /   2);
setLocation(WIDTH   /   4,   HEIGHT   /   4);

CrossPanel   panel   =   new   CrossPanel(WIDTH,   HEIGHT);
Container   con   =   getContentPane();
con.add(panel);

}

private   int   WIDTH;

private   int   HEIGHT;
}

class   CrossPanel   extends   JPanel   {
public   CrossPanel(double   w,   double   h)   {
//   TODO   自动生成构造函数存根
frameHeight   =   h;
frameWidth   =   w;

addMouseMotionListener(new   MouseCross());
setFocusable(true);
}

@Override
public   void   paint(Graphics   g)   {
//   TODO   自动生成方法存根
super.paintComponents(g);
Graphics2D   g2   =   (Graphics2D)   g;

Line2D   lineH,   lineV;
Point2D   PointH1,   PointH2,   PointV1,   PointV2;

PointH1   =   new   Point2D.Double(0.0,   y);
PointH2   =   new   Point2D.Double(frameWidth,   y);
lineH   =   new   Line2D.Double(PointH1,   PointH2);

PointV1   =   new   Point2D.Double(x,   0.0);
PointV2   =   new   Point2D.Double(x,   frameHeight);
lineV   =   new   Line2D.Double(PointV1,   PointV2);

String   str   =   "Current   Position   is: "   +   x   +   ', '   +   y;


g2.drawString(str,   10,   10);
g2.draw(lineV);
g2.draw(lineH);

}



private   double   x;

private   double   y;

private   double   frameWidth;

private   double   frameHeight;

private   class   MouseCross   implements   MouseMotionListener   {

public   void   mouseMoved(MouseEvent   event)   {
//   TODO   自动生成方法存根
x   =   event.getX();