我用 Java 编写了一个小程序,允许用户设置背景颜色和“笔”颜色,然后单击并在窗口框架中绘制以绘制一条线。我通过在拖动鼠标的每个 x 和 y 点填充椭圆来设置这条线。我还允许用户使用 - 和 + 键通过增加或减少椭圆的半径来改变线条的大小。我的问题是线条的绘制有一些滞后的原因。我相信它在 mouseDrag 方法中,并且该方法的执行速度限制了绘制椭圆可以达到多少 x 和 y 点。有没有什么办法可以缓解这种滞后以提供更好的线路?
import java.applet.Applet;
import java.awt.Event;
import java.awt.Color;
import java.awt.Graphics;
public class Screen extends Applet
{
int x = -20, y = -20;
int height = 20, width = 20;
boolean black, blue, cyan, green, magenta, orange, pink, red, white, yellow;
public void init()
{
setSize(400,400);
setBackground(Color.white);
}
public void paint(Graphics g)
{
if (black == true)
g.setColor(Color.BLACK);
else if (blue == true)
g.setColor(Color.BLUE);
else if (cyan == true)
g.setColor(Color.CYAN);
else if (green == true)
g.setColor(Color.GREEN);
else if (magenta == true)
g.setColor(Color.MAGENTA);
else if (orange == true)
g.setColor(Color.ORANGE);
else if (pink == true)
g.setColor(Color.PINK);
else if (red == true)
g.setColor(Color.RED);
else if (white == true)
g.setColor(Color.WHITE);
else if (yellow == true)
g.setColor(Color.YELLOW);
g.fillOval(x, y, width, height);
}
public boolean mouseDrag(Event e, int xPos, int yPos)
{
x = xPos;
y = yPos;
paint(getGraphics());
return true;
}
public boolean keyDown(Event e, int key)
{
black = false;
blue = false;
cyan = false;
green = false;
magenta = false;
orange = false;
pink = false;
red = false;
white = false;
yellow = false;
if (key == 'n')
{
x =-20;
y =-20;
update(getGraphics());
}
else if (key == 'x')
black = true;
else if (key == 'b')
blue = true;
else if (key == 'c')
cyan = true;
else if (key == 'g')
green = true;
else if (key == 'm')
magenta = true;
else if (key == 'o')
orange = true;
else if (key == 'p')
pink = true;
else if (key == 'r')
red = true;
else if (key == 'w')
white = true;
else if (key == 'y')
yellow = true;
else if (key == '+')
{
height += 5;
width += 5;
}
else if (key == '-')
{
height += -5;
width += -5;
}
else if (key == 'X')
setBackground(Color.BLACK);
else if (key == 'B' )
setBackground(Color.BLUE);
else if (key == 'C')
setBackground(Color.CYAN);
else if (key == 'G')
setBackground(Color.GREEN);
else if (key == 'M')
setBackground(Color.MAGENTA);
else if (key == 'O')
setBackground(Color.ORANGE);
else if (key == 'P')
setBackground(Color.PINK);
else if (key == 'R')
setBackground(Color.RED);
else if (key == 'W')
setBackground(Color.WHITE);
else if (key == 'Y')
setBackground(Color.YELLOW);
return true;
}
}