CheckBox List by Zhiguo Yin : List « Swing Components « Java






CheckBox List by Zhiguo Yin

CheckBox List by Zhiguo Yin
 
/*
author: yinzhiguo
mail: yin_zhiguo at hotmail.com
env: ubuntu 8.04 jdk1.6.0

this is a checkbox list ctrl for developer java swing application.
it is very simple. you only require implements a method!
require apache commons-lang.jar

For example:

    langList = new CheckboxList(ts){
            @Override
            public Object getDataLabel(Object data){
                Book a = (Book)data;
                return a.getTitle();
            }
    };
    centerPane.add(langList, BorderLayout.CENTER);
    ArrayList as = langList.getSelectedData();
    
the ts is a Object array that your checkboxlist model.
you will implements the getDataLabel method.
get user's chooser is simple, only invoke langList.getSelectedData()
*/

package com.java2s.java.swing.common.pane;


import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JMenuItem;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

/**
 * this is a checkbox list for swing application
 * @author  yinzhiguo
 */
public class CheckboxList extends javax.swing.JPanel {
    
    private Vector<BooleanWrap> dataModel = new Vector<BooleanWrap>();

    private int columnWidth = 0;
    
    public CheckboxList( Object[] datas) {
         if(datas == null)
            throw new java.lang.IllegalArgumentException("datas is null!");
         int max = 0;
         for(Object o : datas)
         {
                BooleanWrap bw = new BooleanWrap(o);
                int a = bw.getLabel().length();
                if(max < a)
                    max = a;
                dataModel.add(bw);
         }
        columnWidth = max;
        initComponents();
        this.setPreferredSize(table.getPreferredSize());
    }
    
    public CheckboxList(ArrayList list) {
        if(list == null || list.isEmpty())
            throw new java.lang.IllegalArgumentException("list is null or empty!");
        
        int max = 0;
         for(Object o : list)
         {
                BooleanWrap bw = new BooleanWrap(o);
                int a = bw.getLabel().length();
                if(max < a)
                    max = a;
                dataModel.add(bw);
         }
        columnWidth = max;
        initComponents();
        this.setPreferredSize(table.getPreferredSize());
    }

  private JMenuItem getMenuItem(String id) {
        JMenuItem item = new javax.swing.JMenuItem();
        if("all".equals(id))
        {
            item.setText("??");
        }else if("notAll".equals(id))
        {
            item.setText("???");
        }else if("reverse".equals(id))
        {
            item.setText("??");
        }
        return item;
        
    }

    public ArrayList getSelectedData(){
        ArrayList i = new ArrayList();
        
        for(BooleanWrap bw : dataModel){
            if(bw.getChecked()){
                i.add(bw.getData());
            }
        }
        return i;
    }
     
    private TableModel getTableModel() {
        return new DataModel();
    }

   
     

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        popupMenu = new javax.swing.JPopupMenu();
        allMenuItem = getMenuItem("all");
        notAllMenuItem = getMenuItem("notAll");
        reverseMenuItem = getMenuItem("reverse");
        colText = new javax.swing.JTextField();
        scrollPane = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();

        allMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                allMenuItemActionPerformed(evt);
            }
        });
        popupMenu.add(allMenuItem);

        notAllMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                notAllMenuItemActionPerformed(evt);
            }
        });
        popupMenu.add(notAllMenuItem);

        reverseMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                reverseMenuItemActionPerformed(evt);
            }
        });
        popupMenu.add(reverseMenuItem);

        setLayout(new java.awt.BorderLayout());
        add(colText, java.awt.BorderLayout.PAGE_START);

        table.setModel(getTableModel());
        table.setComponentPopupMenu(popupMenu);
        setTableParam();
        scrollPane.setViewportView(table);

        add(scrollPane, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

           private void actionPerformOfButton(int type){
               if(!dataModel.isEmpty()){
                    for(BooleanWrap bw : dataModel)
                    {
                        if(type == 1){
                        bw.setChecked(Boolean.TRUE);
                        }else if(type == 2)
                        {
                            bw.setChecked(Boolean.FALSE);    
                        }else if(type == 3){
                            bw.setChecked(!bw.getChecked());
                        }
                    }
                    ((AbstractTableModel)table.getModel()).fireTableDataChanged();
                }
           }

private void allMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_allMenuItemActionPerformed
// TODO add your handling code here:
    actionPerformOfButton(1);
}//GEN-LAST:event_allMenuItemActionPerformed

