首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从jlist中选择并使用复选框更新jtable

从jlist中选择并使用复选框更新jtable
EN

Stack Overflow用户
提问于 2015-02-04 08:35:57
回答 1查看 1.2K关注 0票数 0

我在jtable中编写了一个java程序,其中我有两个jlist(主类别和子类别)和一个从mysql数据库中检索值的jtable,在jtable中有一个额外的列供复选框,当用户选择几行并从jlist中选择值时,它会自动更新jtable中的2列(主类别和子类别),我面临的问题是,第一次选择一对行并更新它时,它运行得很好,但是当您选择两个不同的行并更新之前和之前选择的行以及您刚刚选择的行时,我该如何解决这个问题呢?请帮帮忙

我的代码:

代码语言:javascript
运行
复制
//Import Statements
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.JLabel;
import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.PreparedStatement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.Refreshable;

import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JTextField;

import net.proteanit.sql.DbUtils;

public class stock extends JFrame implements MouseListener {

    Object selectedCellValue[] = new Object[50];//Variable for selecting cell in JTable

    static Connection connection = null;//Connects to sql
    static Statement stmt = null;//Makes sql query or statement 
    static ResultSet rs = null;//gets results from the query

    JLabel lblDate;
    JLabel lblUpdateStock;
    JLabel lblcategory;
    JLabel lblSubcategory;

    JTextField txtPartNo;
    int selectedRow[] = new int[5000];//variable which stores selected row in a table 
    static int index = 0;


    static JTable table;

    JList main_list;//Main category
    JList sub_list;//Sub category

