将复选框列添加到JScrollPane

时间:2018-01-18 22:48:02

标签: java swing checkbox jframe jscrollpane

我基本上想要做的是在我的表中添加一列复选框,它们负责显示我的数据库的内容。然后我计划在用户点击“更新...”按钮时打开与检查框一样多的JFrame,并在用户点击“删除”时删除与带有复选框的行相对应的行。

这个计划可行吗?如果是这样,你能给我一些关于在哪里寻找解决方案的提示......

界面我打算实施:

interface I am planning to implement

package dbInterface;

import java.awt.BorderLayout;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.*;


public class Interface {


    public Interface(Connection myConn) throws SQLException {
        intFrame=new JFrame();
        intFrame.setTitle("DBInterface");
        intFrame.setLayout(null);
        intFrame.setVisible(true);
        intFrame.setSize(600, 450);
        intFrame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        showDB(myConn);

        insertButton=new JButton("Add...");      
        insertButton.setBounds(85, 300, 85, 25);
        insertButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                try {
                    insertToDB(myConn);
                } catch (SQLException ex) {
                    Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
                }
            }           
        });

        deleteButton=new JButton("Delete");      
        deleteButton.setBounds(255, 300, 85, 25);
        deleteButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                try {
                    delFromDB(myConn);
                } catch (SQLException ex) {
                    Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
                }
            }           
        });

        updateButton=new JButton("Update...");      
        updateButton.setBounds(425, 300, 85, 25);
        updateButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                try {
                    updateDB(myConn);
                } catch (SQLException ex) {
                    Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
                }
            }           
        });

        intFrame.add(updateButton);
        intFrame.add(insertButton);
        intFrame.add(deleteButton);
    }

    private void updateDB(Connection myConn) throws SQLException {

    }

    private void delFromDB(Connection myConn) throws SQLException {

    }

    private void showDB(Connection myConn) throws SQLException {
        dataTable=new JTable();        
        Vector<Object> data = new Vector<Object>();
        Vector<Object> columnNames=new Vector<Object>();

        Statement showStmt=myConn.createStatement();
        ResultSet rs=showStmt.executeQuery("select * from employees");
        ResultSetMetaData md = rs.getMetaData();
        int columns = md.getColumnCount();

        for (int i = 1; i <= columns; i++) 
            columnNames.addElement(md.getColumnName(i));       

        while(rs.next()) {
            Vector<Object> row = new Vector<Object>(6);

            for(int i=1;i<=6;i++)
                row.addElement(rs.getObject(i));

            data.addElement(row);           
        }

        rs.close();
        showStmt.close();

        DefaultTableModel model = new DefaultTableModel(data, columnNames) {            
            @Override
            public Class getColumnClass(int column) {
                for (int row = 0; row < getRowCount(); row++) {
                    Object o = getValueAt(row, column);
                    if (o != null)
                        return o.getClass();                    
                }

                return Object.class;
            }
        };

        dataTable=new JTable(model);
        scrollPane = new JScrollPane(dataTable);
        scrollPane.setBounds(50, 20, 500, 200);
        intFrame.add(scrollPane);
    }   

    private void insertToDB(Connection myConn) throws SQLException {   
        insertForm=new JFrame();
        insertForm.setTitle("Add");
        insertForm.setLayout(null);
        insertForm.setVisible(true);
        insertForm.setSize(600, 450);

        JLabel name=new JLabel("Name:");
        name.setBounds(100,100,50,25);
        JLabel surname=new JLabel("Surname:");        
        surname.setBounds(100,150,50,25);
        JLabel email=new JLabel("E-Mail:");        
        email.setBounds(100,200,50,25);
        JLabel dept=new JLabel("Department:");        
        dept.setBounds(100,250,50,25);
        JLabel salary=new JLabel("Salary:");
        salary.setBounds(100,300,50,25);

        JTextField nameT=new JTextField();
        nameT.setBounds(200,100,100,25);
        JTextField surnameT=new JTextField();
        surnameT.setBounds(200,150,100,25);
        JTextField emailT=new JTextField();
        emailT.setBounds(200,200,100,25);
        JTextField deptT=new JTextField();
        deptT.setBounds(200,250,100,25);
        JTextField salaryT=new JTextField();
        salaryT.setBounds(200,300,100,25);

        JButton insert=new JButton("Add");
        insert.setBounds(400,400,50,25);
        insert.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                try {
                    PreparedStatement insStmt=myConn.prepareStatement("insert into employees" +
                            "(last_name, first_name, email, department, salary)"  +
                            "values" +
                            "(?, ?, ?, ?, ?)");

                    insStmt.setString(1, surnameT.getText());
                    insStmt.setString(2, nameT.getText());
                    insStmt.setString(3, emailT.getText());
                    insStmt.setString(4, deptT.getText());
                    insStmt.setInt(5, Integer.parseInt(salaryT.getText()));

                    insStmt.executeUpdate();
                    insertForm.dispose();

                    intFrame.remove(scrollPane);
                    showDB(myConn);
                } catch (SQLException ex) {
                    Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
                }
            }           
        });

        insertForm.add(name);
        insertForm.add(surname);
        insertForm.add(email);
        insertForm.add(dept);
        insertForm.add(salary);

        insertForm.add(nameT);
        insertForm.add(surnameT);
        insertForm.add(emailT);
        insertForm.add(deptT);
        insertForm.add(salaryT);

        insertForm.add(insert);          
    }

    private JFrame intFrame,rowsFrame,insertForm;
    private JButton showButton, insertButton, deleteButton, updateButton;
    private JTable dataTable;   
    private JScrollPane scrollPane;    

}

