I wanted to make a program with JFrame that would allow you to start and stop a JLabel from being updated with the most recent coordinate of the mouse cursor. I can't figure out what I have done wrong. Please help and be respectful. I'm new at Java so I can't help what dumb mistakes I've made.
Here is the code:
import java.awt.* ;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class PrintPos extends JFrame {
private static final long serialVersionUID = 7526472295622776147L;
public JButton startBtn;
public JButton stopBtn;
public static JLabel posLabelX;
public static JLabel posLabelY;
static boolean started=false;
public static void main(String args[]){
new PrintPos();
}
PrintPos() {
setLayout(new GridLayout(2,2));
startBtn = new JButton("Start");
stopBtn = new JButton("Stop");
posLabelY = new JLabel("X:");
posLabelX = new JLabel("Y:");
add(startBtn);
add(stopBtn);
add(posLabelX);
add(posLabelY);
setSize(200,150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
startBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
started = true;
while(started) {
PointerInfo inf = MouseInfo.getPointerInfo();
Point p = inf.getLocation();
posLabelX.setText(String.valueOf(p.x));
posLabelY.setText(String.valueOf(p.y));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
});
stopBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
started = false;
}
});
}
public static void getInfo() {
while(started) {
PointerInfo inf = MouseInfo.getPointerInfo();
Point p = inf.getLocation();
posLabelX.setText(String.valueOf(p.x));
posLabelY.setText(String.valueOf(p.y));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
}