Search code examples
javaswingjframejbuttonactionlistener

Closing a JFrame using a button in eclipse


I'm a rookie when it comes to programming. We have this project about a log-in profile account. I just started doing it; and I came across a specific problem. I want to close a frame using a button.

buttonenter.setText("Enter");
     buttonenter.addActionListener(new ActionListener (){
       public void actionPerformed (ActionEvent ae){

           }
    });

I tried placing my frame.dispose();, set.Visible(false) etc. but i just got an error. I don't quite get. I really appreciate the help! Thank you!


Solution

  • Here's a simple example of what you're trying to do. What errors are you receiving?

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        JButton btnClose = new JButton("CLOSE");
        btnClose.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frame.setVisible(false);
            }
        });
        frame.getContentPane().add(btnClose, BorderLayout.NORTH);
    }