0

I wanted to create dynamic list of buttons using ArrayList. If I copy the method which is written AddButton in constructor , it works. However, If I run this method in ActionListener, it won't work. How do I resolve this ?

Code:

package HelloJFrame;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main extends JFrame implements ActionListener {

    private static final long serialVersionUID = 1L;
    private JTextField text1;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new Main().setVisible(true);

    }

    public Main() {
        super("Hello JFrame");// Set Title from JFrame constructor
        setSize(600, 600);
        setResizable(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        text1 = new JTextField(20);
        // text.setSize(200, 20);
        add(text1);

        JButton submit = new JButton("Add Button");

        submit.addActionListener(this);
        submit.setActionCommand("ekle");

        add(submit);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        AddButton(2);
    }

    public void AddButton(int number) {
        ArrayList<JButton> buttons = new ArrayList<JButton>();
        for (int i = 0; i < number; i++) {
            buttons.add(new JButton("Button #" + i));
        }
        /*
         * JButton button = new JButton("Click!");
         * button.addActionListener(this); add(button);
         */

        for (int i = 0; i < buttons.size(); i++) {
            this.add(buttons.get(i));
        }
    }

}

1 Answer 1

2

After adding all the buttons to the frame you need to add

revalidate();
repaint();

to make sure the layout manager is invoked.

Also, method names should NOT start with an upper case character. "AddButton" should be "addButton".

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your response. It works fine. However I want to ask a question. Why shouldn't I start with an upper case ?
This is a Java convention. Have you ever seen a text book use an upper case character? Have you looked at the Java API and seen any methods that use upper case characters? Learn by example and don't make up you own conventions if you want other people to be able to read your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.