-1

the task i am trying to do is simple. I want to add JButtons to a panel in a vertical way, but using a loop to adding it, i tried to do it using .setBounds() and .setLocation() mehtod, but i dont have any results.

In a simple way, i want to do this but adding the buttons vertically and keeping the JScroll bar...:

  public class NewMain {

public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    frame.setLayout(null);
    for (int i = 0; i < 10; i++) {
        JButton asd=new JButton("HOLA "+i);
        asd.setLocation(i+20, i+20);
        panel.add(asd);
    }
    JScrollPane scrollPane = new JScrollPane(panel);
    scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    scrollPane.setBounds(50, 30, 300, 50);
    JPanel contentPane = new JPanel(null);
    contentPane.setPreferredSize(new Dimension(500, 400));
    contentPane.add(scrollPane);
    frame.setContentPane(contentPane);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setVisible(true);
}

1 Answers1

1
  1. Give the JPanel that holds the JButtons an appropriate layout manager that adds components in a vertical manner. A GridLayout(0, 1) would work, the parameters referring to 0 rows -- meaning variable number of rows, and 1 column. This will add the JButtons into a vertical grid, column of one
  2. Other possible solutions include BoxLayout and GridBagLayout, both of which are a little more complex than the GridLayout.
  3. Also avoid using null layouts as you're doing as this leads to inflexible GUI's painful debugging and changes.
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Thank you, i have used the first one, problem solved!. – Luis Enrique Bermúdez García May 27 '18 at 18:10
  • @LuisEnriqueBermúdezGarcía: you're welcome, but in the future, please search for this before asking as this has been asked many times before. Please see [this link](https://www.google.com/search?q=java+swing+add+components+vertically+site:stackoverflow.com) as an example search, and one of the best ways to use this site. – Hovercraft Full Of Eels May 27 '18 at 18:11