Перетаскивание своего объекта - Java
Формулировка задачи:
Всем привет
Сразу к делу ...
Объект перетаскивается, но вот как-то нездорово. Что я сделал не так?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Test extends JFrame
{
Test ()
{
super("Тест моего компонента");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int width = 500, height = 400;
setBounds((1024 - width) / 2, (768 - height) / 2, width, height);
setLayout(null);//new FlowLayout(FlowLayout.LEFT));
MySquare ms = new MySquare ();
ms.setBounds(50, 50, 100, 100);
/*
ms.addMouseMotionListener(new MouseMotionAdapter ()
{
public void mouseDragged (MouseEvent e)
{
ms.setText("(" + e.getX() + ", " + e.getY() + ")");
}
});
*/
add(ms);
setVisible(true);
}
public static void main (String args [])
{
SwingUtilities.invokeLater(new Runnable ()
{
public void run ()
{
new Test ();
}
});
}
}import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MySquare extends JPanel
{
private String out;
private Point coordObj;
private Point coordCursor;
private boolean locked;
MySquare ()
{
setMinimumSize(new Dimension (100, 100));
setPreferredSize(new Dimension (100, 100));
locked = false;
addMouseMotionListener(new MouseMotionAdapter ()
{
public void mouseDragged (MouseEvent e)
{
if (locked)
{
setLocation(coordObj.x + e.getX() - coordCursor.x,
coordObj.y + e.getY() - coordCursor.y);
}
}
});
addMouseListener(new MouseAdapter ()
{
public void mousePressed (MouseEvent e)
{
coordObj = getLocation();
coordCursor = e.getPoint();
locked = true;
}
public void mouseReleased (MouseEvent e)
{
locked = false;
}
public void mouseExited (MouseEvent e)
{
locked = false;
}
});
out = "(null)";
repaint();
}
void setText (String text)
{
out = text;
repaint();
}
public void paintComponent (Graphics g)
{
g.setColor(Color.BLACK);
g.fillRect(0, 0, 100, 100);
g.setColor(Color.YELLOW);
g.setFont(new Font("Courier", Font.PLAIN, 14));
g.drawString(out, 10, 20);
}
}Решение задачи: «Перетаскивание своего объекта»
textual
Листинг программы
if (locked)
{
setLocation(coordObj.x + e.getX() - coordCursor.x,
coordObj.y + e.getY() - coordCursor.y);
coordObj = getLocation();
}