改变" JPanel"使用填充数据在JTable中双击

时间:2016-08-05 08:12:41

标签: java swing jtable layout-manager cardlayout

我正在用Java制作简单的CRUD应用程序,我想为用户选择的结果创建"详细视图" 。我有一个简单的代码,可以创建记录并使用JDBC将它们填充到表中。现在我想要做到这一点,如果用户在JTable中双击行时选择一条记录,他应该看到结果的详细视图。

Class Customer.java

package customereditor;


public class Customer {

    private int Id;
    private String name;
    private String surname;

    public int getID() {
        return Id;
    }

    public void setId(int Id) {
        this.Id = Id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    @Override
    public String toString() {
        return "Customer{" + "ID=" + Id + ", name=" + name + ", surname=" + surname + '}';
    }

}

Class CustomerDao.java

package customereditor;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CustomerDao {

    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection("jdbc:derby://localhost:1527/CustomerEditorDb");
        } catch (SQLException ex) {
            Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return conn;
    }

    public static List<Customer> getAllCustomers() {
        List<Customer> allCustomers = new ArrayList();
        try {
            Connection conn = getConnection();
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM CE_CUSTOMERS");
            while (rs.next()) {
                Customer customer = new Customer();
                customer.setId(rs.getInt(1));
                customer.setName(rs.getString(2));
                customer.setSurname(rs.getString(3));
                allCustomers.add(customer);
            }
        } catch (SQLException ex) {
            Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return allCustomers;
    }

    public static List<String> getColumnNames() {
        List<String> columnNames = new ArrayList();
        try {
            Connection conn = getConnection();
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM CE_CUSTOMERS");
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                String columnName = rsmd.getColumnName(i);
                columnNames.add(columnName);
            }
        } catch (SQLException ex) {
            Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return columnNames;
    }

    public static void createCustomer(Customer customer) {
        try {
            Connection conn = getConnection();
            PreparedStatement pstmt = conn.prepareStatement("INSERT INTO CE_CUSTOMERS(ID, NAME, SURNAME) VALUES (?,?,?)");
            pstmt.setInt(1, customer.getID());
            pstmt.setString(2, customer.getName());
            pstmt.setString(3, customer.getSurname());
            pstmt.execute();
        } catch (SQLException ex) {
            Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static Customer getCustomerById(int customerId) {
        Customer customer = new Customer();
        try {
            Connection conn = getConnection();
            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM CE_CUSTOMERS WHERE ID=?");
            pstmt.setInt(1, customerId);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                customer.setId(rs.getInt(1));
                customer.setName(rs.getString(2));
                customer.setSurname(rs.getString(3));
            }
        } catch (SQLException ex) {
            Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return customer;
    }

    public static void deleteCustomer(int customerId) {
        try {
            Connection conn = getConnection();
            PreparedStatement pstmt = conn.prepareStatement("DELETE FROM CE_CUSTOMERS WHERE ID=?");
            pstmt.setInt(1, customerId);
            pstmt.executeUpdate();
        } catch (SQLException ex) {
            Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


}

Class DataTableModel.java

package customereditor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.table.AbstractTableModel;

public class DataTableModel extends AbstractTableModel {

    private final Map<Integer, Boolean> checkBoxes;
    private final List<String> columnNames;
    private final List<Customer> allCustomers;

    public DataTableModel() {
        this.checkBoxes = new HashMap<>();
        this.columnNames = CustomerDao.getColumnNames();
        this.allCustomers = CustomerDao.getAllCustomers();
    }

    public void addRow(Customer customer) {
        allCustomers.add(customer);
        fireTableRowsInserted(allCustomers.size() - 1, allCustomers.size() - 1);
    }

    public void removeRow(int rowIndex) {
        allCustomers.remove(rowIndex);
        fireTableRowsDeleted(rowIndex, rowIndex);
    }

    @Override
    public String getColumnName(int columnIndex) {
        if (columnIndex > 0) {
            return columnNames.get(columnIndex - 1);
        } else {
            return "#";
        }
    }

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

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

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Customer customer = allCustomers.get(rowIndex);
        switch (columnIndex) {
            case 0:
                Object value = checkBoxes.get(rowIndex);
                return (value == null) ? Boolean.FALSE : value;
            case 1:
                return customer.getID();
            case 2:
                return customer.getName();
            case 3:
                return customer.getSurname();
            default:
                return null;
        }
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        if (columnIndex > 0) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void setValueAt(Object value, int rowIndex, int columnIndex) {
        if (columnIndex > 0) {
            Customer customer = allCustomers.get(rowIndex);
            switch (columnIndex) {
                case 1:
                    customer.setId((int) value);
                case 2:
                    customer.setName((String) value);
                case 3:
                    customer.setSurname((String) value);
            }
        } else {
            checkBoxes.put(rowIndex, (boolean) value);
        }
    }

    @Override
    public Class getColumnClass(int columnIndex) {
        switch (columnIndex) {
            case 0:
                return Boolean.class;
            case 1:
                return Integer.class;
            case 2:
                return String.class;
            case 3:
                return String.class;
            default:
                return String.class;

        }

    }

}

Class CustomerEditorMain.java

package customereditor;

import javax.swing.JFrame;

public class CustomerEditorMain {

    private static void createAndShowGui() {
        //Create and set up the window.
        JFrame frame = new JFrame("TableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        CustomerView view = new CustomerView();
        frame.add(view);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {        

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }

}
  • Class Customer.java是简单的POJO。
  • Class CustomerDao.java适用于derby DB。
  • 类DataTableModel.java是CustomerView.java中JTable的模型。该模型使用三个集合框架。一个用于添加复选框以仅删除选定的行。其他用于存储来自JDBC的列名和数据。
  • Class CustomerEditorMain.java只是运行程序。
  • Class CustomerView.java 包含swing组件。在这里,我希望在表格中创建类似于详细视图的记录。我可以在这里做一个名为detailCustomerViewPanel的简单方法,返回JPanel。此方法需要customerId。此customerId是从JTable中的选定行中选择的。用户按下双击行后,JPanel也会更改。

Class CustomerView.java

package customereditor;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;

public class CustomerView extends JPanel {

    private final CardLayout cardLayout;
    private final JPanel cards;
    private final DataTableModel dataModel;
    private final JTable table;

    public CustomerView() {
        this.cardLayout = new CardLayout();
        this.cards = new JPanel(cardLayout);
        this.dataModel = new DataTableModel();
        this.table = new JTable(dataModel);
        initComponents();
    }

    private void initComponents() {
        setLayout(new BorderLayout());
        add(createButtonsPanel(), BorderLayout.PAGE_START);
        cards.add(createShowAllCustomersPanel(), "createShowAllCustomersPanel");
        cards.add(createNewCustomerPanel(), "createNewCustomerPanel");
        add(cards, BorderLayout.CENTER);
    }

    private JPanel createButtonsPanel() {
        JPanel buttonsPanel = new JPanel(new FlowLayout());
        JButton createNewCustomer = new JButton("New");
        createNewCustomer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(cards, "createNewCustomerPanel");
            }
        });
        buttonsPanel.add(createNewCustomer);
        JButton deleteCustomer = new JButton("Delete");
        deleteCustomer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (int i = dataModel.getRowCount() - 1; i >= 0; i--) {
                    boolean checked = (boolean) dataModel.getValueAt(i, 0);
                    if (checked) {
                        CustomerDao.deleteCustomer((int) dataModel.getValueAt(i, 1));
                        dataModel.removeRow(i);
                        dataModel.setValueAt(Boolean.FALSE, i, 0);
                    }
                }
            }
        });
        buttonsPanel.add(deleteCustomer);
        return buttonsPanel;
    }

    private JPanel createShowAllCustomersPanel() {
        JPanel createShowAllCustomersPanel = new JPanel(new BorderLayout());
        table.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    // get ID value from selected row and "first" column
                    int getCustomerId = (int) table.getValueAt(table.getSelectedRow(), 1);
                    // create JPanel and add to cards
                    cards.add(detailCustomerViewPanel(getCustomerId), "detailCustomerViewPanel");
                    cardLayout.show(cards, "detailCustomerViewPanel");
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }
        });
        JScrollPane paneTable = new JScrollPane(table);
        createShowAllCustomersPanel.add(paneTable);
        return createShowAllCustomersPanel;
    }

    private JPanel createNewCustomerPanel() {
        JPanel createNewCustomerPanel = new JPanel();
        JLabel idLabel = new JLabel("Id:");
        createNewCustomerPanel.add(idLabel);
        JTextField idField = new JTextField(10);
        createNewCustomerPanel.add(idField);
        JLabel nameLabel = new JLabel("Name:");
        createNewCustomerPanel.add(nameLabel);
        JTextField nameField = new JTextField(10);
        createNewCustomerPanel.add(nameField);
        JLabel surnameLabel = new JLabel("Surname:");
        createNewCustomerPanel.add(surnameLabel);
        JTextField surnameField = new JTextField(10);
        createNewCustomerPanel.add(surnameField);
        JButton saveButton = new JButton("Save");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (idField.getText() != "") {
                    Customer customer = new Customer();
                    customer.setId(Integer.parseInt(idField.getText()));
                    customer.setName(nameField.getText());
                    customer.setSurname(surnameField.getText());
                    CustomerDao.createCustomer(customer);
                    dataModel.addRow(customer);
                }
            }
        });
        createNewCustomerPanel.add(saveButton);
        JButton closeButton = new JButton("Close");
        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(cards, "createShowAllCustomersPanel");
            }
        });
        createNewCustomerPanel.add(closeButton);
        return createNewCustomerPanel;
    }

    private JPanel detailCustomerViewPanel(int customerId) {
        JPanel detailCustomerViewPanel = new JPanel(new FlowLayout());
        // get customer by ID
        Customer customer = CustomerDao.getCustomerById(customerId);
        JLabel idLabel = new JLabel("Id:");
        detailCustomerViewPanel.add(idLabel);
        JTextField idField = new JTextField(10);
        idField.setText(Integer.toString(customer.getID()));
        detailCustomerViewPanel.add(idField);
        JLabel nameLabel = new JLabel("Name:");
        detailCustomerViewPanel.add(nameLabel);
        JTextField nameField = new JTextField(10);
        nameField.setText(customer.getName());
        detailCustomerViewPanel.add(nameField);
        JLabel surnameLabel = new JLabel("Surname:");
        detailCustomerViewPanel.add(surnameLabel);
        JTextField surnameField = new JTextField(10);
        surnameField.setText(customer.getSurname());
        detailCustomerViewPanel.add(surnameField);
        JButton closeButton = new JButton("Close");
        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(cards, "createShowAllCustomersPanel");
            }
        });
        detailCustomerViewPanel.add(closeButton);
        return detailCustomerViewPanel;
    }

}

所以我的问题是:有更好的方法吗?

0 个答案:

没有答案