在数据库中删除或插入后如何触发Jtable更新?

时间:2018-11-23 09:47:57

标签: java database swing

我不知道删除或从其他JDialog插入后如何刷新JTable中的数据。我尝试在删除后通过调用tabela();来初始化JTable中的数据,但这是行不通的。

import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class LekariD extends JDialog {

    private final JPanel contentPanel = new JPanel();
    private JTable table;
    private String lekar;
    private DefaultTableModel model1;

    public static void main(String[] args) {
        try {
            LekariD dialog = new LekariD();
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.setVisible(true);
            dialog.setLocationRelativeTo(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    Connection con = null;

    public void tabela () {

        Vector<Object> columnNames = new Vector<Object>();
        Vector<Object> data = new Vector<Object>();

        try {
            String sql = "Select * from lekari";
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery( sql );
            java.sql.ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();

            columnNames.addElement("Ime Lekara");
            columnNames.addElement("LBO");

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

                for (int i = 1; i <= columns; i++) {
                    row.addElement( rs.getObject(i) );
                }
                data.addElement( row );
            }
            rs.close();
            stmt.close();  

        } catch (Exception e) {
            System.out.println( e );
        }

        model1 = 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;
            }
        };
    }

    /**
     * Create the dialog.
     */
    public LekariD() {

        con = DatabaseConnector.dbConnector();

        tabela();

        setBounds(100, 100, 514, 654);
        getContentPane().setLayout(new BorderLayout());
        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        getContentPane().add(contentPanel, BorderLayout.CENTER);
        contentPanel.setLayout(null);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(10, 126, 339, 478);
        contentPanel.add(scrollPane);

        table = new JTable(model1);
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                DefaultTableModel model=(DefaultTableModel)table.getModel();
                int selectedRowIndex = table.getSelectedRow();

                lekar = model.getValueAt(selectedRowIndex, 0).toString();
            }
        });
        table.setFillsViewportHeight(true);
        scrollPane.setViewportView(table);

        JButton btnNewButton = new JButton("Unos");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                NoviLekarD nl = new NoviLekarD();
                nl.setLocationRelativeTo(null);
                nl.setVisible(true);
            }
        });
        btnNewButton.setBounds(359, 126, 129, 44);
        contentPanel.add(btnNewButton);

        JButton btnNewButton_1 = new JButton("Brisanje");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {            
                try {
                    String query = "delete from lekari where ime_lekar = '"+lekar+"' ";
                    Statement stmt1 = con.prepareStatement(query);
                    stmt1.executeUpdate(query);
                    stmt1.close();

                    JOptionPane.showMessageDialog(contentPanel, "Uspešno obrisan podatak", "Brisanje !", JOptionPane.INFORMATION_MESSAGE);
                } catch (Exception e2) {
                    System.out.println( e2 );
                }
                //tabela(); - tried with this but don't work
            }
        });

        btnNewButton_1.setBounds(359, 212, 129, 44);
        contentPanel.add(btnNewButton_1);

        JButton btnNewButton_2 = new JButton("Izlaz");
        btnNewButton_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    con.close();
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                dispose();
            }
        });
        btnNewButton_2.setBounds(359, 560, 129, 44);
        contentPanel.add(btnNewButton_2);

        JLabel lblSpisakLekara = new JLabel("Spisak lekara");
        lblSpisakLekara.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 18));
        lblSpisakLekara.setBounds(10, 42, 139, 38);
        contentPanel.add(lblSpisakLekara);  
    }
}

1 个答案:

答案 0 :(得分:2)

让我们看看发生了什么:

  1. 调用tabela()时,您查询数据库并在new DefaultTableModel中创建一个model1
  2. LekariD()中进行构建期间,您将创建一个JTable的新实例,并为其提供model1
  3. 更改后,您将更新数据库并再次调用tabela()。这将在new DefaultTableModel中创建一个model1。您的表格仍保留前一个DefaultTableModel,并在需要绘制某些数据时进行查询。

因此,tabela()之后您要做的就是为表提供新的表模型:

table.setModel(model1);

这会让您的表了解新数据,并使其重新计算列,重绘自身等。