简体   繁体   中英

How to add checkbox if i fetch the record from Database

  1. I want add checkbox front of my record, when i fetch the record from database.Plz check my code your automatically know what i want

  1. Class Name:-AddAccountDao.Java

      public class AddAccountDao { public static List<AddAccount> view(){ List <AddAccount> list=new ArrayList<>(); try{ Connection con=getCon(); PreparedStatement pst=con.prepareStatement("SELECT * FROM adminaccount"); ResultSet rst=pst.executeQuery(); while(rst.next()){ AddAccount ad=new AddAccount(); ad.setId(rst.getInt(1)); ad.setName(rst.getString(2)); ad.setPassword(rst.getString(3)); ad.setEmail(rst.getString(4)); ad.setContact(rst.getString(5)); list.add(ad); } con.close(); } catch(Exception e){ System.out.println(e); } return list; } } 
  2. Class Name:-AdminViewAccount

      public class AdminViewAccount extends JFrame{ static AdminViewAccount frame; public AdminViewAccount(){ List<AddAccount> list=AddAccountDao.view(); int size=list.size(); String data[][]=new String[size][6]; int row=0; for(AddAccount ad:list){ data[row][1]=String.valueOf(ad.getId()); data[row][2]=ad.getName(); data[row][3]=ad.getPassword(); data[row][4]=ad.getEmail(); data[row][5]=ad.getContact(); row++; } String columnName[]= {"Select","ID","Name","Password","Email","Contact No."}; JTable t=new JTable(data,columnName); JScrollPane sp=new JScrollPane(t); add(sp); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100,100,800,400); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable(){ @Override public void run() { try{ frame=new AdminViewAccount(); frame.setVisible(true); } catch(Exception e){ e.printStackTrace(); } } }); } } 
  3. Class Name:-AddAccount

     public class AddAccount { private int id; private String name,password,email,contact; public AddAccount(){} public AddAccount(String name,String password,String email,String contact){ super(); this.name=name; this.password=password; this.email=email; this.contact=contact; } public void setId(int id){ this.id=id; } public int getId(){ return id; } public void setName(String name){ this.name=name; } public String getName(){ return name; } public void setPassword(String password){ this.password=password; } public String getPassword(){ return password; } public void setEmail(String email){ this.email=email; } public String getEmail(){ return email; } public void setContact(String contact){ this.contact=contact; } public String getContact(){ return contact; } } 

https://i.stack.imgur.com/shmm9.jpg

One way is to create a custom TableModel that uses your TableModel and adds a check box column at the start of the table:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class CheckBoxWrapperTableModel extends AbstractTableModel
{
    private ArrayList<Boolean> checkBoxes = new ArrayList<>();

    private DefaultTableModel model;
    private String columnName;

    public CheckBoxWrapperTableModel(DefaultTableModel model, String columnName)
    {
        this.model = model;
        this.columnName = columnName;

        for (int i = 0; i < model.getRowCount(); i++)
            checkBoxes.add( Boolean.FALSE );
    }

    @Override
    public String getColumnName(int column)
    {
        return (column > 0) ? model.getColumnName(column - 1) : columnName;
    }

    @Override
    public int getRowCount()
    {
        return model.getRowCount();
    }

    @Override
    public int getColumnCount()
    {
        return model.getColumnCount() + 1;
    }

    @Override
    public Object getValueAt(int row, int column)
    {
        if (column > 0)
            return model.getValueAt(row, column - 1);
        else
        {
            Object value = checkBoxes.get(row);
            return (value == null) ? Boolean.FALSE : value;
        }
    }

    @Override
    public boolean isCellEditable(int row, int column)
    {
        if (column > 0)
            return model.isCellEditable(row, column - 1);
        else
            return true;
    }

    @Override
    public void setValueAt(Object value, int row, int column)
    {
        if (column > 0)
            model.setValueAt(value, row, column - 1);
        else
        {
            checkBoxes.set(row, (Boolean)value);
        }

        fireTableCellUpdated(row, column);
    }

    @Override
    public Class getColumnClass(int column)
    {
        return (column > 0) ? model.getColumnClass(column - 1) : Boolean.class;
    }

    public void removeRow(int row)
    {
        checkBoxes.remove(row);
        fireTableRowsDeleted(row, row);
        model.removeRow(row);
    }

    private static void createAndShowGUI()
    {
        //  Create the table with check marks in the first column

        DefaultTableModel model = new DefaultTableModel(5, 1);

        for (int i = 0; i < model.getRowCount(); i++)
        {
            model.setValueAt("" + i, i, 0);
        }

        CheckBoxWrapperTableModel wrapperModel = new CheckBoxWrapperTableModel(model, "Select");
        JTable table = new JTable(wrapperModel);

        //  Add button to delete selected rows

        JButton button = new JButton( "Delete Selected Rows" );
        button.addActionListener( new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                for (int i = table.getRowCount() - 1; i >= 0; i--)
                {
                    Boolean selected = (Boolean)table.getValueAt(i, 0);
                    System.out.println(selected + " : " + i);

                    if (selected)
                    {
                        wrapperModel.removeRow(i);
                    }

                }
            }
        });

        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new JScrollPane( table ) );
        frame.add( button, BorderLayout.PAGE_END );
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater( () -> createAndShowGUI() );
/*
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
*/
    }
}

Or the other approach, since you are just copying the data to the TableModel is to just add an extra column when you copy the data:

data[row][0] = Boolean.FALSE; // added
data[row][1]=String.valueOf(ad.getId());

You would then also need to override the getColumnClass(...) method of your TableModel to return Boolean.class for the first column as demonstrated in the TableModel above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM