我正在尝试创建一个绘制圣诞树的小程序,然后使用按钮,用户可以在树上绘制装饰(每个装饰的不同按钮)。
我有它,所以它会在树上画一个圆圈,但是当绘制一个新圆圈时,这个圆圈会消失。有人向我建议,装饰需要定义为具有变量的对象(例如鼠标点击坐标),然后每次单击鼠标时,都会将新实例添加到对象数组中。
首先,我正在尝试创建装饰或“球”对象并将其绘制到屏幕上,一旦我完成了这项工作,我将努力将其添加到数组中,到目前为止,它将绘制球但是在左上角和鼠标单击无效。
任何帮助或提示都会非常感激,它现在开始有点儿了!这是迄今为止的代码。 (我知道那里有一些无意义的代码,它来自之前尝试使其工作。)
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class christmasTree extends Applet implements ActionListener, MouseListener, MouseMotionListener
{
int[] xPoints = {200,50,350};
int[] yPoints = {35,400,400};
Button lights;
Button decorations;
Button stars;
int mx;
int my;
Object source;
ArrayList lightArray;
Ball ball;
public void init()
{
lights = new Button("Add Lights");
decorations = new Button("Add Decorations");
stars = new Button("Add Stars");
add(lights);
add(decorations);
add(stars);
addMouseListener( this );
addMouseMotionListener( this );
lights.addActionListener(this);
decorations.addActionListener(this);
lightArray = new ArrayList();
ball = new Ball();
}
public void paint (Graphics g)
{
super.paint(g);
g.setColor(Color.green);
g.fillPolygon(xPoints, yPoints, 3);
g.setColor(Color.black);
g.fillRect(175, 400, 50, 50);
g.drawString(Integer.toString(mx), 25, 85);
g.drawString(Integer.toString(my), 25, 100);
ball.display(g);
}
public void actionPerformed(ActionEvent ev)
{
if (ev.getSource() == lights){
source = lights;
}
if (ev.getSource() == decorations){
source = decorations;
}
repaint();
}
public void mousePressed(MouseEvent e)
{
mx = e.getX();
my = e.getY();
repaint();
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{}
public void mouseExited(MouseEvent e)
{}
public void mouseMoved(MouseEvent e)
{}
public void mouseClicked(MouseEvent e)
{
}
public void mouseDragged(MouseEvent e)
{}
}
class Ball implements MouseListener, MouseMotionListener
{
int mx1;
int my1;
public Ball()
{
}
public void display(Graphics g)
{
g.setColor(Color.yellow);
g.fillOval(mx1, my1, 20, 20);
}
public void mousePressed(MouseEvent e)
{
mx1 = e.getX();
my1 = e.getY();
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{}
public void mouseExited(MouseEvent e)
{}
public void mouseMoved(MouseEvent e)
{}
public void mouseClicked(MouseEvent e)
{
}
public void mouseDragged(MouseEvent e)
{}
}
由于
答案 0 :(得分:1)
通过添加:
来修复Ball
位置的坐标
public void setLocation(int x, int y) {
mx1 = x;
my1 = y;
}
(纯粹主义者可能选择 setX , setY 。)
否则,它们默认为0和0.(整数的Java默认值)
然后致电:
ball.setLocation(mx, my);
在MouseListener
。
此外,您可能希望创建多个Ball
装饰...因此在单击鼠标之前不要创建任何装饰。我将把它留作练习......! : - )