繁体   English   中英

从Jcombobox选择后如何更新JTable的信息

[英]How to update info of JTable after selection from Jcombobox

我正在开始Jave开发人员。 我正在开发一个程序,该程序说明数据库中员工的数据。 员工关注组合框所示的部门。 这是我的代码:

package gm;

import java.sql.Connection;
public class Department extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Connection connection = null;
    private PreparedStatement statement = null;
    private JTable table;
    private Vector<Object> temp;

    public Department() {
        super("Табель Сотрудников");
        String[] department = { "Юристы", "Логистика", "Отел кадров", "MIS",
                "Внешняя Торговля", "Внутреняя Торговля", "Планирование",
                "Казночейство", "   Бухгалтерия", "Аудит", "ГБО", "Автосервис",
                "Мониторинг, развитие бизнеса", "Канцелярия", "Фин. отдел",
                "Закупки", "Разв. новых пректов", " Маркетинг", "Администрация" };
        JPanel p = new JPanel();
        p.setBackground(new Color(0, 255, 255));

        temp = new Vector<Object>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager
                    .getConnection("jdbc:mysql://localhost/tabel?user=root&password=4499669");
            statement = connection
                    .prepareStatement("select id,tab_num,name_surname,position,worked_hours from department d, employee e,"
                            + " hours h where d.id_dept=e.id_dept and h.emp_id=e.id");
            ResultSet r = statement.executeQuery();

            while (r.next()) {
                Vector<Object> tmp = new Vector<Object>(6);
                tmp.add(r.getObject("id"));
                tmp.add(r.getObject("tab_num"));
                tmp.add(r.getObject("name_surname"));
                tmp.add(r.getObject("position"));
                tmp.add(r.getObject("worked_hours"));
                temp.add(tmp);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                connection.close();

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        //System.out.println(temp);
        Avans1 av = new Avans1();
        Zarplata z = new Zarplata();
        Vector<String> columns = new Vector<String>();
        columns.add("ID");
        columns.add("Tab Number");
        columns.add("Name Surname");
        columns.add("Position");
        columns.add("Worked Hours");
        DefaultTableModel model = new DefaultTableModel(temp, columns);
        getContentPane().add(p);

        JLabel d_n = new JLabel("Подразделение");
        p.add(d_n);
                JComboBox co = new JComboBox(department);
                p.add(co);
                co.setBackground(new Color(102, 205, 170));

        JButton avans = new JButton("Аванс");
        p.add(avans);
        avans.addActionListener(av);
        JButton zarp = new JButton("Зарплата");
        p.add(zarp);
        zarp.addActionListener(z);

        JScrollPane scrollPane_1 = new JScrollPane();
        p.add(scrollPane_1);

        JPanel panel = new JPanel();
        panel.setBackground(new Color(124, 252, 0));
        scrollPane_1.setViewportView(panel);

        table = new JTable();
        table.setBorder(new LineBorder(null));
        table.setModel(model);
        table.getColumnModel().getColumn(2).setPreferredWidth(300);
        table.getColumnModel().getColumn(4).setPreferredWidth(200);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
/////////////////////////////////////////////////////////////
this part should read appropriate info to selected item of combobox from database
        co.addItemListener(new ItemListener() {


            public void itemStateChanged(ItemEvent event) {
                if(event.getStateChange()==ItemEvent.SELECTED)
                {   
                    try {
                        Class.forName("com.mysql.jdbc.Driver");
                        connection = DriverManager
                                .getConnection("jdbc:mysql://localhost/tabel?user=root&password=4499669");
                        statement = connection
                                .prepareStatement("select id,tab_num,name_surname,position,worked_hours from department d, employee e,"
                                        + " hours h where d.id_dept=e.id_dept and h.emp_id=e.id");
                        ResultSet r = statement.executeQuery();

                        while (r.next()) {
                            Vector<Object> tmp = new Vector<Object>(6);
                            tmp.add(r.getObject("id"));
                            tmp.add(r.getObject("tab_num"));
                            tmp.add(r.getObject("name_surname"));
                            tmp.add(r.getObject("position"));
                            tmp.add(r.getObject("worked_hours"));
                            temp.add(tmp);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            connection.close();

                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }

                    System.out.println(event.getItem());
                }
            }


        });
/////////////////////////////////////////////////////////////       





        JScrollPane scrollPane = new JScrollPane(table,
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        Dates dat = new Dates();
        dat.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        dat.setSize(850, 470);
        dat.setVisible(true);
        panel.add(scrollPane);



    }
    private class Avans1 implements ActionListener{
        public void actionPerformed(ActionEvent evend){
            Class1 c = new Class1();
            c.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            c.setSize(850,470);
            c.setVisible(true);
        }
    }
    private class Zarplata implements ActionListener{
        public void actionPerformed(ActionEvent evend){
            Class2 c = new Class2();
            c.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            c.setSize(850,470);
            c.setVisible(true);
        }
    }
    private void reloadData() throws ClassNotFoundException,SQLException{


    }
}

从Jcombobox选择后如何更新JTable的信息

最简单的方法是创建一个Mew TableModel,然后使用以下方法更改表的模型:

table.setModel( newlyCreatedTableModel );

因此,这意味着您将需要删除“临时”向量中的所有数据,以便可以将新数据添加到向量中。 然后,执行SQL查询,遍历ResultSet以获取数据,然后使用Vector中的数据创建一个新的TableModel。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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