    JScrollPane scrollPane_1;
    private static String[] categories = {"Accessories", "Boxed Accessories", "Cordless", "Demolition", "Drilling", "Dust Extraction Accessories", "Garden / Agriculture Tools", "Grinding", "Grinding / Cutting", "Nibblers", "Petrol Engine Tools", "Planing", "Rotary / Demolition", "Rotary Drilling", "Routing", "Routing / Planing", "Sanding / Polishing", "Sawing", "Screwdriving", "Shears"};
    private static String[] sub_categories = {"Abrasive Belt", "Abrasive Disc / Pad", "Abrasive Paper", "Abrasive Wheels", "Accessories", "Accessories for Core Cutters", "Adapter / Drill Chuck / Dust bag", "Adapters / Battery Holder / Bulb", "Band Saw Blades and Accessories", "Battery / Charger Reference Chart", "Battery Chargers", "Belt Sander Accessories", "Broach Cutter for Magnetic Drilling Machine", "Brush and Dust bag", "Brush Cutter Accessories", "Chain Mortiser Accessories", "Chisels", "Combination Sets", "Core Bits", "Core Cutters", "Cut-out Tool Accessories", "Cutting metal", "Diamond Polishing Pad", "Drill Bits", "Drill Bits / Chisels", "Drill Bits / Holesaws", "Drill Chuck", "Drill Chucks / Angle Attachment", "Drill Stand", "Driver Drills / Bit Sets", "Dust Bag", "Dust Cover / Bag", "Extension Bar / Universal Joint / Adapters / Assembly", "Filters", "Flanges", "Glass and Tiles", "Grip", "Grip / Trolley", "Grip/ Loop Handle / Wrenches", "Guide Rule / Guide Rail", "Hammer Service Kits / Oil supply", "Hedge Trimmer Blades", "Hole saw", "Hook and Oil", "Hoses & Pipes", "Impact Sockets", "Jig Saw Accessories", "Jig Saw Blades", "Lawn Mower Blades", "Lithium-ion Batteries", "Maccess Accessories Set", "Masonry", "Masonry, Concrete", "Metal", "Mixing Blades", "Ni-Cd Batteries", "Nibbling Accessories", "Nozzles", "Oil / Grip", "Other Accessories", "Other Blades", "Other Blades & Rings", "Pad", "Petrol Blower Accessories", "Philips Bits", "Philips Bits Holder / Socket Bits", "Planner Accessories", "Plate Joiner Accessories", "Reciprocating Saw Blades", "Router Bits", "Router Bits / Impact Sockets", "Scroll Saw Blades", "Shearing Accessories", "Slide Compound / Miter Saw Accessories", "Slotted Bits", "Specialized Blades", "System Charts", "Table and Stand", "Table Saw Accessories", "Thin Cutting Wheels", "Trimmer, Router, Sash Router Accessories", "Wood", "Wood Cutting"};

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                stock frame = new stock();
                frame.setVisible(true);
            }
        });
    }

    /**
     * Create the frame.
     */
    public stock() {
        getContentPane().setBackground(new Color(176, 224, 230));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 664, 698);
        setResizable(false);
        setLocationRelativeTo(null);
        getContentPane().setLayout(null);

        // Customer List
        ImageIcon titleIcon = new ImageIcon("C:\\Users\\Samir\\Desktop\\banner.jpg");
        lblUpdateStock = new JLabel(titleIcon);
        lblUpdateStock.setFont(new Font("Castellar", Font.BOLD, 28));
        lblUpdateStock.setBounds(0, 0, 658, 111);
        getContentPane().add(lblUpdateStock);

        JLabel lblPartNo = new JLabel("Part No :");
        lblPartNo.setFont(new Font("Bookman Old Style", Font.PLAIN, 16));
        lblPartNo.setBounds(20, 132, 70, 14);
        getContentPane().add(lblPartNo);

        txtPartNo = new JTextField();
        txtPartNo.setBounds(100, 127, 172, 24);
        getContentPane().add(txtPartNo);
        txtPartNo.setColumns(10);

        lblcategory = new JLabel("Main Category");
        lblcategory.setFont(new Font("Calisto MT", Font.PLAIN, 16));
        lblcategory.setBounds(103, 173, 127, 24);
        getContentPane().add(lblcategory);

        lblSubcategory = new JLabel("Sub Category");
        lblSubcategory.setFont(new Font("Bookman Old Style", Font.PLAIN, 16));
        lblSubcategory.setBounds(432, 173, 107, 24);
        getContentPane().add(lblSubcategory);

        // ScrollPane
        JScrollPane scrollPane2 = new JScrollPane();
        scrollPane2.setBounds(20, 480, 617, 154);
        getContentPane().add(scrollPane2);

        // Table
        table = new JTable();
        scrollPane2.setViewportView(table);

        // Button Update
        JButton btnUpdate = new JButton("update");
        btnUpdate.setBounds(274, 439, 107, 30);
        btnUpdate.setFont(new Font("Copperplate Gothic Bold", Font.PLAIN, 18));
        btnUpdate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    UpdateData();
                    PopulateData();
                } catch (SQLException ex) {
                    Logger.getLogger(stock.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        });
        getContentPane().add(btnUpdate);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(20, 202, 287, 226);
        getContentPane().add(scrollPane);
        main_list = new JList(categories);

        scrollPane.setViewportView(main_list);
        main_list.setFont(new Font("Simplified Arabic Fixed", Font.PLAIN, 15));
        main_list.setVisibleRowCount(3);
        main_list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        scrollPane_1 = new JScrollPane();
        scrollPane_1.setBounds(336, 202, 301, 226);
        getContentPane().add(scrollPane_1);
        sub_list = new JList(sub_categories);
        scrollPane_1.setViewportView(sub_list);
        sub_list.setFont(new Font("Simplified Arabic Fixed", Font.PLAIN, 15));
        sub_list.setVisibleRowCount(3);
        sub_list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);


        PopulateData();

        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1) {
                    JTable target = (JTable) e.getSource();

                    selectedRow[index] = target.getSelectedRow();
                    int selectedColumn = 0;

                    selectedCellValue[index] = target.getValueAt(selectedRow[index], selectedColumn);
                    index++;
                }
            }
        });

    }

    private static void PopulateData() {

        // Clear table
        table.setModel(new DefaultTableModel());

        // Model for Table
        DefaultTableModel model = new DefaultTableModel() {
            public Class<?> getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return String.class;
                    case 3:
                        return String.class;

                    case 4:
                        return Boolean.class;

                    default:
                        return String.class;
                }
            }
        };
        table.setModel(model);

        // Add Column
        // model.addColumn("Select");
        model.addColumn("product_code");
        model.addColumn("description");
        model.addColumn("main_category");
        model.addColumn("sub_category");
        model.addColumn("Select");

        Connection con = null;
        Statement s = null;

        try {
            //Change this
           // Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
           // con = DriverManager.getConnection("jdbc:odbc:Project");

             try{       
            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (InstantiationException e) {

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

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

            e.printStackTrace();
        }

            con = DriverManager.getConnection("jdbc:mysql://192.168.1.254/asser_old?user=&password=");
            s = con.createStatement();

            String sql = "SELECT product_code, description, main_category,sub_category FROM stock";

            ResultSet rec = s.executeQuery(sql);
            int row = 0;
            while ((rec != null) && (rec.next())) {
                model.addRow(new Object[0]);
                model.setValueAt(false, row, 4); // Checkbox
                model.setValueAt(rec.getString("product_code"), row, 0);
                model.setValueAt(rec.getString("description"), row, 1);
                model.setValueAt(rec.getString("main_category"), row, 2);
                model.setValueAt(rec.getString("sub_category"), row, 3);

                row++;
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            JOptionPane.showMessageDialog(null, e.getMessage());
            e.printStackTrace();
        }

    }

    private void UpdateData() throws SQLException {

        Connection connect = null;
        Statement s = null;
        ResultSet rs = null;

        try{        
            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (InstantiationException e) {

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

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

            e.printStackTrace();
        }

        connect = DriverManager.getConnection("jdbc:mysql://192.168.1.254/asser_old?user=&password=");

        System.out.println("Connected");
        s = connect.createStatement();
        String part = "";
        String partno = txtPartNo.getText().toString();
        String Descrip = "";
        String cat = "";
        String subcat = "";
        String category = main_list.getSelectedValue().toString();
        String sub_category = sub_list.getSelectedValue().toString();
        String query = "Select description,main_category,sub_category from stock where product_code ='" + partno + "'";
        stmt = connect.createStatement();
        rs = stmt.executeQuery(query);
        while (rs.next()) {
            Descrip = rs.getString("description");
            cat = rs.getString("main_category");
            subcat = rs.getString("sub_category");
        }
        String query2 = "UPDATE stock SET main_category='" + category + "',sub_category='" + sub_category + "' where product_code ='" + partno + "'";
        stmt.executeUpdate(query2);
        System.out.println("Updated");
        txtPartNo.setText("");
        txtPartNo.requestFocus();
        System.out.println(selectedCellValue[index]);
        for (int count = 0; count < index; count++) {
            String sql = "select * from stock where product_code = '" + selectedCellValue[count] + "' ";

            rs = s.executeQuery(sql);

            String sql2 = "UPDATE stock SET main_category='" + category + "',sub_category='" + sub_category + "' where product_code = '" + selectedCellValue[count] + "'";

            s.executeUpdate(sql2);


            }

    }

    @Override
    public void mousePressed(MouseEvent e) {
    }

    @Override
    public void mouseReleased(MouseEvent e) {
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

    @Override
    public void mouseClicked(MouseEvent arg0) {
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-04 09:07:46

一个基本的想法是将表/模型中的数据重置回false,例如。

代码语言:javascript
运行
复制
for (int row = 0; row < table.getRowCount(); row++) {
    if (table.getValueAt(row, 4) == Boolean.TRUE) {
        table.setValueAt(Boolean.FALSE, row, 4);
    }
}

更详细的信息请查看如何使用表

更新的

摆脱selectedCellValue,这只是让人困惑的事情。

只需使用上面这样的内容来构建所选项的List

代码语言:javascript
运行
复制
List<Integer> selectedRows = new ArrayList<>(25);
for (int row = 0; row < table.getRowCount(); row++) {
    if (table.getValueAt(row, 4) == Boolean.TRUE) {
        selectedRows.add(row);
    }
}

然后就像..。

代码语言:javascript
运行
复制
for (int row : selectedRows) {
    int code = table.getValueAt(row, 0);
    String sql = "select * from stock where product_code = '" + code + "' ";

    // Blah, blah, blah...

若要获取所选行所需的值,请执行以下操作。当然,你可以把这两种想法结合起来,用一个循环代替.

您的数据库资源处于危险的非管理状态,这可能会减少应用程序的执行,并导致数据库服务器在这些资源的有用寿命之外维护打开的连接。

看看试探性资源语句,关于如何更好地管理您的资源的一些想法。记住,如果你打开它,你必须关闭它。

你也迫切需要了解使用准备好的语句

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28316853

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档