Search code examples
javaswingjpaneljbuttonjscrollpane

How to add a jbutton to a jpanel


I've trying (unsuccessfully) to add loop generated JButtons to a JPanel. The thing is that the JPanel is over JScrollPane. Here is my code:

String categoria = this.cmbCategoria.getSelectedItem().toString();
    String[] partidos = myEstadio.buscarPartidos(categoria).split("/");        
    JButton b;
    for(String p : partidos){
        b = new JButton(p);
        this.panelScroll.add(b, BorderLayout.CENTER);
        System.out.println(p);
        System.out.println(b.getLocationOnScreen());

As you can see, I'm printing the Label and the Button's location to be sure it exists.

It exists and the label too but it doesn't show up. The JPanel has a BorderLayout layout and I'm using NetBeans 8.0.2


Solution

  • In fact you are putting newly created Button instances to the same place. One over another. Use other layout constraints (such as NORTH, SOUTH, ...), a different LayoutManager or even better, nested LayoutManagers such as FlowLayout within BorderLayout. Moreover, you should add it to the JPanel.