Search code examples
javaswingsetjtextfield

Set JTextField auto changed


Have a problem, I have "yC" which will change all the time when user press alt + C

The question is how to make JTextField change the value inside every single time the value yC is changes.

yT=new JTextField(5);
mainframe.add(yT);
yT.setText(Integer.toString(yC));
window.getContentPane().add(mainframe);
window.pack();
window.setVisible(true);

How change the yC:

cor.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                PointerInfo a = MouseInfo.getPointerInfo();
                Point b = a.getLocation();
                xC = (int) b.getX();
                yC = (int) b.getY();
                textArea.replaceSelection("X-Coordinates:" + xC + "  Y-Coordinates: " + yC + "\n");
            }

        });

Solution

  • If yC and yT are in the same class, then your job got easier. Consider giving yC a setter method:

    public void setYC(int yC) {
       this.yC = yC;
       yT.setText(String.valueOf(yC));
    }
    

    And then never set yC directly, but instead always through its setter method.


    Edit
    One issue you have with your code you've linked to is here:

    public class Test {
    
       static JTextField curTimeH, curTimeM, curTimeS, xT, yT;
       Timer timer;
       Robot robot = new Robot();
       static JFrame window;
       static JPanel mainframe;
       static JFrame frameRes;
       static JTextArea textArea;
       static int xC, yC;
    

    All of the static fields above should be instance fields, or non-static fields. If you state that you did this because the compiler complained about "Cannot make a static reference to the non-static field window" or something similar, then I'll tell you that you fixed the wrong thing. The key is make key fields such as these instance fields that are used in instance sort of way and not in a static sort of way.