我正在制作一些需要在屏幕上拖动对象的项目。在我的主课中,我有这样的听众
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
currentX = e.getX() - 10 ;
currentY = e.getY() - 5;
if(currentNote != null)
{
if(!editingMode)
{
graphics2D.setPaint(Color.BLACK);
currentNote.setParameters(currentX, currentY, NoteDrawing.SKIP_CHECK);
currentNote.paintComponent(graphics2D);
}
else
{
graphics2D.setPaint(Color.BLACK);
currentNote.setParameters(currentNote.getBallFromX(), currentY, NoteDrawing.SKIP_CHECK);
currentNote.paintComponent(graphics2D);
}
}
repaint();
}
})
现在在应该绘制的对象(扩展 JComponent)中,我有以下 PaintComponent 方法:
public void paintComponent(Graphics g) {
g.drawImage(bmoll,fromX, fromY,null);
g.drawLine(fromX, fromY, fromX + 30, fromY);
repaint();
}
参数设置方法:
public void setParameters(int x, int y) {
this.fromX = x;
this.fromY = y;
}
当我在对象上按下按钮然后拖动鼠标时,在paintComponent方法中绘制的线条被正确拖动,但图像却没有。该图像不为空 - 它以原始位置出现在屏幕上。如果我用不同的坐标复制行 g.drawImage(bmoll,fromX, fromY,null);
,它就会按照应有的方式在两个地方绘制。但是当我拖动鼠标时 - 它没有任何反应。如果有人对导致问题的原因有一些建议,我将不胜感激。
最佳答案
显然问题出在对象的构造函数中。在原始对象的创建中,程序调用:
public Bmoll(int startX, int startY)
{
this.fromX = startX;
this.fromY = startY;
this.inverted = false;
this.staff = Staff.getActiveStaff();
this.bmoll = GuiHelper.getImage(B_MOLL_FILE);
}
同时,在创建用于拖动的对象时,调用了空构造函数,因此图像对象 bmoll
为 null - 没有任何内容可绘制。
关于java - 拖动鼠标时图像未绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23651792/