private void notAllMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_notAllMenuItemActionPerformed
// TODO add your handling code here:
    actionPerformOfButton(2);
}//GEN-LAST:event_notAllMenuItemActionPerformed

private void reverseMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_reverseMenuItemActionPerformed
// TODO add your handling code here:
    actionPerformOfButton(3);
}//GEN-LAST:event_reverseMenuItemActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem allMenuItem;
    private javax.swing.JTextField colText;
    private javax.swing.JMenuItem notAllMenuItem;
    private javax.swing.JPopupMenu popupMenu;
    private javax.swing.JMenuItem reverseMenuItem;
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JTable table;
    // End of variables declaration//GEN-END:variables

    private void setTableParam() {
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
     //   table.setDragEnabled(false);
        table.setShowGrid(false);
        table.getTableHeader().setEnabled(false);
        
        //???????
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setPreferredSize(new Dimension(0, 0));
        table.getTableHeader().setDefaultRenderer(renderer);
        
        
        table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting()) {
                        return;
                    }
                    ListSelectionModel sm = (ListSelectionModel) e.getSource();
                    int row = sm.getLeadSelectionIndex();
                    if(row >=0){
                        BooleanWrap bw = dataModel.get(row);
                        colText.setText(bw.getLabel());
                    }
                }
            });
        
        DefaultTableColumnModel dtm = (DefaultTableColumnModel)table.getColumnModel();
        
        int count = dtm.getColumnCount();
        for(int i = 0; i < count; i++)
        {
            TableColumn tc = dtm.getColumn(i);
            tc.setResizable(false);
            if(i == 0){
                tc.setWidth(15);
                tc.setPreferredWidth(25);
            }else{
                tc.setWidth(columnWidth * 3);
                tc.setPreferredWidth(columnWidth * 10);
            }
        }
        ColumnColorTableCellRenderer ctlr = new ColumnColorTableCellRenderer();
        table.getColumnModel().getColumn(1).setCellRenderer(ctlr); 
    }

    
     class DataModel extends AbstractTableModel {
            private String[] columnNames = {"...", "..."};
            
            public Class getColumnClass(int columnIndex) {
                if(columnIndex == 0)
                    return Boolean.class;
                return String.class;
            }
            
            public String getColumnName(int column) {
                return columnNames[column];
            }
            public int getRowCount() {
                return dataModel.size();
            }
            
            public int getColumnCount() {
                return columnNames.length;
            }
            
            public Object getValueAt(int rowIndex, int colIndex) {
                BooleanWrap bw = dataModel.get(rowIndex);
                if(colIndex == 1)
                    return getDataLabel(bw.getData());
                else{
                    
                    return bw.getChecked();
                }
            }
            
        @Override
            public void setValueAt(Object value, int rowIndex, int colIndex) {
                if(colIndex == 0){
                    Boolean flag = (Boolean)value;
                    BooleanWrap bw = dataModel.get(rowIndex);
                    bw.setChecked(flag);
                    
                }
            }
            
        @Override
            public boolean isCellEditable(int rowIndex,
                    int columnIndex) {
                if(columnIndex == 0)
                    return true;
                return false;
            }
        }
    
     /**
      * ????????list????????
      * ????,??????
      * @param data
      * @return
      */
    public Object getDataLabel(Object data){
        return data.toString();
    }
    
     class BooleanWrap{
        private Boolean checked = Boolean.FALSE;
        private Object data = null;
        
        public BooleanWrap(Object obj)
        {
            this.data = obj;
        }

        public Boolean getChecked() {
            return checked;
        }

        public void setChecked(Boolean checked) {
            this.checked = checked;
        }

        public Object getData() {
            return data;
        }

        public void setData(Object data) {
            this.data = data;
        }
        
        public String getLabel(){
            return (String)getDataLabel(this.getData());
        }
    }
    
}

//////////////////////////////////////////////////////

/*
 * AlternationColorTableCellRenderer.java
 *
 * Created on 2007?9?14?, ??10:32
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.java2s.java.swing.common.pane;

import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;

/**
 *
 * @author java
 */
public class ColumnColorTableCellRenderer extends DefaultTableCellRenderer{
    
    private Color colorOne = Color.white;
    private Color colorTwo = new Color(206,231,255);
    
    private Color textColor = Color.BLUE;
    private Color numberColor = Color.RED;
    private Color dateColor = Color.BLUE;
    
