Ahmed Tawfik
Ahmed Tawfik

Reputation: 63

Can't add ActionListener in Java

Can you please help me with this code ? How can I make it that when the button is clicked, a second button appears? I've already added the actionlisteners and created the second button, but I can't seem to be able to do it. Thank you soooooooo much everyone!!!

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Skeleton extends JFrame implements ActionListener {
    
    public static void main(String[] args) {

        JFrame frame = new JFrame("Skeleton");
        JPanel panel = new JPanel();
        JButton button = new JButton("This is a button.");
        JButton button2 = new JButton("Hello");

        frame.setSize(600,600);
        frame.setResizable(false);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        
        frame.setContentPane(panel);
        panel.setLayout(new FlowLayout());
        panel.add(button);        
    }

    public void actionPerformed(ActionEvent e) {

        panel.add(button2); //Whenever I compile with this line 
                            //of code inserted, it tells
                            //me cannot find Button 2 
    }    
}

Thanks again!

Upvotes: 0

Views: 3844

Answers (1)

Sammy Guergachi
Sammy Guergachi

Reputation: 2006

Your code has many issues. First you can't create/build your UI in the main() method you need to create an instance of the class and call the method from there.

Also for you to be able to refer to panel and button2 you need to make them class objects not local objects inside the UI method.

And you need to at the very least add the ActionListener to the button

Finally you just need to call panel.revalidate() for the panel to show the added button:

    public class Skeleton extends JFrame implements ActionListener {

    public static void main(String[] args) {

        new Skeleton().buildUI();
    }

    JPanel panel;
    JButton button2;

    public void buildUI() {

        JFrame frame = new JFrame("Skeleton");
        panel = new JPanel();
        JButton button = new JButton("This is a button.");
        button2 = new JButton("Hello");

        frame.setSize(600, 600);
        frame.setResizable(false);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);

        frame.setContentPane(panel);

        panel.setLayout(new FlowLayout());
        panel.add(button);

        button.addActionListener(this);

        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {

        panel.add(button2); 
        panel.revalidate();

    }
  }

Upvotes: 1

Related Questions