Changing text on a JLabel from another class

后端 未结 1 791
栀梦
栀梦 2021-01-17 00:36

So, I have been trying to figure this out for a little bit and cannot figure out how to do it. I want one of my buttons in another class to change the text of a JLabel in th

相关标签:
1条回答
  • 2021-01-17 00:54

    First, add a getter with public access so your second class can access the field. Something like,

    public JLabel getError() {
         return error;
    }
    

    Or (as @MadProgrammer suggested in the comments, a mutator) like

    public void setError(String txt) {
         error.setText(txt);
    }
    

    Then modify your second class, and pass the instance of GUI to it in the constructor. Like,

    public class guessHandler implements ActionListener{
        private GUI gui;
        public guessHandler(GUI gui) {
            this.gui = gui;
        }
        public void actionPerformed(ActionEvent e) {
            gui.changePOS(4, 50, 0, 300, 20);
            gui.setError("HI from guessHandler.java");
        }
    }
    
    0 讨论(0)
提交回复
热议问题