0

I like to adding a scrollbar to a JPanel with FlowLayout but is impossible, I don't see the scrollbar.

I've tried a thousand different ways but I have not accomplished anything. I am fairly new to java and I have yet many failures so please be kind.

Here is my code:

//Creamos el panel que contendra los botones de cada producto diferente
package com.foolsrecords.tpv.tablaproductos.vista;

//Hacemos todas las importaciones necesarias
import com.foolsrecords.tpv.modelo.Producto;
import com.foolsrecords.tpv.modelo.eventos.ControladorEventListener;
import com.foolsrecords.tpv.modelo.eventos.ProductoSeleccionadoListener;
import com.foolsrecords.tpv.servicios.ServicioItemVenta;
import com.foolsrecords.tpv.servicios.ServicioProducto;
import com.foolsrecords.tpv.vista.componentes.JProductoButton;
import java.awt.Color;
import java.awt.Image;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.SwingConstants;
import javax.swing.UIManager;

//Creamos la clase principal
public class TablaProductos extends javax.swing.JPanel {

//Creamos las variables y objetos necesarios para poder trabajar
private Map<Integer, JProductoButton> mapaProductos;
ProductoSeleccionadoListener objEven = new ProductoSeleccionadoListener(this);
ServicioItemVenta servItemVenta = new ServicioItemVenta();

//Creamos el constructor
public TablaProductos() {
    initComponents();
    inicializarPanelProductos(0); //con los subproductos de tipo 1
}

//Inicializamos el panel de productos y le pasamos la familia de los productos como       parametro para mostrar los botones correctos
public void inicializarPanelProductos(int tipoProducto) {

    //Creamos un objeto para conectar con la base de datos a traves de la clase servicioproducto
    ServicioProducto servicio = new ServicioProducto();

    //Conectamos con la base de datos y cojemos los productos de la familia enviada como parametro
    List<Producto> productos = servicio.getProductos(tipoProducto);

    //Creamos un mapaproductos para poder crear los botones dinamicamente
    mapaProductos = new HashMap();

    //Borramos el panel jpanelproductos para montarlo de nuevo como nosotros queremos
    jpanelProductos.removeAll();

    //Creamos los 15 botones que contendra el panel y los hacemos todos invisibles
    for (int i = 1; i <= 30; i++) {
        mapaProductos.put(i, new JProductoButton());
        mapaProductos.get(i).addActionListener(objEven);
        mapaProductos.get(i).setVisible(false);
        jpanelProductos.add(mapaProductos.get(i), i - 1);
    }

    //Hacemos visibles tantos botones como productos tenemos en la familia enviada como parametro
    for (int i = 0; i < productos.size(); i++) {

        JProductoButton boton = mapaProductos.get(i + 1);
        UIManager.put("Button.select", Color.WHITE);
        boton.setVisible(true);
        boton.setProducto(productos.get(i));
        boton.setHorizontalTextPosition(SwingConstants.CENTER);
        boton.setVerticalTextPosition(SwingConstants.BOTTOM);
        boton.setFocusPainted(false);
        boton.setBackground(Color.WHITE);
        boton.setFont(new java.awt.Font("Arial", 1, 9));;
        boton.setText(productos.get(i).getDescripcion());
        boton.setIcon(new javax.swing.ImageIcon(productos.get(i).getImagen().getScaledInstance(88, 70, Image.SCALE_SMOOTH)));
        boton.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 204), 2));
        boton.setPreferredSize(new java.awt.Dimension(79, 97));
        boton.setMinimumSize(new java.awt.Dimension(79, 97));
        boton.setMaximumSize(new java.awt.Dimension(79, 97));
    }

    jpanelProductos.repaint();
}

//Este metodo es generado automaticamente por netbeans
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jScrollPane2 = new javax.swing.JScrollPane();
    jpanelProductos = new javax.swing.JPanel();

    setMinimumSize(new java.awt.Dimension(410, 300));
    setName(""); // NOI18N
    setPreferredSize(new java.awt.Dimension(410, 300));
    setLayout(null);

    jPanel1.setPreferredSize(new java.awt.Dimension(410, 300));
    jPanel1.setLayout(null);

    jpanelProductos.setPreferredSize(new java.awt.Dimension(400, 800));
    jpanelProductos.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 2));
    jScrollPane2.setViewportView(jpanelProductos);

    jPanel1.add(jScrollPane2);
    jScrollPane2.setBounds(0, 0, 410, 300);

    add(jPanel1);
    jPanel1.setBounds(0, 0, 410, 300);
}// </editor-fold>                        


// Variables declaration - do not modify                     
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JPanel jpanelProductos;
// End of variables declaration                   

//Creamos los get y los set necesarios
public javax.swing.JPanel getJpanelProductos() {
    return jpanelProductos;
}

public void setJpanelProductos(javax.swing.JPanel jpanelProductos) {
    this.jpanelProductos = jpanelProductos;
}

