I'm a newbie here. I have a code here from which I would like to change the text of a JLabel to that of the position of a moving - mouse. Here is my code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class Draw extends JFrame{
int x;
int y;
String positions = "Positions: " + x + ", " + y;
JLabel positionsOnFrame = new JLabel(positions);
public class AL implements MouseMotionListener {
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
}
public void mouseDragged(MouseEvent e) {
positions += " dragged.";
}
}
//Constructor
public Draw() {
setTitle("Title");
setBackground(Color.BLACK);
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
addMouseMotionListener(new AL());
add(positionsOnFrame);
setVisible(true);
}
public static void main(String[] args) {
new Draw();
}
}
Side problem: The JFrame doesn't turn black as well even though I have set the color to be black from the constructor.
Any solution to the mouse problem? Nothing happens! The values are just set to 0! (I haven't initialized them, they're just automatically set to 0!). Help would definitely be appreciated!
First, uninitialized integers (such as x and y) are given a default value of zero. But it's not good practice to rely on this; best to explicitly initialize their values even if still zero.
Next, your mouseMoved() callback is in-fact getting called. But it's not updating the text of your 'positionsOnFrame' label, it's only updating the x and y coordinates. Just because you created the label with a String (positions), doesn't mean the label's text will automatically change whenever that String is changed. You have to change the text of the label accordingly. So adding positionsOnFrame.setText("Positions: " + x + "," + y); inside your mouseMoved() callback will fix that part.
Finally, change the color of the frame's content pane instead of the frame directly: getContentPane().setBackground(Color.BLACK);
Hope that helps!