这是我的问题,我无法使用鼠标移动Rectangle2D
变量rect
移动。我究竟做错了什么?也许我不明白MouseListener
是如何运作的。
public class CreppyRectangle extends JComponent {
private int viteza = 15;
private int yPosL = 100;
Rectangle2D rect;
Graphics2D g3d;
int lungimea = 40;
int latimea = 10;
int x = 0;
int y = 100;
public static void main(String[] args) {
new CreppyRectangle();
}
public CreppyRectangle() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
});
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
yPosL = e.getX();
repaint(x, e.getX(), latimea, lungimea);
System.out.println(e.getX());
}
});
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Testing");
final TestPane misha = new TestPane(Color.BLACK);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(misha);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private int xPos;
private int yPos;
private int size = 10 ;
private int xDelta = 5;
private int yDelta = 5;
public TestPane(Color foreground) {
setForeground(foreground);
Timer timer = new Timer(viteza , new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
xPos += xDelta;
yPos += yDelta;
if (xPos < 10) {
xPos = 10;
xDelta *= -1;
System.out.println(xDelta);
} else if (xPos + size > getWidth()) {
xPos = getWidth() - size;
xDelta *= -1;
} else if (yPos < 0) {
yPos = 0;
yDelta *= -1;
System.out.println(xDelta);
} else if (yPos + size > getHeight()) {
yPos = getHeight() - size;
yDelta *= -1;
}
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(500, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g3d = (Graphics2D) g.create();
rect = new Rectangle2D.Double(x, yPosL, latimea, lungimea);
g3d.draw(rect);
g3d.fill(rect);
g2d.setColor(getForeground());
g2d.drawRect(xPos, yPos, size, size);
g2d.fillRect(xPos, yPos, size, size);
g2d.dispose();
}
}
}
答案 0 :(得分:3)
基本上,你实际上从未向任何事物添加CreppyRectangle
,因此,没有任何东西可以监听鼠标事件。
你的设置有点奇怪。我不知道为什么你要从JComponent
延伸,当你应该把所有的逻辑都放在TestPane
此外,我认为你不想做yPosL = e.getX()
,我想你想尝试yPosL = e.getY()
而不是