Access GUI components from another class

前端 未结 5 2064
遇见更好的自我
遇见更好的自我 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 16:08

    There is actually no need to use a class that implements ActionListener.

    It works without, what might be easier to implement:

    public class SomeActionListener {
    
    private Gui gui;
    private JButton button1;
    
        public SomeActionListener(Gui gui){
    
            this.gui  = gui;
            this.button1 = gui.getButton();
            this.button1.addActionListener(l -> System.out.println("one"));
        }
    
    }
    

    and then, like others have elaborated before me in this topic:

    public class GUI {
        private JButton button = new JButton();
    
        public GUI() {
            // pass this instance of GUI to other class
            SomeActionListener listener = new SomeActionListener(GUI.this);
        }
    
        public JButton getButton() {
            return button;
        }
    }
    

提交回复
热议问题