Access GUI components from another class

前端 未结 5 2048
遇见更好的自我
遇见更好的自我 2020-12-06 15:34

I\'m new to Java and I\'ve hit a brick wall. I want to access GUI components (that have been created in one class) from another class. I am creating a new GUI class from one

5条回答
  •  有刺的猬
    2020-12-06 15:42

    First respect encapsulation rules. Make your fields private. Next you want to have getters for the fields you need to access.

    public class GUI {
        private JTextField field = new JTextField();
    
        public GUI() {
            // pass this instance of GUI to other class
            SomeListener listener = new SomeListener(GUI.this);
        }
    
        public JTextField getTextField() {
            return field;
        }
    }
    

    Then you'll want to pass your GUI to whatever class needs to access the text field. Say an ActionListener class. Use constructor injection (or "pass reference") for the passing of the GUI class. When you do this, the GUI being referenced in the SomeListener is the same one, and you don't ever create a new one (which will not reference the same instance you need).

    public class SomeListener implements ActionListener {
        private GUI gui;
        private JTextField field;
    
        public SomeListener(GUI gui) {
            this.gui = gui;
            this.field = gui.getTextField();
        }
    }
    

    Though the above may work, it may be unnecesary. First think about what exactly it is you want to do with the text field. If some some action that can be performed in the GUI class, but you just need to access something in the class to perform it, you could just implement an interface with a method that needs to perform something. Something like this

    public interface Performable {
        public void someMethod();
    }
    
    public class GUI implements Performable {
        private JTextField field = ..
    
        public GUI() {
            SomeListener listener = new SomeListener(GUI.this);
        }
    
        @Override
        public void someMethod() {
             field.setText("Hello");
        }
    }
    
    public class SomeListener implements ActionListener {
        private Performable perf;
    
        public SomeListener(Performable perf) {
            this.perf = perf;
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            perf.someMethod();
        }
    }
    

提交回复
热议问题