简体   繁体   English

使用Jcombobox更改项目后无法编辑jtable

[英]Editing the jtable after item change using Jcombobox is not working

Im making a project about school management system , i have a jframe to set marks and inside the jframe i have a jtable which is connected to sql database , in the jframe i have a JCombobox with 6 different subjects and in my database i have created 6 tables for the subjects and if any of the subjects are clicked then the jTable will connect to database and change the table to that subject , after its changed if u double click on any row and insert a value then it will automatically update the table in the database , but my problem is that if i select the first option from the jcombox which is English and edit the values then it works fine , but if i select any other option eg Math or Science , then i try to edit the table then it edits the English table , I commented the English option in the code to see what happens and i saw that it edits only the first option and if u try to change the subjects and edit than it edits the first subject in the combobox , so how can i solve this ? 我正在做一个有关学校管理系统的项目,我有一个用于设置标记的jframe,并且在jframe中有一个连接到sql数据库的jtable,在jframe中,我有一个JCombobox包含6个不同的主题,在我的数据库中,我创建了6个主题表,如果单击任何主题,则jTable将连接到数据库并将表更改为该主题。更改后,如果您双击任何行并插入值,它将自动更新表中的表。数据库,但是我的问题是,如果我从jcombox中选择英语的第一个选项并编辑值,那么它可以正常工作,但是如果我选择任何其他选项,例如Math或Science,则我尝试编辑表然后对其进行编辑在英语表中,我注释了代码中的英语选项以查看发生的情况,我看到它仅编辑第一个选项,如果您尝试更改主题并编辑,而不是编辑组合框中的第一个主题,那么我怎么办?解决这个问题? please help 请帮忙

CODE: 码:

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JToolBar;
import javax.swing.event.TableModelEvent;
import javax.swing.event.*;
import javax.swing.table.TableModel;
import net.proteanit.sql.DbUtils;

public class Marks implements TableModelListener {

    JFrame frame;
    JTable table;
    JComboBox comboBox;
    static Connection connection = null;
    static Statement stmt = null;
    static ResultSet rs;
    String item = "";
    String id = "";
    String name = "";


    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Marks window = new Marks();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Marks() throws SQLException {

        connection = DriverManager.getConnection("jdbc:odbc:Project");

        initialize();
        table();
        ComboItem();
        stateChanged();    
        Combobox();
        item = comboBox.getSelectedItem().toString();
        System.out.println("Final Item: "+item);
    }

