same code but add method to auto move instead by hand drag, move slowly from center to…
- User
same code but add method to auto move instead by hand drag, move slowly from center to top right corner: this was your code: public DragLabelExample() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle(“Drag Label Example”);
// Create a panel to hold the label and add it to the frame JPanel panel = new JPanel(); panel.setLayout(null); // This allows us to position components manually add(panel); // Create a label to drag around and add it to the panel label = new JLabel(“Drag me!”); label.setBounds(200, 200, 100, 30); panel.add(label); // Add a mouse listener to the label to handle drag events label.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { // Remember where the mouse was clicked relative to the label mouseX = e.getX(); mouseY = e.getY(); // Remember the label’s current position labelX = label.getX(); labelY = label.getY(); // Start dragging dragging = true; } public void mouseReleased(MouseEvent e) { // Stop dragging dragging = false; } }); // Add a mouse motion listener to the label to handle drag events label.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { if (dragging) { // Calculate the difference between the current mouse position and the position of the JLabel int dx = e.getX() - mouseX; int dy = e.getY() - mouseY; // Calculate the new position of the JLabel based on the mouse movement int newX = labelX + dx; int newY = labelY + dy; // Constrain the JLabel’s position to within the panel newX = Math.max(0, Math.min(panel.getWidth() - label.getWidth(), newX)); newY = Math.max(0, Math.min(panel.getHeight() - label.getHeight(), newY)); // Move the JLabel to its new position label.setLocation(newX, newY); // Remember the new position of the JLabel as the current position labelX = newX; labelY = newY; } } }); // Set the size of the frame and make it visible setSize(500, 500); setVisible(true); } public static void main(String[] args) { new DragLabelExample(); }}
- Assistant
- User
start all over again: show how to auto move a jLabel accross the JFrame: implemet the moveLabel method accurate
- Assistant
- User
moveLabel should run in a thread
- Assistant
- User
dont use swingworker, instead extends thread
- Assistant
- User
can you avoid the timer class ?
- Assistant