简体   繁体   中英

How to update info of JTable after selection from Jcombobox

I am beginning Jave developer. I am developing programm that illustrates data of employees from database. Employees concern to departments which are illustrated with combobox. Here is my code:

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{


    }
}

How to update info of JTable after selection from Jcombobox

The easiest way is to create a mew TableModel and then just change the model of the table by using:

table.setModel( newlyCreatedTableModel );

So this means you will need to delete all the data in your "temp" Vector so that you can add new data to the Vector. Then you do you SQL query, iterate through the ResultSet to get the data and then create a new TableModel with the data in the Vector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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