public void setControlador(ControladorEventListener controlador) {
    this.objEven.setControlador(controlador);
}
}
aterai
  • 9,658
  • 4
  • 35
  • 44
  • FlowLayout doesn't wrap its content (well). You'd be better off using another layout manager, something like [WrapLayout](http://tips4java.wordpress.com/2008/11/06/wrap-layout/) perhaps – MadProgrammer Aug 17 '14 at 22:46
  • I tried wraplayout but still not working, I have no scroll bar. Thanks for your answer. – daft punky Aug 17 '14 at 22:59

2 Answers2

1

This...

jpanelProductos.setPreferredSize(new java.awt.Dimension(400, 800));

Is your problem. The JScrollPane will use the preferred size of your component to determine if it needs to use scroll bars to display it or not. You should let the layout manager make this determination.

If you want to affect the size of the viewport (how big the scrollpane appears by default), then you should be using the Scrollable interface

Hava a look at Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? for more details.

Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • I tested with getPreferedSize () and nothing, I can't get the scroll, probably I'll do something wrong. I have looked at the message that you put me and I have read over and over again but do not know how to display the scroll. I said before that I am very new to java. Could you guide me a little more ??.You can give me some more information?. – daft punky Aug 18 '14 at 11:50
0

Thanks for all, the code is working now, i delete all code and make all of new and now all is working, here is my new code:

//Creamos el panel que contendra los botones de cada producto diferente
package com.foolsrecords.tpv.tablaproductos.vista;

//Hacemos todas las importaciones necesarias
import com.foolsrecords.tpv.modelo.Producto;
import com.foolsrecords.tpv.modelo.eventos.ControladorEventListener;
import com.foolsrecords.tpv.modelo.eventos.ProductoSeleccionadoListener;
import com.foolsrecords.tpv.servicios.ServicioItemVenta;
import com.foolsrecords.tpv.servicios.ServicioProducto;
import com.foolsrecords.tpv.vista.componentes.JProductoButton;
import java.awt.Color;
import java.awt.Image;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.SwingConstants;
import javax.swing.UIManager;

//Creamos la clase principal
public class TablaProductos extends javax.swing.JPanel {

//Creamos las variables y objetos necesarios para poder trabajar
private Map<Integer, JProductoButton> mapaProductos;
ProductoSeleccionadoListener objEven = new ProductoSeleccionadoListener(this);
ServicioItemVenta servItemVenta = new ServicioItemVenta();

//Creamos el constructor
public TablaProductos() {
    initComponents();
    inicializarPanelProductos(0); //con los subproductos de tipo 1
}

//Inicializamos el panel de productos y le pasamos la familia de los productos como parametro para mostrar los botones correctos
public void inicializarPanelProductos(int tipoProducto) {

    //Creamos un objeto para conectar con la base de datos a traves de la clase servicioproducto
    ServicioProducto servicio = new ServicioProducto();

    //Conectamos con la base de datos y cojemos los productos de la familia enviada como parametro
    List<Producto> productos = servicio.getProductos(tipoProducto);

    //Creamos un mapaproductos para poder crear los botones dinamicamente
    mapaProductos = new HashMap();

    //Borramos el panel jpanelproductos para montarlo de nuevo como nosotros queremos
    jpanelProductos.removeAll();

    //Creamos los 15 botones que contendra el panel y los hacemos todos invisibles
    for (int i = 1; i < productos.size()+2; i++) {
        mapaProductos.put(i, new JProductoButton());
        mapaProductos.get(i).addActionListener(objEven);
        mapaProductos.get(i).setVisible(false);
        jpanelProductos.add(mapaProductos.get(i), i - 1);
    }

    //Hacemos visibles tantos botones como productos tenemos en la familia enviada como parametro
    for (int i = 0; i < productos.size(); i++) {

        JProductoButton boton = mapaProductos.get(i + 1);
        UIManager.put("Button.select", Color.WHITE);
        boton.setVisible(true);
        boton.setProducto(productos.get(i));
        boton.setHorizontalTextPosition(SwingConstants.CENTER);
        boton.setVerticalTextPosition(SwingConstants.BOTTOM);
        boton.setFocusPainted(false);
        boton.setBackground(Color.WHITE);
        boton.setFont(new java.awt.Font("Arial", 1, 9));;
        boton.setText(productos.get(i).getDescripcion());
        boton.setIcon(new javax.swing.ImageIcon(productos.get(i).getImagen().getScaledInstance(88, 70, Image.SCALE_SMOOTH)));
        boton.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 204), 2));
        boton.setPreferredSize(new java.awt.Dimension(76, 97));
        boton.setMinimumSize(new java.awt.Dimension(76, 97));
        boton.setMaximumSize(new java.awt.Dimension(76, 97));
    }

    jpanelProductos.repaint();
}

//Este metodo es generado automaticamente por netbeans
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jScrollPane2 = new javax.swing.JScrollPane();
    jpanelProductos = new javax.swing.JPanel();

    setMinimumSize(new java.awt.Dimension(410, 300));
    setName(""); // NOI18N
    setPreferredSize(new java.awt.Dimension(410, 300));
    setLayout(null);

    jpanelProductos.setPreferredSize(new java.awt.Dimension(350, 2000));
    jpanelProductos.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 2));
    jScrollPane2.setViewportView(jpanelProductos);

    add(jScrollPane2);
    jScrollPane2.setBounds(0, 0, 410, 300);
}// </editor-fold>                        


// Variables declaration - do not modify                     
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JPanel jpanelProductos;
// End of variables declaration                   

//Creamos los get y los set necesarios
public javax.swing.JPanel getJpanelProductos() {
    return jpanelProductos;
}

public void setJpanelProductos(javax.swing.JPanel jpanelProductos) {
    this.jpanelProductos = jpanelProductos;
}

public void setControlador(ControladorEventListener controlador) {
    this.objEven.setControlador(controlador);
}

public javax.swing.JScrollPane getjScrollPane2() {
    return jScrollPane2;
}

public void setjScrollPane2(javax.swing.JScrollPane jScrollPane2) {
    this.jScrollPane2 = jScrollPane2;
}

}
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • This is a different problem. You should ask a separate question regarding the scrollbar visiblity. I removed this part from your answer. – Artjom B. Aug 20 '14 at 08:24