以动态方式向JTable添加值

时间:2014-04-27 21:33:32

标签: java eclipse swing dynamic jtable

我有一个文本框,它向数据库发送了一些内容,jtable列出了数据库中的值。但是当我向数据库添加内容时。 Jtable不要同时显示它。当我关闭程序并再次调试时,它会显示时间。我希望Jtabel在单击“保存”按钮时显示文本框值。我如何创建动态jtable?

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

public class Topic extends JFrame {

    private static final long serialVersionUID = 1L;
    JFrame frmTopic;
    JPanel pnl, pnl_generaltopic;
    static JTextField txt_topic;
    JLabel lbl_topicNme, lbl_topicpage;
    JButton btn_close, btn_update, btn_save;
    public static Connection con = null;
    public static ResultSet rs = null;
    public static Statement st = null;
    static Vector<Vector<String>> data = new Vector<Vector<String>>();
    private JScrollPane scrollPane;
    private static JTable table;

    public Topic() {
        pnl_generaltopic = new JPanel();
        pnl_generaltopic.setBackground(Color.lightGray);
        pnl_generaltopic.setLayout(null);

        frmTopic = new JFrame("Topic");
        frmTopic.addWindowListener(new WindowAdapter() {
            @Override
            public void windowOpened(WindowEvent arg0) {

                con = Dbconnect.conect();
            }
        });
        frmTopic.setTitle("E-TEST");
        frmTopic.setBounds(100, 100, 500, 500);
        frmTopic.setVisible(true);
        frmTopic.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmTopic.getContentPane().setLayout(new BorderLayout(0, 0));
        frmTopic.getContentPane().add(pnl_generaltopic);

        topicPanel();
        topicTable();
    }

    public void topicPanel() {

        JPanel panel_addingNewTopic = new JPanel();
        panel_addingNewTopic.setBounds(10, 0, 464, 203);
        pnl_generaltopic.add(panel_addingNewTopic);
        panel_addingNewTopic.setLayout(null);
        btn_save = new JButton("Save");
        btn_save.setBounds(65, 166, 67, 23);
        panel_addingNewTopic.add(btn_save);
        btn_update = new JButton("Update");
        btn_update.setBounds(142, 162, 90, 30);
        panel_addingNewTopic.add(btn_update);
        btn_close = new JButton("Close");
        btn_close.setBounds(240, 162, 90, 30);
        panel_addingNewTopic.add(btn_close);
        txt_topic = new JTextField();
        txt_topic.setBounds(65, 59, 270, 71);
        panel_addingNewTopic.add(txt_topic);


        lbl_topicNme = new JLabel("Topic Name");
        lbl_topicNme.setBounds(10, 65, 150, 59);
        panel_addingNewTopic.add(lbl_topicNme);
        lbl_topicpage = new JLabel("Topic Page");
        lbl_topicpage.setBounds(10, 11, 300, 20);
        panel_addingNewTopic.add(lbl_topicpage);
        lbl_topicpage.setFont(new Font("arial", Font.BOLD, 15));


        btn_close.addActionListener(new ActionListener() {
                                        public void actionPerformed(ActionEvent e) {
                                            frmTopic.dispose();
                                        }
                                    }
        );

        btn_save.addActionListener(new ActionListener() {
                                       public void actionPerformed(ActionEvent e) {
                                           try {

                                               st = con.createStatement();
                                               String sorgu = "insert into topic " + "(topicname)"
                                                       + "VALUES ('" + txt_topic.getText() + "')";
                                               st.executeUpdate(sorgu);
                                               JOptionPane.showMessageDialog(Topic.this, "Topic was added");
                                           } catch (Exception s) {
                                               System.out.print(s.getMessage());
                                           }
                                       }
                                   }
        );
    }


    public void topicTable() {

        scrollPane = new JScrollPane();
        scrollPane.setBounds(10, 226, 464, 190);
        pnl_generaltopic.add(scrollPane);

        Vector<String> headers = new Vector<String>();
        headers.add("Topic Name");


        getData();

        //this is the model which contain actual body of JTable
        DefaultTableModel model = new DefaultTableModel(data, headers);
        table = new JTable(model);
        scrollPane.setColumnHeaderView(table);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        //table=new JTable(model);
        //table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        header_size();

        //JScrollPane scroll = new JScrollPane(table);

        scrollPane.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        pack();
        setResizable(false);
        setVisible(true);
    }


    /**
     * Setting the particular Column Size in JTable
     */
    public static void header_size() {
        TableColumn column = table.getColumnModel().getColumn(0);
        column.setPreferredWidth(100);

        column = table.getColumnModel().getColumn(0);
        column.setPreferredWidth(350);
    }


    /**
     * Fetching Data From MySql Database
     * and storing in a Vector of a Vector
     * to Display in JTable
     */
    private static void getData() {
        // Enter Your MySQL Database Table name in below Select Query.
        String str = "select * from topics";
        Connection con;
        ResultSet rs;
        Statement st;

        try {
            con = DriverManager.getConnection("jdbc:mysql://" + "localhost:3306/database", "root", "1234");
            st = con.createStatement();
            rs = st.executeQuery(str);

            while (rs.next()) {
                Vector<String> d = new Vector<String>();

                d.add(rs.getString("topicname"));

                d.add("\n\n\n\n\n\n\n");
                data.add(d);
            }

        } catch (SQLException e) {

            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        Topic topic = new Topic();
        topic.setVisible(false);
    }


}

1 个答案:

答案 0 :(得分:1)

您可以使用addRow(...)的{​​{1}}方法在模型中动态添加一行数据。

因此,如果对数据库的更新成功,那么您将调用addRow()方法。

此外,在使用SQL时应使用PreparedStatement。它将使您更容易创建SQL,因为您不需要担心分隔符。给你一个想法的简单例子:

DefaultTableModel