Scrollbar

0

I want to put a scroll bar both to the right and to the bottom I know I have to put JScrollPane but I do not know where I would put it or how.

This is the code:

package bonos1;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;

public class Tabla {


    private JTable t;
    private DefaultTableModel m;
    private int i=0;
    private int a=0;

    public Tabla(){
        //* Inicializar variables *//
        JFrame v = new JFrame();
        m = new DefaultTableModel();
        t = new JTable(m);
        JScrollPane s = new JScrollPane(t);

        //* Se agregarn tres columnas inicialmente //*
        m.addColumn("Desarrollo Social");
        m.addColumn("Recursos materiales");
        m.addColumn("Des.agropecuario");
        m.addColumn("Desarrollo economico");
        m.addColumn("Educacion y cultura");
        m.addColumn("Seguridad Publica");
        m.addColumn(" DIF");
        m.addColumn("Secretaria general");
        m.addColumn("Archivo");
        m.addColumn("Registro de lo familiar");
        m.addColumn("Catastro");
        m.addColumn("Turismo");
        m.addColumn("Transparencia");
        m.addColumn("Informatica");
        m.addColumn("Teseroria");
        m.addColumn("Contraloria");
        m.addColumn("Conciliacion Municipal");
        m.addColumn("Oficialia mayor");
        m.addColumn("Servicios generales");
        m.addColumn("Ecologia");
        m.addColumn("Reaglamentos y Espect");
        m.addColumn("Obras publicas");
        m.addColumn("Planeacion");
        m.addColumn("Unidad juridica");
        m.addColumn("Comunicacion social");
        m.addColumn("IMDM");
        m.addColumn("IMJUV");
        m.addColumn("COMUDE");
        m.addColumn("Poteccion civil");


        /** Se agregan diez columnas inicialmente con el valor del contador **/

        /** Se agregan el scroll a la ventna **/
        v.getContentPane().add(s,BorderLayout.CENTER);

        JPanel pN=new JPanel();

        //* Inicializan botonnes y se dan acciones *//
        JButton aF = new JButton("Agregar Fila");
        pN.add(aF);
        aF.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                agregar(2);
            }
        });

        JButton bF = new JButton("Borrar Fila");
        pN.add(bF);
        bF.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                eliminar(2);
            }
        });


        /** Agregan y se crea ventana **/
        v.getContentPane().add(pN,BorderLayout.NORTH);
        v.pack();
        v.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        v.setVisible(true);
    }

    /* Se encarga de eliminar
     * si el valor es 1 elimina la columna
     * si el valor es 2 elimina la fila */
    private void eliminar(int caso){
        try{
            switch(caso){
                case 1:
                    t.removeColumn(t.getColumnModel().getColumn(t.getSelectedColumn()));//Elimna la columna selecionada por el usuario
                    break;
                case 2:
                    m.removeRow(t.getSelectedRow());//Elimna la fila selecionada por el usuario
                    break;
            }
        }catch(ArrayIndexOutOfBoundsException aIE){}
    }

    /* Se encarga de agregar
     * si el valor es 1 agrega una columna
     * si el valor es 2 agrega una fila */
    private void agregar(int caso){
        try{
            switch(caso){
                case 2:
                    m.addRow(new Object[]{a++,"",""});//Agrega un fila con el valor del contador y los demas en blanco
                    break;
            }
        }catch(ArrayIndexOutOfBoundsException aIE){}
    }
    public static void main(String [] args){
        new Tabla();//Se corre la clase
    }
}
    
asked by nataly paola avila pineda 06.07.2018 в 19:33
source

1 answer

1

Greetings, Nataly.

Everything you've done seems fine (you've already added the JScrollPane ), all you need to do is show the scroll bars.

By default, class JScrollPane shows scroll bars when needed , that is, when you add many rows (and these no longer fit in JScrollPane ) the bar will appear automatically .

All you have to do is add these methods after declaring your JScrollPane :

JScrollPane s = new JScrollPane(t);
s.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
s.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

Scroll bars can have 3 types of "tactic" or "standard" how they should appear. In the case of the vertical bar:

JScrollPane.VERTICAL_SCROLLBAR_ALWAYS // Mostrará la barra SIEMPRE
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED // Se mostrara si se necesita (por defecto)
JScrollPane.VERTICAL_SCROLLBAR_NEVER // Nunca se mostrará (aunque los elementos no quepan)

And in the case of the horizontal bar equal:

JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS // Mostrará la barra SIEMPRE
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED // Se mostrara si se necesita (por defecto)
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER // Nunca se mostrará (aunque los elementos no quepan)

In the case of the HORIZONTAL scroll bar, even if you adjust it to always appear it will not really have any effect, since the default JTable auto-adjusts all the columns so that they fit in the size of JScrollPane . I would recommend you do the following:

t = new JTable(m);
t.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

The setAutoResizeMode method changes how columns should be auto-adjusted. By default, the class JTable uses a "self-adjustment to all columns", when using JTable.AUTO_RESIZE_OFF we indicate to JTable that it does not adjust them to fit, but to stretch (which would force to appear the horizontal scroll bar).

I enclose the result:

    
answered by 06.07.2018 / 20:31
source