我想使用applet绘制多行复选框以选择行的颜色。这是我的代码:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
public class PaintApplet extends Applet implements MouseMotionListener,ItemListener{
public void init() {
setLayout(new GridLayout(1, 0));
CheckboxGroup colorType = new CheckboxGroup();
red = new Checkbox("red", colorType, false);
red.addItemListener(this);
green = new Checkbox("green", colorType, false);
green.addItemListener(this);
blue = new Checkbox("blue", colorType, true);
blue.addItemListener(this);
//setLayout(new GridLayout(0, 1));
Panel p = new Panel();
add(p);
p.add(red);
p.add(green);
p.add(blue);
addMouseMotionListener(this);
}
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == red)
System.out.println("red");
else if (e.getSource()==green)
System.out.println("green");
else if (e.getSource()==blue)
System.out.println("blue");
}
public void mouseDragged(MouseEvent e) {
draw=true;
// X=new Vector<Integer>();
// Y=new Vector<Integer>();
X.add(e.getX());
Y.add(e.getY());
System.out.println("mouse is being dragged at location (" + e.getX() + ", " + e.getY() + ")");
DrawX.add(X.get(lastSize));
DrawY.add(Y.get(lastSize));
DrawX.add(X.get(X.size()-1));
DrawY.add(Y.get(Y.size()-1));
repaint();
lastSize=X.size();
//System.out.println(lastSize);
}
public void mouseMoved(MouseEvent e) {
//System.out.println("mouse is being moved at location (" + e.getX() + ", " + e.getY() + ")");
}
public void paint(Graphics g) {
for(int i=0;i<X.size()-1;i=i+2)
{
initX=DrawX.get(i);
initY=DrawY.get(i);
finalX=DrawX.get(i+1);
finalY=DrawY.get(i+1);
//g.drawLine(0, 0, 100, 100);
if(draw)
g.drawLine(initX, initY, finalX, finalY);
g.setColor(Color.blue);
//System.out.println(initX);
//System.out.println(finalY);
}
super.paint(g);
//repaint();
}
int lastSize=0;
int initX,initY;
int finalX,finalY;
Vector<Integer> X=new Vector<Integer>();
Vector<Integer> Y=new Vector<Integer>();
boolean draw=false;
Vector<Integer> DrawX=new Vector<Integer>();
Vector<Integer> DrawY=new Vector<Integer>();
Checkbox red,green,blue;
}
然而,代码的问题在于,当正确显示复选框时,拖动鼠标时无法绘制线条,但在删除复选框时,线条绘制功能正常工作。我实现MouseMotionListener和ItemListener时有什么问题吗?
答案 0 :(得分:0)
您可以尝试将两个侦听器放在两个separeted线程中。 Here is how to set up a thread
使用这种方法,两个侦听器可以分别同时工作,因此它们不会相互阻塞。