How to create Jpanel dynamically?

1

Good morning, please, I need help on this ... I have a Jframe that contains a jpanel inside ... my idea is that by means of a button arraylist that will be loaded when executing this jframe, they will be shown in the jpanel, but only 3 buttons ... if I have more than 3 buttons, I want it to be in another jpanel, but that these are not visible until in a "next" button For example if I have 8 buttons in my arraylist, in the panel of the frame I should show the first 3, the 3 following in a second panel and the 2 remain in a third panel, I just want you to see them when you first "next" I just need someone to help me in how to generate these panels, since my list can have n elements and therefore I would also need n panels inside the panel that I have, the positions the buttons and I have everything, just this I have no problem.

    
asked by Alvaro Machado 05.12.2017 в 07:38
source

1 answer

0

I'm going to pass you two codes to see if you can use one with the intention of finding the solution more easily.

The first:

Itera on a List and separates into groups of three buttons, once you read the three buttons perform a certain action, which in this case you should think the extra logic that would be the creation and adherence of the same to a JPanel to the JFrame.

In this case, I only made an impression of the text of each button appear on the console.

For me it is really complex to understand, even to apply. Find an alternative solution I think it is a better option.

Once you give Run as java application, watch the behavior of the List < > items on the console.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Panel {
    private List<JButton> buttons = new ArrayList<>();
    private JButton button1, button2, button3, button4, button5, button6, button7, button8, button9;
    private JFrame frame;
    private JPanel panel;

    public Panel() {

        button1 = new JButton("Boton1");
        button2 = new JButton("Boton2");
        button3 = new JButton("Boton3");
        button4 = new JButton("Boton4");
        button5 = new JButton("Boton5");
        button6 = new JButton("Boton6");
        button7 = new JButton("Boton7");
        button8 = new JButton("Boton8");
        button9 = new JButton("Boton9");
        buttons = Arrays.asList(button1, button2, button3, button4, button5, button6, button7, button8, button9);

        frame = new JFrame(); // Frame
        panel = new JPanel(); // Panel
        frame.add(panel); // Agregamos el panel al frame

        /* Cominezo de la aplicación del método que itera */
        int startIndex = 0;
        int items = 3;

        while (startIndex < buttons.size()) {
            buttonsByParts(buttons, startIndex, items);
            startIndex += items;

            /* Adherimos en este panel las posiciones 0,1,2 de la List<> */
            for (int i = 0; i < 3; i++) {
                panel.add(buttons.get(i));
            }

        }

        /* Configuración básica */
        frame.setTitle("JTextField");
        frame.setBounds(160, 160, 300, 300);
        frame.setVisible(true);

    }

    public static void buttonsByParts(List<JButton> buttons, int startIndex, int items) {

        if (buttons != null && startIndex >= 0 && startIndex < buttons.size()) {

            // recorro desde el indice inicial indicado mientras no haya llegado al final de
            // la lista ni haya impreso la cantidad deseada de elementos
            while (startIndex < buttons.size() && items > 0) {

                // imprimo boton
                System.out.println(buttons.get(startIndex).getText());

                // incremento el indice de recorrida
                startIndex++;

                // decremento la cantidad de items restantes a imprimir
                items--;
            }
        }
        System.out.println("");
    }

    /* Método inicializador de App */
    public static void main(String[] args) {
        /* Creamos el panel con el setVisible() en su constructor */
        Panel p = new Panel();
    }

}

The second one:

I find it simpler to apply, JPanel creations are not automated but it is a simple way to create a panel from a button. If you want to create more panels that contain more buttons, the only thing you have to do is add the code to the addActionListener () method.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Panel {

    private JButton next;
    private JFrame frame;
    private JPanel panel;

    public Panel() {

        next = new JButton("Siguiente");
        frame = new JFrame(); // Frame
        panel = new JPanel(); // Panel
        panel.add(next); // Adherimos el boton al panel
        frame.add(panel); // Agregamos el panel al frame

        next.addActionListener(event -> {
            JFrame frame2 = new JFrame();
            frame2.add(newPanel());
            frame2.setBounds(150, 150, 300, 300);
            frame2.setVisible(true);
        });


        /* Configuración básica */
        frame.setTitle("JTextField");
        frame.setBounds(160, 160, 300, 300);
        frame.setVisible(true);

    }


    /* Método inicializador de App */
    public static void main(String[] args) {
        /* Creamos el panel con el setVisible() en su constructor */
        Panel p = new Panel();
    }

    /* Creamos un método que devuelva un JPanel armado */ 
    public JPanel newPanel() {
        List<JButton> listButtons = new ArrayList<>();
        JButton button1 = new JButton("boton1");
        JButton button2 = new JButton("boton2");
        JButton button3 = new JButton("boton3");
        listButtons = Arrays.asList(button1, button2, button3);
        JPanel panel = new JPanel();

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

        return panel;
    }

}
    
answered by 05.12.2017 в 17:47