1 个答案:

答案 0 :(得分:0)

尝试以下源代码:

CheckedTableExample

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

public class CheckedTableExample {

    private static JFrame frame;
    private static JTable table;
    private static DefaultTableModel model;
    private static final Object[] tableColumnName = new Object[] { "Flag", "Id", "Last Name", "First Name",
            "Department", "Salary" };
    private static JScrollPane pane;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                checkedTableExampleApp();
            }
        });
    }

    private static void checkedTableExampleApp() {
        frame = new JFrame();
        frame.setTitle("Checked JTable Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        frame.setBounds(350, 100, 650, 450);

        initTable();

        JButton addEmp = new JButton("Add...");
        JButton deleteEmp = new JButton("Delete");
        JButton updateEmp = new JButton("Update...");

        addEmp.setBounds(60, 370, 100, 27);
        deleteEmp.setBounds(270, 370, 100, 27);
        updateEmp.setBounds(470, 370, 100, 27);

        frame.getContentPane().add(addEmp);
        frame.getContentPane().add(deleteEmp);
        frame.getContentPane().add(updateEmp);

        addEmp.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                model.setRowCount(model.getRowCount() + 1);

                table.setValueAt(new Boolean(false), model.getRowCount() - 1, 0);
                table.setValueAt(model.getRowCount(), model.getRowCount() - 1, 1);

                table.setValueAt("Siren", model.getRowCount() - 1, 2);
                table.setValueAt("Anna", model.getRowCount() - 1, 3);
                table.setValueAt("Legal", model.getRowCount() - 1, 4);
                table.setValueAt(68000, model.getRowCount() - 1, 5);
            }
        });

        deleteEmp.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                deleteSelected();
            }
        });

        updateEmp.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                updateSelected();
            }
        });

        frame.setVisible(true);
    }

    private static void initTable() {
        Object[][] object = new Object[][] { { false, 1, "Doe", "John", "HR", 55000 },
                { false, 2, "Public", "Mary", "Engineering", 75000 }, 
                { false, 3, "Queue", "Susan", "Legal", 130000 },
                { false, 4, "Williams", "David", "HR", 120000 }, 
                { false, 5, "Johnson", "Lisa", "Engineering", 50000 },
                { false, 6, "Smith", "Paul", "Legal", 100000 } };

        model = new DefaultTableModel(object, tableColumnName) {
            private static final long serialVersionUID = 1L;

            @Override
            public Class<?> getColumnClass(int columnIndex) {
                switch (getColumnName(columnIndex)) {
                case "Flag":
                    return Boolean.class;
                case "Id":
                    return Integer.class;
                case "Last Name":
                    return String.class;
                case "First Name)":
                    return String.class;
                case "Department":
                    return String.class;
                case "Salary":
                    return Integer.class;
                }
                return super.getColumnClass(columnIndex);
            };

            @Override
            public boolean isCellEditable(int row, int col) {
                //only allow to edit the checkbox value
                if (col == 0)
                    return true;
                else
                    return false;
            }
        };

        table = new JTable(model);

        TableCellRenderer rendererFromHeader = table.getTableHeader().getDefaultRenderer();
        JLabel headerLabel = (JLabel) rendererFromHeader;
        headerLabel.setHorizontalAlignment(JLabel.CENTER);
        headerLabel.setVerticalTextPosition(JLabel.CENTER);

        table.setRowHeight(25);
        table.getColumnModel().getColumn(0).setPreferredWidth(35);
        table.getColumnModel().getColumn(1).setPreferredWidth(70);
        table.getColumnModel().getColumn(2).setPreferredWidth(150);
        table.getColumnModel().getColumn(3).setPreferredWidth(150);
        table.getColumnModel().getColumn(4).setPreferredWidth(120);
        table.getColumnModel().getColumn(5).setPreferredWidth(108);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        table.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent evt) {
                JTable source = (JTable) evt.getSource();
                final int tableRow = source.getSelectedRow();
                if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
                    if (tableRow != -1) {
                        if (source.isRowSelected(tableRow)) {
                            boolean flag = Boolean.valueOf(String.valueOf(source.getModel().getValueAt(tableRow, 0)));
                            table.setValueAt(!flag, tableRow, 0);
                        }
                    }
                }
            }
        });

        pane = new JScrollPane(table);
        pane.setBounds(0, 0, 635, 350);
        pane.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        pane.setComponentZOrder(pane.getVerticalScrollBar(), 0);
        pane.setComponentZOrder(pane.getViewport(), 1);
        pane.getVerticalScrollBar().setOpaque(false);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        frame.getContentPane().add(pane);
    }

    private static void deleteSelected() {
        for (int i = model.getRowCount() - 1; i >= 0; i--) {
            if ((boolean) table.getValueAt(i, 0)) {
                model.removeRow(i);
            }
        }
    }

    private static void updateSelected() {
        @SuppressWarnings("unused")
        int count = 0, rowIndex = 0;
        looper: for (int i = 0; i < model.getRowCount(); i++) {
            if ((boolean) table.getValueAt(i, 0)) {
                rowIndex = i;
                count++;
                if (count > 1) {
                    JOptionPane.showMessageDialog(frame, "Select only single row to Update");
                    break looper;
                }
            }
        }

        if (count == 1) {
            // you have the rowIndex
            JOptionPane.showMessageDialog(frame,
                    "Update Employee id : " + table.getValueAt(rowIndex, 1) + " details..");
            // Write your logic to update the selected JTable row...
        }
    }
}