2015-02-04 4 views
0

필자는 2 개의 jlists (메인 카테고리와 서브 카테고리)와 jtable이있는 mysql 데이터베이스에서 값을 검색하는 jtable이있는 내부에 자바 프로그램을 만들었습니다. 사용자가 두 개의 행을 선택하고 jlable에서 값을 선택합니다. jtable의 2 열 (주 카테고리 및 하위 카테고리)을 자동으로 업데이트하는 것보다 마주 보는 문제는 처음으로 두 행을 선택하고 업데이트하는 것입니다. 그것은 잘 작동하지만 다음 몇 가지 다른 행을 선택하고 그것을 업데이 트보다 이전에 선택한 행을 u는 그냥 그래서 어떻게 내가이 문제를 해결할 수 있습니다 선택한? 도와주세요jlist에서 선택하고 체크 박스를 사용하여 업데이트 jtable

내 코드 :

//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) { 
    } 
} 
+0

생각 해 봤나 배울 필요가? – MadProgrammer

+0

나는 똑같은 생각을했지만, 어떻게하는지 모른다. – user3645728

+0

for 루프를 사용하면 (자),'JTable.getRowCount()'를 사용해 JTable의 모든 행을 반복 처리합니다. 각 행에 대해'JTable # setVaueAt'를 사용하여 행과 열 4의 값을 'Boolean.FALSE'로 설정합니다. – MadProgrammer

답변

1

기본 아이디어는

for (int row = 0; row < table.getRowCount(); row++) { 
    if (table.getValueAt(row, 4) == Boolean.TRUE) { 
     table.setValueAt(Boolean.FALSE, row, 4); 
    } 
} 

가 좀 더 자세히 살펴 보자 .. 예를 들어, false 다시 테이블/모델의 데이터를 재설정하는 것 How to Use Tables 자세한 내용은

selectedCellValue을 없애면 혼란스러운 문제 일뿐입니다.

단순히

for (int row : selectedRows) { 
    int code = table.getValueAt(row, 0); 
    String sql = "select * from stock where product_code = '" + code + "' "; 

    // Blah, blah, blah... 

당신이 선택한 행에 필요한 값을 얻으려면 ... 선택한 항목

List<Integer> selectedRows = new ArrayList<>(25); 
for (int row = 0; row < table.getRowCount(); row++) { 
    if (table.getValueAt(row, 4) == Boolean.TRUE) { 
     selectedRows.add(row); 
    } 
} 

그리고 뭔가 등의 List을 구축하기 위해 위 같은 것을 사용합니다. 물론 두 가지 아이디어를 결합하여 단일 루프를 사용할 수도 있습니다 ...

데이터베이스 리소스를 위험한 상태로 관리하지 않으면 응용 프로그램의 성능이 저하되고 데이터베이스 서버가 자원의 유용한 수명.

The try-with-resources Statement 리소스를 더 잘 관리하는 방법에 대해 알아보십시오. 당신이 그것을 열면 그것을 닫아야한다는 것을 기억하십시오.

또한, 필사적으로 업데이트 한 후 선택을 재설정에 대한 Using Prepared Statements

+0

다른 방법으로는 할 수 없습니다 – user3645728

+0

'selectedCellValue'가 너와 장난하고있다. 정말 필요하지는 않다. 개인적으로 제거 할 수있다. (열 4는 선택 정보를 유지하고 있다고 가정한다.) – MadProgrammer

+0

고마워요. @MadProgrammer – user3645728

관련 문제