我在编程和Java方面几乎全新。我不明白为什么这不起作用。我的目标是填充Rectangle,然后用户按下鼠标,但它什么都不做。为什么? 我的主要课程:
package mousebandymas;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class Mousebandymas extends Applet{
boolean toFill = false;
public void init(){
super.init();
setSize(500,500);
setBackground(Color.RED);
this.addMouseListener(new MouseInsert());
}
public void paint(Graphics g){
g.setColor(Color.GREEN);
g.drawRect(100, 200, 100, 100);
g.drawRect(300, 200, 100, 100);
if (toFill == true){
g.fillRect(100, 200, 100, 100);
}
}
}
我的鼠标课程:
package mousebandymas;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class MouseInsert extends Mousebandymas implements MouseListener, MouseMotionListener{
public void mouseClicked(MouseEvent e) {
int mx = e.getX();
int my = e.getY();
if (mx > 1){
toFill = true; // *Here main problem, don't work*
repaint();
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
}
答案 0 :(得分:0)
您的MouseInsert不是Mousebandymas的内部类(顺便说一下,为什么要扩展Mousebandymas?),因此当您更改为填充时,您将更改其他一些toFill,而不是Mousebandymas中的那个。 你的意思是这样的:
package mousebandymas;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class Mousebandymas extends Applet{
boolean toFill = false;
public void init(){
super.init();
setSize(500,500);
setBackground(Color.RED);
this.addMouseListener(new MouseInsert());
}
public void paint(Graphics g){
g.setColor(Color.GREEN);
g.drawRect(100, 200, 100, 100);
g.drawRect(300, 200, 100, 100);
if (toFill == true){
g.fillRect(100, 200, 100, 100);
}
}
private class MouseInsert implements MouseListener, MouseMotionListener{
public void mouseClicked(MouseEvent e) {
int mx = e.getX();
int my = e.getY();
if (mx > 1){
toFill = true; // *Here main problem, don't work*
repaint();
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
}
}