我最近在java中创建了一个MakeDots类,当你拖动鼠标时,它会产生点(是的!)。我实现了一个MouseMotionListener。它工作正常。然后我添加了一些按钮来改变点的颜色。我为此添加了ActionListeners。一旦我这样做,颜色变化起作用,但我只能画在按钮的非常小的边界!为什么会这样?我如何解决它?如果您需要我发布我的代码,请在评论中说明,我会这样做。
CODE:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
public class MakeDots extends Applet implements MouseMotionListener{
private Graphics graphics = null;
private Color dotColor = Color.red;
private Button setRed;
private Button setPink;
private Button setPurple;
private Button clrBtn;
public void init() {
setRed = new Button("Red");
setPink = new Button("Pink");
setPurple = new Button("Purple");
clrBtn = new Button("Clear");
this.addMouseMotionListener(this);
this.add(setRed);
this.add(setPink);
this.add(setPurple);
this.add(clrBtn);
setRed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dotColor = Color.red;
}
});
setPink.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dotColor = Color.pink;
}
});
setPurple.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dotColor = new Color(80, 0, 80);
}
});
clrBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
clear();
}
});
}
public void paint(Graphics g) {
this.setSize(new Dimension(800, 600));
graphics = g.create();
clear();
}
public void drawDot(int x, int y) {
graphics.setColor(dotColor);
graphics.fillOval(x, y, 10, 10);
}
public void clear() {
Dimension d = this.getSize();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, d.width, d.height);
}
@Override
public void mouseDragged(MouseEvent e) {
int mouseX = e.getX();
int mouseY = e.getY();
drawDot(mouseX, mouseY);
}
@Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:4)
您可能想做的事情很少。
每次添加actionPerformed(...)
时都会失去写actionListener()
的做法。只需使用getActionCommand()
来检查触发事件的按钮。另外,创建一个Color()
的全局对象,并在actionPerformed()