    /** Creates a new instance of AlternationColorTableCellRenderer */
    public ColumnColorTableCellRenderer(Color one, Color two) {
        if(one != null)
            colorOne = one;
        if(two != null)
            colorTwo = two;
    }
    
    public ColumnColorTableCellRenderer() {
    }
    
    public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus,
            int row, int column) {
        
        if(value instanceof String)
        {
            String str = (String)value;
            this.setForeground(textColor);
            
        }else if(value instanceof Integer || value instanceof Double || value instanceof Long)
        {
            this.setForeground(numberColor);
            this.setHorizontalAlignment(SwingConstants.RIGHT);
        }
        if(row % 2 == 0){
            setBackground(colorOne);
        }
        else if(row % 2 == 1)
        {
            setBackground(colorTwo); 
        }
        return super.getTableCellRendererComponent(table, value,
                isSelected, hasFocus, row, column);
    }

    public Color getTextColor() {
        return textColor;
    }

    public void setTextColor(Color textColor) {
        this.textColor = textColor;
    }

    public Color getNumberColor() {
        return numberColor;
    }

    public void setNumberColor(Color numberColor) {
        this.numberColor = numberColor;
    }

    public Color getDateColor() {
        return dateColor;
    }

    public void setDateColor(Color dateColor) {
        this.dateColor = dateColor;
    }
}


//////////////////////////////////////////////////////

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.java2s.java.swing.common.pane;

import com.uusee.platform.util.*;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Point;
import java.awt.Toolkit;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

/**
 * @email yin_zhiguo@hotmail.com
 * @author yinzhiguo
 */
public class SwingUtil {
    
    /** Creates a new instance of SwingUtil */
    private SwingUtil() {
    }
    
    public static String[] getClassNameOfLookAndFeel() {
        LookAndFeelInfo[]  lookAndFeelInfos = UIManager.getInstalledLookAndFeels();
        String[] name = new String[lookAndFeelInfos.length];
        for (int i = 0; i < lookAndFeelInfos.length; i++) {
            name[i] = lookAndFeelInfos[i].getClassName();
        }
        return name;
    }
    
    public static void setLookAndFeel(String clzz) {
        try {
            UIManager.setLookAndFeel(clzz);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        
    }
    
    public static int getScreenWidth() {
        return getScreenSize().width;
    }
    
    public static int getScreenHeight() {
        return getScreenSize().height;
    }
    
    public static Dimension getScreenSize() {
        return Toolkit.getDefaultToolkit().getScreenSize();
    }
    
    public static void setLocationToCenterOfComponent(Component parent, Component child)
    {
        Point parentPoint = parent.getLocation();
        Dimension parentDim = parent.getSize();
        Dimension childDim = child.getSize();
        child.setLocation(parentPoint.x + (parentDim.width - childDim.width)/2, parentPoint.y + (parentDim.height - childDim.height)/2);
    }
    
    /**
     * ???????
     * @param comp
     */
    public static void setLocationToCenterOfScreen(Component comp) {
        Dimension screenSize = getScreenSize();
        Dimension frameSize = comp.getSize();
        
        if (frameSize.height > screenSize.height) {
            frameSize.height = screenSize.height;
        }
        if (frameSize.width > screenSize.width) {
            frameSize.width = screenSize.width;
        }
        comp.setLocation((screenSize.width - frameSize.width) / 2,
            (screenSize.height - frameSize.height) / 2);
    }
    
    public static String[] convertToMaxWidth(String[] strs, FontMetrics fm){
        int max = 0; //????
        int fix = fm.stringWidth(" ");//???????(?????)
        int[] widths = new int[strs.length]; //???????(?????)
        int[] dis = new int[strs.length]; //???????(?????)
        for(int i = 0; i < strs.length; i++){
            int w = fm.stringWidth(strs[i]);
           // System.out.println(strs[i] + " " + w);
            widths[i] = w;
            if(w > max){
                max = w;
            }
        }
        max = max + fix * 4;
       // System.out.println("max: " + max + ", fix: " + fix);
        for(int i = 0; i < strs.length; i++){
            int distance = max - widths[i]; //??????
            dis[i] = (distance / fix) + 1;
        }
        String[] res = new String[strs.length];
        for(int i = 0; i < strs.length; i++){
            res[i] = Helper.leftAppendSpace(strs[i], dis[i]);
            //System.out.println(strs[i] + " " + dis[i] + ", "+ widths[i] + ", " + fm.stringWidth(strs[i]));
        }
        return res;
    }
    
}

//////////////////////////////////////////////////////

package com.java2s.java.swing.common.pane;

import java.awt.BorderLayout;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

/**
 * @email yin_zhiguo@hotmail.com
 * @author yinzhiguo
 */
public class CheckboxListTestFrame extends javax.swing.JFrame {