    public void table() {
        try {
            String a = comboBox.getSelectedItem().toString();
            //a = a.substring(0, a.length() - 1);
            String query = " Select * from " + a;
            PreparedStatement pst = connection.prepareStatement(query);
            rs = pst.executeQuery();
            table.setModel(DbUtils.resultSetToTableModel(rs));
            //item = comboBox.getSelectedItem().toString();

        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public void stateChanged(){
        itemListener = new ItemListener() {
            public void itemStateChanged(ItemEvent itemEvent) {
                System.out.println("Item after stateChanged: " + item);
                if (comboBox.getSelectedItem().equals("English")) {
                    try {
                        String query = "Select * from English";
                        PreparedStatement pst = connection.prepareStatement(query);
                        rs = pst.executeQuery();
                        table.setModel(DbUtils.resultSetToTableModel(rs));
                        table.getModel().addTableModelListener(new Marks());
                        item = "English";
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }

                if (comboBox.getSelectedItem().equals("Math")) {
                    try {
                        String query = "Select * from Math";
                        PreparedStatement pst = connection.prepareStatement(query);
                        rs = pst.executeQuery();
                        table.setModel(DbUtils.resultSetToTableModel(rs));
                        table.getModel().addTableModelListener(new Marks());
                        item = "Math";
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }

                if (comboBox.getSelectedItem().equals("Science")) {
                    try {
                        String query = "Select * from Science;";
                        PreparedStatement pst = connection.prepareStatement(query);
                        rs = pst.executeQuery();
                        table.setModel(DbUtils.resultSetToTableModel(rs));
                        table.getModel().addTableModelListener(new Marks());
                        item = "Science";
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }

                if (comboBox.getSelectedItem().equals("History")) {
                    try {
                        String query = "Select * from History;";
                        PreparedStatement pst = connection.prepareStatement(query);
                        rs = pst.executeQuery();
                        table.setModel(DbUtils.resultSetToTableModel(rs));
                        table.getModel().addTableModelListener(new Marks());
                        item = "History";
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }

                if (comboBox.getSelectedItem().equals("IT")) {
                    try {
                        String query = "Select * from IT;";
                        PreparedStatement pst = connection.prepareStatement(query);
                        rs = pst.executeQuery();
                        table.setModel(DbUtils.resultSetToTableModel(rs));
                        table.getModel().addTableModelListener(new Marks());
                        item = "IT";
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }

                if (comboBox.getSelectedItem().equals("Geography")) {
                    try {
                        String query = "Select * from Geography;";
                        PreparedStatement pst = connection.prepareStatement(query);
                        rs = pst.executeQuery();
                        table.setModel(DbUtils.resultSetToTableModel(rs));
                        table.getModel().addTableModelListener(new Marks());
                        item = "Geography";
                    } catch (Exception ex) {
                        ex.printStackTrace();

                    }

                }
            }
        };
    }

    @Override
    public void tableChanged(TableModelEvent e) {

        try {
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel) e.getSource();
            String columnName = model.getColumnName(column);
            Object data = model.getValueAt(row, column);
            Object roll = model.getValueAt(row, 0);
            System.out.println("Subject Changed: " + item);
            System.out.println("New Data: " + data.toString());
            System.out.println("User Id: " + roll.toString());
            System.out.println("Column name: " + columnName);

            String query = "UPDATE " + item + " SET " + columnName + " = '"
                    + data.toString() + "' WHERE userid='" + roll.toString() + "' ";

            PreparedStatement pst;

            pst = connection.prepareStatement(query);

            pst.executeUpdate();
            // pst.close();
        } catch (SQLException ex) {
            Logger.getLogger(Marks.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }

    }
    ItemListener itemListener;

    public void ComboItem(){        
        comboBox.addItemListener(itemListener);
    }

    private void Combobox() {
        comboBox.addItemListener(itemListener);

        comboBox.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                System.out.println(item);

               if (comboBox.getSelectedItem().equals("English")) {
                    try {
                        String query = "Select * from English";
                        PreparedStatement pst = connection.prepareStatement(query);
                        rs = pst.executeQuery();
                        table.setModel(DbUtils.resultSetToTableModel(rs));
                        table.getModel().addTableModelListener(new Marks());
                        item = "Engish";
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }

                if (comboBox.getSelectedItem().equals("Math")) {
                    try {
                        String query = "Select * from Math";
                        PreparedStatement pst = connection.prepareStatement(query);
                        rs = pst.executeQuery();
                        table.setModel(DbUtils.resultSetToTableModel(rs));
                        table.getModel().addTableModelListener(new Marks());
                        item = "Math";
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }

                if (comboBox.getSelectedItem().equals("Science")) {
                    try {
                        String query = "Select * from Science;";
                        PreparedStatement pst = connection.prepareStatement(query);
                        rs = pst.executeQuery();
                        table.setModel(DbUtils.resultSetToTableModel(rs));
                        table.getModel().addTableModelListener(new Marks());
                        item = "Science";
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }

                if (comboBox.getSelectedItem().equals("History")) {
                    try {
                        String query = "Select * from History;";
                        PreparedStatement pst = connection.prepareStatement(query);
                        rs = pst.executeQuery();
                        table.setModel(DbUtils.resultSetToTableModel(rs));
                        table.getModel().addTableModelListener(new Marks());
                        item = "History";
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }

                if (comboBox.getSelectedItem().equals("IT")) {
                    try {
                        String query = "Select * from IT;";
                        PreparedStatement pst = connection.prepareStatement(query);
                        rs = pst.executeQuery();
                        table.setModel(DbUtils.resultSetToTableModel(rs));
                        table.getModel().addTableModelListener(new Marks());
                        item = "IT";
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }

                if (comboBox.getSelectedItem().equals("Geography")) {
                    try {
                        String query = "Select * from Geography;";
                        PreparedStatement pst = connection.prepareStatement(query);
                        rs = pst.executeQuery();
                        table.setModel(DbUtils.resultSetToTableModel(rs));
                        table.getModel().addTableModelListener(new Marks());
                        item = "Geography";
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }

            }
        });
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.getContentPane().setBackground(Color.WHITE);
        frame.setBounds(100, 100, 600, 400);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //frame.setResizable(false);
        frame.getContentPane().setLayout(null);

        JLabel lblSetMarks = new JLabel("<html><u>Set Marks</u></html>");
        lblSetMarks.setHorizontalAlignment(SwingConstants.CENTER);
        lblSetMarks.setFont(new Font("Castellar", Font.BOLD, 25));
        lblSetMarks.setBounds(218, 11, 159, 22);
        frame.getContentPane().add(lblSetMarks);

        comboBox = new JComboBox();
        comboBox.setFont(new Font("Book Antiqua", Font.PLAIN, 15));
        comboBox.setBounds(459, 47, 125, 22);
        comboBox.addItem("English");
        comboBox.addItem("Geography");
        comboBox.addItem("History");
        comboBox.addItem("IT");
        comboBox.addItem("Math");
        comboBox.addItem("Science");
        frame.getContentPane().add(comboBox);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(10, 87, 574, 259);
        frame.getContentPane().add(scrollPane);

        table = new JTable();

        scrollPane.setViewportView(table);

        JLabel lblClass = new JLabel("Date :");
        lblClass.setFont(new Font("Tahoma", Font.PLAIN, 15));
        lblClass.setBounds(10, 51, 58, 14);
        frame.getContentPane().add(lblClass);

        JLabel lblSubject = new JLabel("Subject :");
        lblSubject.setFont(new Font("Tahoma", Font.PLAIN, 15));
        lblSubject.setBounds(391, 49, 58, 18);
        frame.getContentPane().add(lblSubject);
    }
}

The problem revolves around the use of table.getModel().addTableModelListener(new Marks()); 问题围绕着使用table.getModel().addTableModelListener(new Marks()); , which is creating a new instance of Marks , which your main class, each time you select a new project ,这会在您每次选择新项目时创建一个新的Marks实例,这是您的主类

This means that when tableChanged is called, it's not dealing with the instance of item which you modified in the original instance, but some other instance, which is ALWAYS set to English 这意味着在tableChanged时,它不会处理您在原始实例中修改的item实例,而是处理其他实例(始终设置为English

Instead, you should try using something like table.getModel().addTableModelListener(this); 相反,您应该尝试使用诸如table.getModel().addTableModelListener(this); instead, but only set it ONCE from within the constructor, otherwise it will be called multiple times, which will degrade the performance of your system... 而是只在构造函数中一次设置它,否则它将被多次调用,这将降低系统的性能...

Be Careful using a TableModelListener , it will be called when a cell is changed, row is changed, added, removed or the entire contents of the table model is changed. 使用TableModelListener要小心,当更改单元格,更改行,添加,删除或更改表模型的全部内容时,将调用它。 You should be trying to determine the actual type of event before trying to update the database, as you could end up updating the data to the wrong tables for the wrong reasons 您应该先尝试确定事件的实际类型,然后再尝试更新数据库,因为由于错误的原因最终可能会将数据更新到错误的表中

You should avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. 您应该避免使用null布局,像素完美布局是现代ui设计中的一种幻觉。 There are too many factors which affect the individual size of components, none of which you can control. 有太多因素会影响组件的单个大小,您无法控制。 Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify. Swing旨在与布局经理为核心一起工作,舍弃这些问题不会导致问题和问题的终结,您将花费越来越多的时间来进行纠正。

It would seriously discourage the use of a KeyListener on a JComboBox (I'd seriously discourage the use of KeyListener generally), it's not the best choice of listener for this case, besides, you now have two ItemListener s and a KeyListener attached to your combobox, all doing the same thing...multiple times... 这会严重阻止在JComboBox上使用KeyListener (我通常会严重阻止使用KeyListener ),对于这种情况,这不是最佳的监听器选择,此外,您现在有两个ItemListener和一个KeyListener附加到您的组合框,都在做同一件事...多次...

Get rid of the ItemListener and use an ActionListener instead, ItemListener may be triggered multiple times (once for the deselection of the selected item and once of the selection of the new item) and frankly, you just don't care, you only want to know when it's changed. 摆脱ItemListener并改用ActionListenerItemListener可能会被多次触发(一次取消选中选定项,一次选定新项),并且坦率地说,您不在乎,您只想知道何时更改。

Take a look at: 看一眼:

for more details 更多细节

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

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