如何重新使用JTable

时间:2015-08-24 16:58:58

标签: java swing jtable defaulttablemodel

    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    import java.awt.Color.*;
    import java.util.Date;
    import java.sql.*;
    import java.util.*;
    import java.text.DateFormat;
    import java.util.Timer;
    import java.util.TimerTask;
    import java.text.SimpleDateFormat;
    import javax.swing.SwingUtilities;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.AbstractDocument;
    import javax.swing.text.DocumentFilter;
    import javax.swing.text.DocumentFilter.FilterBypass;

    class CTS extends JFrame implements ActionListener
    {
    JLabel l,l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,l11,l12,l13,l14,l15,l16,l17,l18,l19,l20,l21,l22,l23;
    JButton b1,b2,b3,b4,b5,b6,b7,b8,b9;
    JTextField t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15;
    JPanel p1=new JPanel();
    JPanel p2=new JPanel();
    JPanel pBook = new JPanel();
    JComboBox cb1,cb2,cb3;
    JTextArea j1 = new JTextArea();
    JRadioButton rb1,rb2;
    JTable table = new JTable();
    JTable table1 = new JTable();
    int i,j,srcount;
    ButtonGroup bgrp = new ButtonGroup();
    String AgentID,sdfdate,from,to,customer;
    SimpleDateFormat sdf;
    Date date;
    Connection con;
    PreparedStatement pstmt;
    private DefaultTableModel dtm = new DefaultTableModel(0,0);
    Statement stmt;
    ResultSet rs;
    Dimension screen= Toolkit.getDefaultToolkit().getScreenSize();
    int total,netpay,balance;
    String s,bal,net;

    CTS()
    {
    super("Momin Traders");

    date= Calendar.getInstance().getTime();
    sdf= new SimpleDateFormat("dd/MM/yyyy");
    sdfdate=sdf.format(date);

    date= Calendar.getInstance().getTime();
    sdf= new SimpleDateFormat("dd/MM/yyyy");
    from=sdf.format(date);

    date= Calendar.getInstance().getTime();
    sdf= new SimpleDateFormat("dd/MM/yyyy");
    to=sdf.format(date);

    p1.setLayout(null);
    p2.setLayout(null);
    p1.setBackground(new java.awt.Color(210, 210, 210));
    p1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
    p2.setBackground(new java.awt.Color(255, 226, 226));
    p2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
    p2.setBounds(10,150,1335,380);

    try
            {
                // Load the Driver
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                con=DriverManager.getConnection("jdbc:odbc:MominDB","","");
                pstmt=con.prepareStatement("select * from CTS where Date=?");
                pstmt.setString(1,sdfdate);
                rs=pstmt.executeQuery();            

                int i=0;

    while(rs.next())
    {

    String s= rs.getString("SR#");
    int j = Integer.parseInt(s);

      if(i<j)
        i=j;
        System.out.println("i="+i);


    }

    srcount=i+1;
    }


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

    l=new JLabel(new ImageIcon("images/bg.jpg"));
    l.setBounds(0,0,screen.width,screen.height);    
    l1=new JLabel("Name");
    t1=new JTextField();
    l1.setBounds(10,70,70,80);
    t1.setBounds(45,100,100,20);

    l2=new JLabel("Description");
    t2=new JTextField();
    l2.setBounds(145,70,80,80);
    t2.setBounds(210,100,100,20);

    l3=new JLabel("Customer Search");
    l3.setBounds(300,30,130,20);
    t3=new JTextField();
    t3.setBounds(410,25,190,30);

    l4=new JLabel("From Date");
    l4.setBounds(620,30,90,20);
    t4=new JTextField();
    t4.setBounds(680,30,90,20);

    l11=new JLabel("To Date");
    l11.setBounds(790,30,90,20);
    t11=new JTextField();
    t11.setBounds(840,30,90,20);

    b5=new JButton("Search");
    b5.setBounds(950,25,80,30);
    b5.addActionListener(this);


    l5=new JLabel("Quantity");
    t5=new JTextField();
    l5.setBounds(315,70,60,80);
    t5.setBounds(365,100,100,20);

    l6=new JLabel("Weight");
    t6=new JTextField();
    l6.setBounds(475,70,60,80);
    t6.setBounds(520,100,100,20);


    l8=new JLabel("Rate");
    t7=new JTextField();
    l8.setBounds(625,70,60,80);
    t7.setBounds(655,100,100,20);


    l9=new JLabel("Total");
    t8=new JTextField();
    l9.setBounds(760,70,60,80);
    t8.setBounds(790,100,100,20);


    l10=new JLabel("Balance");
    t9=new JTextField();
    l10.setBounds(890,70,60,80);
    t9.setBounds(940,100,100,20);

    l14=new JLabel("Paid");
    t14=new JTextField();
    l14.setBounds(1040,70,60,80);
    t14.setBounds(1070,100,100,20);

    l15=new JLabel("Net Pay");
    t15=new JTextField();
    l15.setBounds(1170,70,60,80);
    t15.setBounds(1220,100,100,20);

    /////////////////////////////////////////////
    l16=new JLabel("Total");
    l16.setBounds(1110,530,60,80);

    l17=new JLabel("Balance");
    l17.setBounds(1110,550,60,80);

    l18=new JLabel("Net Pay");
    l18.setBounds(1110,570,60,80);


    l22=new JLabel("Firm Name |");
    l22.setBounds(10,0,90,80);

    l23=new JLabel("Momin Traders");
    l23.setBounds(90,0,130,80);


    b1=new JButton("Save");
    b1.setBounds(1240,120,80,30);


    b2=new JButton(new ImageIcon("Lg.jpg"));
    b2.setBounds(1260,10,50,50);
    b2.addActionListener(this);

    b3=new JButton(new ImageIcon("cp.jpg"));
    b3.setBounds(1180,10,50,50);
    b3.addActionListener(this);

    b4=new JButton(new ImageIcon("add.jpg"));
    b4.setBounds(1100,10,50,50);
    b4.addActionListener(this);

    b7=new JButton("Generate Invoice");
    b7.setBounds(620,570,190,40);
    b7.addActionListener(this);

    b8=new JButton("Generate Statement");
    b8.setBounds(840,570,190,40);
    b8.addActionListener(this);

    b9=new JButton("Reset");
    b9.setBounds(840,620,100,40);
    b9.addActionListener(this);

    rb1= new JRadioButton("Daily");
    rb1.setBounds(10,540,80,30);

    rb2= new JRadioButton("Weekly / Monthly");
    rb2.setBounds(10,570,170,30);
    b1.addActionListener(this);
    rb1.addActionListener(this);
    rb2.addActionListener(this);

    l19=new JLabel();
    l19.setBounds(1160,530,60,80);

    l20=new JLabel();
    l20.setBounds(1160,550,60,80);

    l21=new JLabel();
    l21.setBounds(1160,570,60,80);


    l12=new JLabel("From");
    t12=new JTextField(20);
    l12.setBounds(200,570,70,20);
    t12.setBounds(240,570,70,20);

    l13=new JLabel("To");
    t13=new JTextField(20);
    l13.setBounds(320,570,70,20);
    t13.setBounds(340,570,70,20);

    b6=new JButton("Search");
    b6.setBounds(420,570,100,20);
    b6.addActionListener(this);


    try
            {
                // Load the Driver
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                con=DriverManager.getConnection("jdbc:odbc:MominDB","","");


            }
        catch(Exception e)
        {
                e.printStackTrace();
            }
    p1.add(l16);
    p1.add(l17);
    p1.add(l18);    
    p1.add(b7);
    p1.add(b8);
    p1.add(b5);
    p1.add(p2);
    p1.add(b1);
    p1.add(rb1);
    p1.add(rb2);
    p1.add(b2);
    p1.add(b3);
    p1.add(b4);
    add(l);
    add(p1);
    p1.add(l22);
    p1.add(l1);
    p1.add(t1);
    p1.add(l2);
    p1.add(t2);
    p1.add(l3);
    p1.add(t3);
    p1.add(l4);
    p1.add(t4);
    p1.add(l5);
    p1.add(t5);
    p1.add(l6);
    p1.add(t6);
    p1.add(t7);
    p1.add(l8);
    p1.add(t8);
    p1.add(l9);
    p1.add(l11);
    p1.add(t11);
    p1.add(l10);
    p1.add(t9);
    p1.add(rb1);
    bgrp.add(rb1);
    bgrp.add(rb2);
    p1.add(b9);
    rb1.enable(true);
    p1.add(t12);
    p1.add(l12);
    p1.add(l13);
    p1.add(t13);
    l12.setVisible(false);
    t12.setVisible(false);
    t13.setVisible(false);
    l13.setVisible(false);
    b6.setVisible(false);
    customer=t3.getText();
    p1.add(b6);
    p1.add(l23);
    p1.add(l14);
    p1.add(l15);
    p1.add(t14);
    p1.add(t15);
    p1.add(l19);
    p1.add(l20);
    p1.add(l21);

    DocumentFilter df=new DocumentFilter()
    {
     public void insertString(FilterBypass fb, int i, String string, AttributeSet as) throws BadLocationException
    { 
     if(isDigit(string))
      { 
        super.insertString(fb,i,string,as);
        calc();
     }
    }

     public void remove(FilterBypass fb, int i, int i1) throws BadLocationException
    {
     super.remove(fb,i,i1);
     calc();
    }

     public void replace(FilterBypass fb, int i, int i1, String string, AttributeSet as) throws BadLocationException
    {
     if(isDigit(string))
      {
       super.replace(fb,i,i1,string,as);
       calc();
      }
    }

     private boolean isDigit(String string)
    { 
     for(int n=0; n < string.length(); n++)
     {
      char c = string.charAt(n); //get a single character string
       //System.out.println(c);
       if(!Character.isDigit(c))
       {
        //if it is an alpabetical charcater or white space
        return true;
       }
      }
       return true;
    }

    void calc()
    {
     double total;
     double netpay;
     double quantity=0.0;
     double weight=0.0;
     double rate=0.0;
     double bal=0.0;
     double paid=0.0;
      if(!t5.getText().isEmpty())
     {
      quantity=Double.parseDouble(t5.getText()); //we must add this
     }
      if(!t6.getText().isEmpty())
      {
      weight=Double.parseDouble(t6.getText()); //we must add this
      }
      if(!t7.getText().isEmpty())
      {
       rate=Double.parseDouble(t7.getText());
      }
       total=weight*rate;
      t8.setText(String.valueOf(total));

      if(!t9.getText().isEmpty())
      {
       bal=Double.parseDouble(t9.getText());
      }
      if(!t14.getText().isEmpty())
     {
      paid=Integer.parseInt(t14.getText()); //we must add this
     }
      netpay=total+bal-paid;
      t15.setText(String.valueOf(netpay));
    }

    };


    ((AbstractDocument)(t7.getDocument())).setDocumentFilter(df);
    ((AbstractDocument)(t5.getDocument())).setDocumentFilter(df);
    ((AbstractDocument)(t6.getDocument())).setDocumentFilter(df);
    ((AbstractDocument)(t14.getDocument())).setDocumentFilter(df);
    ((AbstractDocument)(t9.getDocument())).setDocumentFilter(df);


    pBook.setLayout (null);
    setSize(screen);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    DefaultTableModel dtm = new DefaultTableModel(new Object[]{"SR#", "Date", "Name", "Description", "Quantity", "Weight", "Rate", "Total", "Balance","Paid","Net Pay"},0);

    }

    public void actionPerformed(ActionEvent ae)
    {

    DefaultTableModel dtm = new DefaultTableModel(new Object[]{"SR#", "Date", "Name", "Description", "Quantity", "Weight", "Rate", "Total", "Balance","Paid","Net Pay"},0);                     
        table= new JTable(dtm);
        table.setModel(dtm); 
        JScrollPane scroller = new JScrollPane(table);
        table.setBackground(new java.awt.Color(255,226,226));
        scroller.setBounds(0,0,1335,380);
        p2.add(scroller);
        dtm.setRowCount(0);
        /*dtm.addRow(new Object[]{rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8),rs.getString(9),rs.getString(10),rs.getString(11)});*/

    if(ae.getSource()==b9)
    {
    dtm.setRowCount(0);
    }


    if(ae.getSource()==b1)
    {
    try{
    if(t1.getText().equals("")||t2.getText().equals("")||t6.getText().equals("")||t7.getText().equals("")||t8.getText().equals("")||t9.getText().equals(""))
                JOptionPane.showMessageDialog(CTS.this,"Please enter the data in all the fields...","Error Message..",JOptionPane.OK_OPTION);
            else {
                    // Establish the connection
                   Connection con =DriverManager.getConnection("jdbc:odbc:MominDB","","");
                    System.out.println("Connection Established of create");

                    PreparedStatement pstmt=con.prepareStatement("insert into CTS values(?,?,?,?,?,?,?,?,?,?,?)");
                    pstmt.setString(1,String.valueOf(srcount));
                    pstmt.setString(2,sdfdate);
                    pstmt.setString(3,t1.getText());
                    pstmt.setString(4,t2.getText());
                    pstmt.setString(5,t5.getText());
                    pstmt.setString(6,t6.getText());
                    pstmt.setString(7,t7.getText());
                    pstmt.setString(8,t8.getText());
                    pstmt.setString(9,t9.getText());
                    pstmt.setString(10,t14.getText());
                    pstmt.setString(11,t15.getText());


                                 pstmt.executeUpdate();
                                  srcount++;

    ///////////////////////////////////////////////////////////////////////////
        try{

                    stmt = con.createStatement();
                    rs=stmt.executeQuery("select * from CTS where Date='"+sdfdate+"' ");
                                while(rs.next())
                                {
                            dtm.addRow(new Object[]{rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8),rs.getString(9),rs.getString(10),rs.getString(11)});
                                System.out.println("Working rb1");
                                }
                                t1.setText("");t2.setText("");t3.setText("");t5.setText("");t6.setText("");t7.setText("");t8.setText("");
                                t9.setText("");t14.setText("");t15.setText("");
                                }
                                    catch(Exception e) {
                                e.printStackTrace();
                                    }

                            }         
                            }   
            catch(Exception e) {
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(CTS.this,"Record is not created, \n  please try again or check your Database connection ","Error Message...",JOptionPane.OK_OPTION);
                }
    }






    /*====================================================================*/
    if(ae.getSource()==b2)
    {
    JOptionPane.showMessageDialog(CTS.this,"System is shutting down.....\nHave a nice day","System Shuting down",JOptionPane.OK_OPTION);
    System.exit(0);
    }
    if(ae.getSource()==b3)
    {
    new cpass().setVisible(true);
    setDefaultCloseOperation(MainMenu.EXIT_ON_CLOSE);

    }
        if(ae.getSource()==b5)

        if(t3.getText().equals("")||t4.getText().equals("")||t11.getText().equals(""))
        JOptionPane.showMessageDialog(CTS.this,"Please enter the data in all the fields...","Error Message..",JOptionPane.OK_OPTION);
        else{

        try{
            dtm.setRowCount(0);
            stmt = con.createStatement();
        rs=stmt.executeQuery("select * from CTS where name='"+t3.getText()+"' and Date BETWEEN '"+t4.getText()+"' and '"+t11.getText()+"'");        
        while(rs.next())
        {


        dtm.addRow(new Object[]{rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8),rs.getString(9),rs.getString(10),rs.getString(11)});



                                }
                                }
                                    catch(Exception e) {
                                e.printStackTrace();
                                    }
        try{
        rs=stmt.executeQuery("select total from CTS where name='"+t3.getText()+"' and Date BETWEEN '"+t4.getText()+"' and '"+t11.getText()+"'");
        while(rs.next())
        {
        total+=rs.getInt(1);
        }

        System.out.println(total);

        s= String.valueOf(total);

        l19.setText(s);
        total=0;

        rs=stmt.executeQuery("select balance from CTS where name='"+t3.getText()+"' and Date BETWEEN '"+t4.getText()+"' and '"+t11.getText()+"'");
        while(rs.next())
        {
        balance+=rs.getInt(1);

        }
        System.out.println(balance);

        bal= String.valueOf(balance);

        l20.setText(bal);
        balance=0;

        rs=stmt.executeQuery("select netpay from CTS where name='"+t3.getText()+"' and Date BETWEEN '"+t4.getText()+"' and '"+t11.getText()+"'");
        while(rs.next())
        {
        netpay+=rs.getInt(1);
        }
        System.out.println(netpay);

        net= String.valueOf(netpay);

        l21.setText(net);
        netpay=0;


        }

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


    }
    if(ae.getSource()==rb1)
    {
    dtm.setRowCount(0);
    try{    
        stmt = con.createStatement();
        rs=stmt.executeQuery("select * from CTS"); 


                    while(rs.next())
                    {

            dtm.addRow(new Object[]{rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.            getString(8),rs.getString(9),rs.getString(10),rs.getString(11)});
            System.out.println("Working rb1");

                    }

                    stmt = con.createStatement();
        rs=stmt.executeQuery("select sum(total) from CTS where Date='"+sdfdate+"' ");

        while(rs.next())
        {
        System.out.println("in side total");

        }
                    }
                        catch(Exception e) {
                    e.printStackTrace();
                        }
                                try{
                rs=stmt.executeQuery("select total from CTS where Date='"+sdfdate+"' ");
                while(rs.next())
                {
                total+=rs.getInt(1);

                }

                System.out.println(total);

                s= String.valueOf(total);

                l19.setText(s);
                total=0;

                rs=stmt.executeQuery("select balance from CTS where Date='"+sdfdate+"' ");
                while(rs.next())
                {
                balance+=rs.getInt(1);

                }
                System.out.println(balance);

                bal= String.valueOf(balance);

                l20.setText(bal);
                balance=0;

                rs=stmt.executeQuery("select netpay from CTS where Date='"+sdfdate+"' ");
                while(rs.next())
                {
                netpay+=rs.getInt(1);
                }
                System.out.println(netpay);

                net= String.valueOf(netpay);

                l21.setText(net);
                netpay=0;

                }

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


    }

    if(ae.getSource()==b7)
    {
    new invoice();
    }
    if(ae.getSource()==b8)
    {
    new St();
    }

    if(ae.getSource()==rb2)
    {
    t12.setVisible(true);
    l12.setVisible(true);
    t13.setVisible(true);
    l13.setVisible(true);
    b6.setVisible(true);
    setDefaultCloseOperation(MainMenu.EXIT_ON_CLOSE);

    }

    if(ae.getSource()!=rb2 && ae.getSource()!=b6)
    {
    t12.setVisible(false);
    l12.setVisible(false);
    t13.setVisible(false);
    l13.setVisible(false);
    b6.setVisible(false);
    rb1.enable(true);
    }

    if(ae.getSource()==b6)
    {
    try{
                stmt = con.createStatement();
                rs=stmt.executeQuery("select * from CTS where Date BETWEEN '"+t12.getText()+"' and '"+t13.getText()+"'");

                            while(rs.next())
                            {
                            dtm.addRow(new Object[]{rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8),rs.getString(9),rs.getString(10),rs.getString(11)});

                                    System.out.println("Working rb2");

                            }

            }


    catch(Exception e)
    {
    e.printStackTrace();
    }
    try{
                rs=stmt.executeQuery("select total from CTS where  Date BETWEEN '"+t12.getText()+"' and '"+t13.getText()+"'");
                while(rs.next())
                {
                total+=rs.getInt(1);

                }

                System.out.println(total);

                s= String.valueOf(total);

                l19.setText(s);
                total=0;

                rs=stmt.executeQuery("select balance from CTS where  Date BETWEEN '"+t12.getText()+"' and '"+t13.getText()+"'");
                while(rs.next())
                {
                balance+=rs.getInt(1);

                }
                System.out.println(balance);

                bal= String.valueOf(balance);

                l20.setText(bal);
                balance=0;

                rs=stmt.executeQuery("select netpay from CTS where  Date BETWEEN '"+t12.getText()+"' and '"+t13.getText()+"'");
                while(rs.next())
                {
                netpay+=rs.getInt(1);
                }
                System.out.println(netpay);

                net= String.valueOf(netpay);

                l21.setText(net);
                netpay=0;

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

    }

    if(ae.getSource()==b4)
    {
    new Add().setVisible(true);
    setDefaultCloseOperation(MainMenu.EXIT_ON_CLOSE);

    }

    if(ae.getSource()==p1)
    {
    new MainMenu().setVisible(false);
    }

    }
    public static void main(String args[])
    {
    new CTS();

    }
    }

在运行要在您的计算机上实现的代码之前,您需要执行以下操作:

  1. 使用名称MominDB.mdb(它是一个微软访问文件)设置系统DSN。
  2. 填写名为CTS的表(表名为CTS),从中获取所有数据。
  3. 填满桌子,直到你滚动下来。 (这是主要问题)Scroller正在重叠。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

  1. 使您的模型(dtm)成为会员字段。
  2. 移除动作监听器中的setModelscroller.add个来电。
  3. while循环之前 - 将数据模型重置为空。您可以致电setRowCount(0)getDataVector().clear()
  4. 然后看它是否有效。请发布格式化代码,以便我们能够很好地阅读。