    /** Creates new form CheckboxListTestFrame */
    public CheckboxListTestFrame() {
        initComponents();
        this.setSize(140, 230);
        this.setTitle("CheckboxList ??");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        centerPane = new javax.swing.JPanel();
        testButPane = new javax.swing.JPanel();
        testBut = getButtonBy("test");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        centerPane.setLayout(new java.awt.BorderLayout());

        testButPane.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        testBut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                testButActionPerformed(evt);
            }
        });
        testButPane.add(testBut);

        centerPane.add(testButPane, java.awt.BorderLayout.PAGE_END);

        prepareCheckboxListPane();

        getContentPane().add(centerPane, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

     /**
     * ??ID??JButton???
     * @param id ?????
     * @return ????
     */
    public JButton getButtonBy(String id){

        JButton but = new JButton();
        if("test".equals(id)){
             but.setText("??");
             but.setToolTipText("??");
        }
        return but;
    }

    private CheckboxList langList = null;
    
    class Book{
        private String title = "";
        private double price = 0.0;

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public double getPrice() {
            return price;
        }

        public void setPrice(double price) {
            this.price = price;
        }
    }
    
    private void prepareCheckboxListPane() {
        
        Book t = new Book();
        t.setTitle("Java??");
        t.setPrice(20.5);
        
        Book t1 = new Book();
        t1.setTitle("PHP??");
        t1.setPrice(30.5);
        
        Book t2 = new Book();
        t2.setTitle("C++??");
        t2.setPrice(50.5);
        
        Book t3 = new Book();
        t3.setTitle("Python??");
        t3.setPrice(30.5);
        
        Book t4 = new Book();
        t4.setTitle("Perl??");
        t4.setPrice(23.5);
        
        Book t5 = new Book();
        t5.setTitle("SmallTalk??");
        t5.setPrice(23.5);
        
        Book t6 = new Book();
        t6.setTitle("Ruby??");
        t6.setPrice(23.5);
        
        Book t7 = new Book();
        t7.setTitle("Lisp??");
        t7.setPrice(23.5);
        
        Book t8 = new Book();
        t8.setTitle("Shell??");
        t8.setPrice(23.5);
        
        Book[] ts = {t,t1,t2,t3,t4,t5,t6,t7,t8};
        
        langList = new CheckboxList(ts){
            @Override
            public Object getDataLabel(Object data){
                Book a = (Book)data;
                return a.getTitle();
            }
        };
        centerPane.add(langList, BorderLayout.CENTER);
    }
    
private void testButActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_testButActionPerformed
// TODO add your handling code here:
    ArrayList as = langList.getSelectedData();
    if(as.isEmpty()){
        JOptionPane.showMessageDialog(this, "????????!", "??", JOptionPane.INFORMATION_MESSAGE);
    }else{
        StringBuffer sub = new StringBuffer();
        sub.append("<html>");
        sub.append("<b>????:</b><br>");
        sub.append("<ul>");
        for(Object o : as){
            Book b = (Book)o;
            sub.append("<li>" + b.getTitle() + ", " + b.getPrice() + "</li>");
        }
        sub.append("</ul>");
        sub.append("</html>");
        JOptionPane.showMessageDialog(this, sub.toString(), "??", JOptionPane.INFORMATION_MESSAGE);
    }
}//GEN-LAST:event_testButActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        UIManager.put("swing.boldMetal", Boolean.FALSE);
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                CheckboxListTestFrame cltf = new CheckboxListTestFrame();
                SwingUtil.setLocationToCenterOfScreen(cltf);
                cltf.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel centerPane;
    private javax.swing.JButton testBut;
    private javax.swing.JPanel testButPane;
    // End of variables declaration//GEN-END:variables

}





           
         
  








CheckboxListDemoYinZhiGuo.zip( 241 k)

Related examples in the same category

1.Mouse Roll over ListMouse Roll over List
2.Check List ExampleCheck List Example
3.Check List Example 2Check List Example 2
4.ToolTip List ExampleToolTip List Example
5.Editable List ExampleEditable List Example
6.DND Drag and drop List
7.CheckBox List