用户点击一个位置并在另一个位置发布。我使用点击开始的位置和结束的位置来制作两个坐标。这就是我想要得到的矩形的宽度和高度,以便满足drawRect()方法的所有参数。我想让他们制作的矩形出现在屏幕上。它显示宽度和高度,但不创建矩形。
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.Timer;
@SuppressWarnings("serial")
public class PracticeClass extends Applet implements MouseListener, ActionListener, KeyListener
{
int x, y, velX, velY, Width, Height, x2, y2;
String tracer, tracer2, tracer3;
Timer tm = new Timer(4, this);
public PracticeClass()
{
tm.start();
setFocusable(true);
setSize(900, 900);
setFocusTraversalKeysEnabled(false);
addKeyListener(this);
addMouseListener(this);
}
public void mousePressed(MouseEvent e){}
public void mouseClicked(MouseEvent e)
{
x = e.getX();
y = e.getY();
tracer = " x = " + x + " y = " + y;
// repaint the applet//
repaint();
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseReleased(MouseEvent e)
{
int x2 = e.getX();
int y2 = e.getY();
int Width = x2 - x;
int Height = y2 - y;
tracer2 = "Width = " + Width + " Height = " + Height;
tracer3 = "X2 = " + x2 + " Y2 = " + y2;
repaint();
}
// paint method
public void paint(Graphics g){
g.drawString(tracer, 0, 20);
g.drawString(tracer2, 0, 40);
g.drawString(tracer3, 0, 60);
g.drawRect(x,y, Width, Height);
g.setColor(Color.BLUE);
}
public void actionPerformed(ActionEvent e)
{
if (x < 0)
{
velX = 0;
x = 0;
}
if (x > 470)
{
velX = 0;
x = 470;
}
if (y < 0)
{
velY = 0;
y = 0;
}
if (y > 470)
{
velY = 0;
y = 470;
}
x = x + velX;
y = y + velY;
repaint();
}
public void keyPressed(KeyEvent e)
{
int c = e.getKeyCode();
if (c == KeyEvent.VK_LEFT)
{
velX = -1;
}
if (c == KeyEvent.VK_RIGHT)
{
velX = 1;
}
if (c == KeyEvent.VK_UP)
{
velY = -1;
}
if (c == KeyEvent.VK_DOWN)
{
velY = 1;
}
repaint();
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e)
{
int c = e.getKeyCode();
if ((c == KeyEvent.VK_LEFT) || (c == KeyEvent.VK_RIGHT))
{
velX = 0;
}
if ((c == KeyEvent.VK_UP) || (c == KeyEvent.VK_DOWN))
{
velY = 0;
}
}
}
答案 0 :(得分:0)
g.drawRect(x, y, Width, Height)
在重新放入mouseReleased函数之前把它放好
你已经做了所有艰苦的工作,哈哈