How do you resize a Jpanel inside a Jscrollpane automatically?

Asked

Viewed 1,056 times

0

After adding a greater amount of buttons than the JPanel support, I would like to update(increase the JPanel) automatically, how can I do this?

private JPanel contentPane;
private static int tamanho = 429;

public static void main(String[] args) 
{
    teste frame = new teste();
    frame.setVisible(true);
}

private static int qtButton = 0 ;

public teste() 
{
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 900, 500);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JScrollPane scroll = new JScrollPane();
    scroll.setBounds(10, 11, 464, 439);
    contentPane.add(scroll);

    JPanel panel = new JPanel();
    scroll.setViewportView(panel);
    panel.setLayout(null);

    panel.setPreferredSize(new Dimension(390, 1000));

    JButton adicionar = new JButton("Adicionar");
    adicionar.setBounds(481, 11, 134, 23);
    contentPane.add(adicionar);

    adicionar.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {
            gerarButton(panel);

        }
    });
}
public static void gerarButton(JPanel panel)
{
    JButton NewButton = new JButton("New button");
    NewButton.setBounds(10, 11 + (34 * qtButton), 425, 23);
    panel.add(NewButton);

    qtButton ++;

    tamanho = 11 + (34 * qtButton) + 50;

    if(qtButton == 16)
    {
    }

    panel.repaint();
}

As you can see in the image below, the last button is off the panel, and I would like that when that happens, I can resize the panel for it to increase in size, thus fitting the last button.

inserir a descrição da imagem aqui

  • Again? Creating duplicate won’t get your question answered any faster. Be patient. If no one answered, it is either because your question is not clear, or because no one who understands the subject saw the question yet.

  • @Diegof It’s not the same question, read it again. I ask you to create a project and test the code before you accuse me of duplicate.

  • It is the same doubt. And you still ask someone to do it for you, which is worse. And the code is no problem, I tested it here and the button is added and the scroll works normally.

  • In the other question I asked for help to DO the Scroll and in this question I asked for help to change the size of the Jpanel if the Jbuttons exceed the size of the same. I didn’t know that in this forum it was wrong to ask for an example for my best understanding, since I created the above code just to decrease the size of the question, instead of putting the code I’m actually using, I’m sorry.

  • When you add a very large amount of buttons, the last button comes out of the Jpanel and I would like to change the size of the Jpanel so that it fits all buttons instead of getting that blank when scrolling down.

  • Note: I ask you to give an example using the code above. - The way you wrote it, it implied that you want someone to do it for you, not that it’s forbidden, but asking them to do it for you is not well regarded. And I tested the code the way you added it, it didn’t give this "whitespace" problem. Maybe the problem is the rendering of your IDE.

  • I’ll put an image explaining exactly my problem.

  • I haven’t seen the problem yet, that spacing is the same as between the buttons.

Show 4 more comments

1 answer

1


I made some changes to your code, all the changes are commented. In short, to automatically arrange the buttons on JPanel, it was necessary to configure a Layout Manager, chose the BoxLayout for meeting the vertical alignment of the buttons, as you reported in the question:

import java.awt.*;
import javax.swing.*;

public class Teste extends JFrame {

    private JPanel contentPane;
    private static int tamanho = 429;

    public static void main(String[] args) {
        Teste frame = new Teste();
        frame.setVisible(true);
    }

    private static int qtButton = 0;

    public Teste() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 900, 500);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JScrollPane scroll = new JScrollPane();
        //aqui eu isolo a localização do scrollpane
        scroll.setLocation(10, 11);
        contentPane.add(scroll);
        //alterei pra final para que fosse possivel
        //chamar o componente dentro da classe anonima
        //do actionPerformed
        final JPanel panel = new JPanel();
        //aqui defino um boxlayout, e a forma de alinhamento
        //dos componentes, no caso, somente em vertical
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setSize(new Dimension(464, 439));
        //adicionar borda transparente ao painel
        //defini right e left pros botoes não ficarem
        //colados na borda
        panel.setBorder(new EmptyBorder(0, 5, 0, 5));
        scroll.setViewportView(panel);
        //vincula o tamanho do panel pro tamanho do scroll
        scroll.setSize(panel.getSize());

        JButton adicionar = new JButton("Adicionar");
        adicionar.setBounds(481, 11, 134, 23);
        contentPane.add(adicionar);

        adicionar.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                gerarButton(panel);

            }
        });
    }

    public static void gerarButton(JPanel panel) {
        JButton NewButton = new JButton("New button");
        //pro botão ficar com tamanho maximo no BoxLayout
        // é preciso definir a dimensão maxima do botao
        //Integer.MAX_VALUE definir a maior largura possivel
        NewButton.setMaximumSize(new Dimension(Integer.MAX_VALUE, NewButton.getMinimumSize().height));
        //adicionei um espaçamento pro proximo botao não
        //ficar colado, você pode alterar a vontade
        panel.add(Box.createRigidArea(new Dimension(0, 5)));
        panel.add(NewButton);

        qtButton++;
        tamanho = 11 + (34 * qtButton) + 50;

        if (qtButton == 16) {
        }
        //o revalidate deve ser aplicado ao componente root
        //neste caso, o JFrame
        //pra evitar problemas com tamanho de outros containers
        //da tela
        panel.getRootPane().revalidate();
    }
}
  • Olà, and in case I want to add a border, so the boots don’t stick to themselves or to Jpanel, which method I would use ??

  • @Lucascarezia only add one EmptyBorder on the button panel, setting the right and left spacing. I updated the code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.