Programando con java de manera ágil, fácil y entretenida de tal manera que lo harás como jugando.

viernes, 1 de junio de 2012

Jtable con Checkboxs

Si en alguna oportunidad has necesitado poner checkbox en un Jtable y no tubiste ni idea aqui veremos lo facil que resulta.

Todo va dentro de un arreglo estatico pero uds pueden ponerlo en un for while u otra estructura de control antes de lanzar el agregado o la funcion getTable()

Adjunto el código:

/**
*
* @author http://jonathan-palomino.blogspot.com/
*
*/
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.UIManager;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class J_table extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel jContentPane = null;
    private JScrollPane scroll = null;
    private JTable Table = null;
    Object[] columnas = {"ACTIVOS", "NOMBRE", "EDAD"};
    Object[][] datos = {
        {true,"JOSE",50},
        {false,"ANDREA",12},
        {true,"IVETTE",18},
        {false,"JUAN",18}};

    /**
     * This method initializes scroll   
     *    
     * @return javax.swing.JScrollPane   
     */
    private JScrollPane getScroll() {
        if (scroll == null) {
            scroll = new JScrollPane();
            scroll.setViewportView(getTable());
        }
        return scroll;
    }

    /**
     * This method initializes Table   
     *    
     * @return javax.swing.JTable   
     */
    private JTable getTable() {
        if (Table == null) {
             DefaultTableModel modelo = new DefaultTableModel(datos, columnas) {
                    public Class<?> getColumnClass(int column) {
                        return getValueAt(1, column).getClass();
                    }
                };
            Table = new JTable(modelo);
          
        }
        return Table;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try{
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                }catch(Exception e) {
                    e.printStackTrace();
                }
                J_table thisClass = new J_table();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    /**
     * This is the default constructor
     */
    public J_table() {
        super();
        initialize();
    }

    /**
     * This method initializes this
     *
     * @return void
     */
    private void initialize() {
        this.setSize(609, 281);
        this.setContentPane(getJContentPane());
        this.setTitle("JTable con checkbox por http://jonathan-palomino.blogspot.com/");
        this.setLocationRelativeTo(null);
    }

    /**
     * This method initializes jContentPane
     *
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(new BorderLayout());
            jContentPane.add(getScroll(), BorderLayout.CENTER);
        }
        return jContentPane;
    }

Jlabel editable con tecla Enter

En este caso podremos editar en tiempo de ejecución un Jlabel con la tecla Enter con lo cual lo podremos modificar a nuestro gusto.

Dejo el codigo para que lo prueben:

/**
*
* @author http://jonathan-palomino.blogspot.com/
*
*/
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JTextField;

import java.awt.CardLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;

public class principal extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel jContentPane = null;
    private JPanel panel_edicion = null;
    private JLabel etiqueta_editable = null;
    /*************************************/
    //si el usuario hizo enter
    private static final int confirmar = KeyEvent.VK_ENTER;
    //si es usuario pulso escape
    private static final int cancelo = KeyEvent.VK_ESCAPE;
    private CardLayout card;//utilizo el carlayotu para manejar varios objetos dentro del mismo panel
    private static final String txt_caja = "text field";  //  @jve:decl-index=0:
    private JTextField caja_edicion;
    private static final String LABEL = "label";
    private String valor=new String("");

    /**
     * This method initializes panel_edicion   
     *    
     * @return javax.swing.JPanel   
     */
    private JPanel getPanel_edicion() {
        if (panel_edicion == null) {
            card = new CardLayout();
            etiqueta_editable = new JLabel();
            etiqueta_editable.setText("Programación fácil con JAVA");
            etiqueta_editable.setHorizontalAlignment(SwingConstants.CENTER);
            etiqueta_editable.setFont(new Font("Dialog", Font.BOLD, 48));
            etiqueta_editable.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    //si el usurario hizo doble clic encima de la etiqueta
                    if (e.getClickCount() == 2) {
                        editando();
                    }
                }
            });
            caja_edicion = new JTextField();
            caja_edicion.addKeyListener(new KeyAdapter() {
                public void keyReleased(KeyEvent e) {
                    if (e.getKeyCode() == confirmar) {
                        confirmar();
                    } else if (e.getKeyCode() == cancelo) {
                        cancelar();
                    }
                }
            });
            panel_edicion = new JPanel(card);
            panel_edicion.add(caja_edicion, txt_caja);
            panel_edicion.add(etiqueta_editable, LABEL);
            card.show(panel_edicion, LABEL);
        }
        return panel_edicion;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                principal thisClass = new principal();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    /**
     * This is the default constructor
     */
    public principal() {
        super();
        initialize();
    }

    /**
     * This method initializes this
     *
     * @return void
     */
    private void initialize() {
        this.setSize(864, 251);
        this.setContentPane(getJContentPane());
        this.setTitle("JLabel editable en tiempo de ejecucion por jonathan-palomino.blogspot.com");
        this.setLocationRelativeTo(null);
    }

    /**
     * This method initializes jContentPane
     *
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(new BorderLayout());
            jContentPane.add(getPanel_edicion(), BorderLayout.CENTER);
        }
        return jContentPane;
    }
    /*********************************************/
    private void editando() {
        card.show(getPanel_edicion(), txt_caja);
        caja_edicion.setText(valor);
        caja_edicion.requestFocus();
        caja_edicion.selectAll();
    }

    private void cancelar() {
        caja_edicion.setText(valor);
        card.show(getPanel_edicion(), LABEL);
    }

    public void confirmar() {
        valor = caja_edicion.getText();
        etiqueta_editable.setText(valor);
        card.show(getPanel_edicion(), LABEL);
    }
   

Enviar

Twitter Delicious Facebook Digg Stumbleupon Favorites More