1

我在做表格。我希望从数据库中获取数据。我想要 3 个按钮打开、编辑、删除以及每个获取的记录。我已经完成了记录的获取。我在将按钮添加到 JTable 时遇到问题。从字符串到“日期”的日期覆盖也有问题。我使用了数据库 MySql 5.1。

import java.awt.event.*;

import javax.management.openmbean.OpenDataException;
import javax.swing.*;
//import java.awt.*;
import javax.swing.table.DefaultTableModel;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.regex.*;

class frameRegistry extends JFrame implements ActionListener

{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

// ----------------------------------PANELS--------------------------------------

    JPanel  panelImage, panelDate, panelAddForm, panelSearch,
            panelDisplay;

    // -----------------------GUI ELEMENTS------------------------------------------
    // -----------------------------------------------------------------------------
    JButton addRecord, searchHistory, save, cancel;

    JLabel  labelName, labelFirstName, labelMiddleName, labelLastName,
            labelBirthDate, labelAge, labelCity, labelContact, labelImage,
            labelDate, labelValidity, labelAmount, labelNote,labelTime;

    JLabel  demo;

    JTextField  textFieldFirstName, textFieldMiddleName, textFieldLastName,
            textFieldAge, textFieldCity, textFieldContact, textFieldValidity,
            textFieldAmount, textFieldNote;

    JTextField  textFieldNameSearch;

    JTable table;
    JScrollPane scrollPane;

    Calendar currentDate, validitydate;
    SimpleDateFormat sdf;
    Date validity;

    int age, amount;
    Double contact;
    int flag = 0;

    String Year, Month, Day, stringValidityDate;
    String firstName, middleName, lastName, city;
    String stringnamesearch;
    String time;

    // ---------------------DATABASEVARIABLES-----------------------------------------
    // -------------------------------------------------------------------------------

    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;

    String url = "jdbc:mysql://localhost:3306/records";
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root";
    String password = "";

    // ------------------COMPONANT ARRAYS------------------------------------------
    // ----------------------------------------------------------------------------

    JButton open[];
    JButton edit[];
    JButton delete[];

// -----------------------FRAME STARTS---------------------------------------------
//---------------------------------------------------------------------------------

    frameRegistry(  ) 
    {


//-----------------------------------------------------------------------------     

        setSize( 600, 800 );
        setDefaultLookAndFeelDecorated( true );
        setVisible( true );

        setLayout( null );

        labelImage = new JLabel( new ImageIcon( "C:\\Users\\SUN\\Desktop  
                                                        \\logo.png" ) );
        panelImage = new JPanel(  );

        panelImage.add( labelImage );
        panelImage.setBounds( 0, 0, 700, 90 );
        add( panelImage );

        currentDate = Calendar.getInstance(  );

        Year = "" + currentDate.get( Calendar.YEAR );
        Month = "" + currentDate.get( Calendar.MONTH );
        Day = "" + currentDate.get( Calendar.DAY_OF_MONTH );

        time = "" + currentDate.get( Calendar.HOUR_OF_DAY ) + ":"
                + currentDate.get( Calendar.MINUTE );

        labelDate = new JLabel( "Date:" + Day + "/" + Month + "/" + Year + " "
                    + time );

        panelDate = new JPanel(  );
        panelDate.add( labelDate );
        panelDate.setBounds( 350, 100, 130, 20 );
        add( panelDate );

        panelSearch = new JPanel(  );
        panelSearch.setLayout( null );

        addRecord = new JButton( "Add Record" );
        addRecord.setBounds( 5, 10, 100, 30 );
        addRecord.addActionListener( this );
        panelSearch.add( addRecord );

// ------------------------NAME SEARCH IN DATABASE-----------------------

        textFieldNameSearch = new JTextField(  );
        textFieldNameSearch.setBounds( 150, 10, 100, 30 );

        textFieldNameSearch.addKeyListener( new KeyAdapter(  ) {
            public void keyTyped( KeyEvent e ) {
                String input = textFieldNameSearch.getText(  );
                Pattern p = Pattern.compile( "[ 0-9,^$,&%$#@!()*^]" );
                Matcher m = p.matcher( input );
                if ( m.find(  ) ) {
            JOptionPane.showMessageDialog( null, "Please enter valid Name",
                        "Sorry", JOptionPane.ERROR_MESSAGE );
                }

            }
        } );
        panelSearch.add( textFieldNameSearch );

        searchHistory = new JButton( "Search" );
        searchHistory.setBounds( 270, 10, 100, 30 );
        searchHistory.addActionListener( this );
        panelSearch.add( searchHistory );
        panelSearch.setBounds( 0, 130, 450, 50 );
        add( panelSearch );

        panelAddForm = new JPanel(  );
        panelAddForm.setLayout( null );

        panelDisplay = new JPanel(  );
        panelDisplay.setLayout( null );

         //------------------------NAME------------------------------------------------
        labelName = new JLabel( "Name" );
        labelName = new JLabel( "Name" );
        labelName.setBounds( 20, 10, 50, 20);
        panelAddForm.add(labelName);

         //-------------------------FNAME------------------------------------------------

        labelFirstName = new JLabel("First Name");
        labelFirstName.setBounds(100, 30, 80, 10);
        panelAddForm.add(labelFirstName);

        textFieldFirstName = new JTextField(  );
        textFieldFirstName.setBounds( 100, 10, 80, 20 );

        textFieldFirstName.addKeyListener( new KeyAdapter(  ) {
            public void keyTyped( KeyEvent e ) {
                String input = textFieldFirstName.getText(  );
                    Pattern p = Pattern.compile( "[ 0-9,&%$#@!()*^,\t\n\f\r]");
                Matcher m = p.matcher( input );
                if ( m.find(  ) ) {
            JOptionPane.showMessageDialog( null, "Please Enter Valid Name",
                        "Sorry", JOptionPane.ERROR_MESSAGE );
                }

            }
        } );

        panelAddForm.add( textFieldFirstName );

        //----------------------------------------MNAME----------------------------------

        labelMiddleName= new JLabel("Middle Name");
        labelMiddleName.setBounds( 190, 30, 80,  10);
        panelAddForm.add(labelMiddleName);


        textFieldMiddleName = new JTextField(  );
        textFieldMiddleName.setBounds( 190, 10, 80, 20 );

        textFieldMiddleName.addKeyListener( new KeyAdapter(  ) {
            public void keyTyped( KeyEvent e ) {
                String input = textFieldMiddleName.getText(  );
                Pattern p = Pattern.compile( "[ 0-9,&%$#@!()*^]" );
                Matcher m = p.matcher( input );
                if ( m.find(  ) ) {
                JOptionPane.showMessageDialog( null, "Please Enter Valid 
                                               Name","Sorry", JOptionPane.ERROR_MESSAGE );
                }

            }
        } );

        panelAddForm.add( textFieldMiddleName );

        //-----------------------------------labelName----------------------------------------

        labelLastName = new JLabel("Last Name");
        labelLastName.setBounds(280, 30, 80, 10);
        panelAddForm.add(labelLastName);

        textFieldLastName = new JTextField(  );
        textFieldLastName.setBounds( 280, 10, 80, 20 );

        textFieldLastName.addKeyListener( new KeyAdapter(  ) {
            public void keyTyped( KeyEvent e ) {
                String input = textFieldLastName.getText(  );
                Pattern p = Pattern.compile( "[ 0-9,&%$#@!()*^]" );
                Matcher m = p.matcher( input );
                if ( m.find(  ) ) {
            JOptionPane.showMessageDialog( null, "Please Enter Valid Name",
                        "Sorry", JOptionPane.ERROR_MESSAGE );
                }
            }
        } );

        panelAddForm.add( textFieldLastName );

        //-------------------------------------BDATE--------------------------------------
        labelBirthDate = new JLabel( "Birth Date" );
        labelBirthDate.setBounds( 20, 60, 60, 20 );
        panelAddForm.add( labelBirthDate );

        //--------------------------------------------AGE---------------------------------------
        labelAge = new JLabel( "Age" );
        labelAge.setBounds( 20, 110, 50, 20 );
        panelAddForm.add( labelAge );

        textFieldAge = new JTextField(  );
        textFieldAge.setBounds( 100, 110, 80, 20 );

        textFieldAge.addKeyListener( new KeyAdapter(  ) {
            public void keyTyped( KeyEvent e ) {
                String input = textFieldAge.getText(  );
                Pattern p = Pattern.compile( "[ A-Z,a-z,&%$#@!()*^]" );
                Matcher m = p.matcher( input );
                if ( m.find(  ) ) {
                JOptionPane.showMessageDialog( null, "Numbers only",
                        "Sorry", JOptionPane.ERROR_MESSAGE );
                }

            }
        } );

        panelAddForm.add( textFieldAge );

         //-------------------------------------CITY----------------------------------------------
        labelCity = new JLabel( "City" );
        labelCity.setBounds( 20, 160, 80, 20 );
        panelAddForm.add( labelCity );

        textFieldCity = new JTextField(  );

        textFieldCity.addKeyListener( new KeyAdapter(  ) {
            public void keyTyped( KeyEvent e ) {
                String input = textFieldCity.getText(  );
                Pattern p = Pattern.compile( "[ 0-9,&%$#@!()*^]" );
                Matcher m = p.matcher( input );
                if ( m.find(  ) ) {
                JOptionPane.showMessageDialog( null, "Characters only",
                        "Sorry", JOptionPane.ERROR_MESSAGE );
                }

            }
        } );

        textFieldCity.setBounds( 100, 160, 80, 20 );
        panelAddForm.add( textFieldCity );

        //------------------------------------------CONTACT-----------------------------
        labelContact = new JLabel( "Contact" );
        labelContact.setBounds( 20, 210, 60, 20 );
        panelAddForm.add( labelContact );

        textFieldContact = new JTextField( 12 );
        textFieldContact.setBounds( 100, 210, 80, 20 );
        textFieldContact.addKeyListener( new KeyAdapter(  ) {
            public void keyTyped( KeyEvent e ) {
                String input = textFieldContact.getText(  );
                Pattern p = Pattern.compile( "^[ 1-9][ 0-9]{12}$" );
                Matcher m = p.matcher( input );
                if ( m.find(  ) ) {
                JOptionPane.showMessageDialog( null, "Numbers only",
                        "Sorry", JOptionPane.ERROR_MESSAGE );
                }
            }
        } );

        panelAddForm.add( textFieldContact );

        // ----------------------------------------VALIDITY-----------------------
        labelValidity = new JLabel( "Valiidity" );
        labelValidity.setBounds( 20, 260, 60, 20 );
        panelAddForm.add( labelValidity );

        textFieldValidity = new JTextField(  );
        textFieldValidity.setBounds( 100, 260, 80, 20 );
        panelAddForm.add( textFieldValidity );

        //------------------------------------------NOTE------------------------------------
        labelNote = new JLabel( "Note" );
        labelNote.setBounds( 20, 310, 60, 20 );
        panelAddForm.add( labelNote );

        textFieldNote = new JTextField(  );
        textFieldNote.setBounds( 100, 310, 80, 20 );

        textFieldNote.addKeyListener( new KeyAdapter(  ) {
            public void keyTyped( KeyEvent e ) {
                String input = textFieldNote.getText(  );
                Pattern p = Pattern.compile( "[ 0-9,&%$#@!(    )*^]" );
                Matcher m = p.matcher( input );
                if ( m.find(  ) ) {
                JOptionPane.showMessageDialog( null, "Characters only",
                        "Sorry", JOptionPane.ERROR_MESSAGE );
                }
            }
        } );

        panelAddForm.add( textFieldNote );

        //----------------------------------------FEES-------------------------------------------
        labelAmount = new JLabel( "Fees" );
        labelAmount.setBounds( 20, 360, 60, 20 );
        panelAddForm.add( labelAmount );

        textFieldAmount = new JTextField(  );
        textFieldAmount.setBounds( 100, 360, 80, 20 );

        textFieldAmount.addKeyListener( new KeyAdapter(  ) {
            public void keyTyped( KeyEvent e ) {
                String input = textFieldAmount.getText(  );
                Pattern p = Pattern.compile( "[ A-Z,a-z,&%$#@!(    )*^]" );
                Matcher m = p.matcher( input );
                if ( m.find(  ) ) {
                JOptionPane.showMessageDialog( null, "Numbers only",
                             "Sorry", JOptionPane.ERROR_MESSAGE );
                }

            }
        } );

        panelAddForm.add( textFieldAmount );

        //----------------------------------------------------------------------------------
        save = new JButton( "SAVE" );
        save.setBounds( 25, 410, 70, 20 );
        save.addActionListener( this );
        panelAddForm.add( save );

        cancel = new JButton( "CANCEL" );
        cancel.setBounds( 150, 410, 80, 20 );
        cancel.addActionListener( this );
        panelAddForm.add( cancel );

        panelAddForm.setBounds( 0, 220, 600, 700 );
        panelAddForm.setVisible( false );

    // ---------------------------ADD FORM COMPLETE-----------


        panelDisplay.setBounds( 0, 200, 800, 600 );


    }

    // -------------------BUTTON EVENTS START-------------------------

    public void actionPerformed( ActionEvent ae )
    {

        int actionCount=0;

        if ( ae.getSource(  ) == addRecord ) 
        {
            remove(panelDisplay);
            add( panelAddForm );

            panelAddForm.setEnabled( true );
            panelAddForm.setVisible( true );

            validitydate = Calendar.getInstance(  );
            validitydate.add( Calendar.DAY_OF_MONTH, 90 );
            stringValidityDate = "" + validitydate.get( Calendar.DAY_OF_MONTH )
                    + "/" + validitydate.get( Calendar.MONTH ) + "/"
                    + validitydate.get( Calendar.YEAR );

            textFieldValidity.setText( stringValidityDate );
            textFieldValidity.setEnabled( false );

        }

        if ( ae.getSource(  ) == save ) {

            firstName = textFieldFirstName.getText(  );
            middleName = textFieldMiddleName.getText(  );
            lastName = textFieldLastName.getText(  );
            age = Integer.parseInt( textFieldAge.getText(  ) );
            city = textFieldCity.getText(  );

            int flag = 0;

            String cnt = "" + textFieldContact.getText(  );
            if ( cnt.length(  ) < 6 ) {
                flag = 1;
            }

            contact = Double.parseDouble( textFieldContact.getText(  ) );


            if ( flag == 1 ) {
                JOptionPane.showMessageDialog( null, 
                                                 "Enter valid phone number",
                        "Sorry", JOptionPane.ERROR_MESSAGE );
            } else {

                try {

                    Class.forName( driver ).newInstance(  );
                    connection = DriverManager.getConnection( url,
                                                                  userName, password );

                    statement = connection.createStatement(
                        ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_UPDATABLE );

                    System.out.println( "Connected to database" );

                    resultSet = statement.executeQuery( "select * 
                                                                            from record" );

                    resultSet.moveToInsertRow(  );
                    resultSet.updateString( 1, firstName );
                    resultSet.updateString( 2, middleName );
                    resultSet.updateString( 3, lastName );
                    resultSet.updateInt( 5, age );
                    resultSet.updateDouble( 6, contact );
                    resultSet.updateString( 7, city );
                resultSet.updateDate( 8, ( java.sql.Date ) validity );
                    resultSet.updateInt( 9, amount );

                    resultSet.insertRow(  );
                    JOptionPane.showMessageDialog(  null, 
                                                    "Record Added","Success", 
                                                    JOptionPane.INFORMATION_MESSAGE );

                                        panelAddForm.setEnabled(false);
                    panelAddForm.setVisible( false );
                    connection.close(  );

                }
                                 catch ( Exception e ) {
                    e.printStackTrace(  );
                    JOptionPane.showMessageDialog(  null, 
                                                                  "Insertion failed",
                        "Sorry", JOptionPane.ERROR_MESSAGE );
                }
            }
        }

        if ( ae.getSource(  ) == cancel ) {
            textFieldFirstName.setText( "" );
            textFieldMiddleName.setText( "" );
            textFieldLastName.setText( "" );
            textFieldAge.setText( "" );
            textFieldCity.setText( "" );
            textFieldContact.setText( "" );
            textFieldValidity.setText( "" );
            textFieldAmount.setText( "" );
            panelAddForm.setEnabled( false );
            panelAddForm.setVisible( false );
        }

        if ( ae.getSource(  ) == searchHistory )
        {

            panelAddForm.setEnabled( false );
            panelAddForm.setVisible( false );

            remove( panelAddForm );
            add( panelDisplay );

            stringnamesearch = "" + textFieldNameSearch.getText(  );
            DefaultTableModel tableModel = new DefaultTableModel(  );


            if(stringnamesearch=="")
            {
                JOptionPane.showMessageDialog(  null, "Search is blank",
                        "Sorry", JOptionPane.ERROR_MESSAGE );
            }

        else
        {
            try 
            {

                            Class.forName( driver ).newInstance(  );
                           connection = DriverManager.getConnection( url, 
                                                                  userName,password );

                    statement = connection.createStatement( 
                            ResultSet.TYPE_SCROLL_SENSITIVE,
                            ResultSet.CONCUR_UPDATABLE );

                resultSet = statement.executeQuery( "select * from record 
                                             where firstname = '"+ stringnamesearch+
                                             "'or lastname = '" + stringnamesearch + "'" );

                                       System.out.println( "Query executed" );

                    String firstName;
                    String lastName;

                    int counter = 0;

                    JButton add=new JButton("ADD");
                    while ( resultSet.next(  ) )
                    {


                    firstName = resultSet.getString( 1 );
                    lastName = resultSet.getString( 3 );


                    String[ ] columnNames = { "First Name",
                                                                 "Last Name","click" };

                    Object[ ] data = { "" + firstName, "" +
                                                             lastName, add };

                    tableModel.setColumnIdentifiers( columnNames );
                    tableModel.addRow( data );
                    tableModel.fireTableDataChanged();

                    counter++;
                    }

                    table = new JTable( tableModel );
                    table.setEnabled(false);
                    scrollPane = new JScrollPane( table );
                    scrollPane.setBounds( 10, 10, 350, 100 );
                    scrollPane.revalidate();


                    panelDisplay.add( scrollPane );
                    connection.close(  );   
                    System.out.println( "" + counter );

//------------- creating array of Buttons---------------------------------  

                    open=new JButton[counter];
                    edit=new JButton[counter];
                    delete=new JButton[counter];


                    for( int i=0,y=30; i<counter;i++,y+=15 )
                    {

                        open[i]=new JButton( "Open" );
                        System.out.println("1st: "+i);
                        open[i].setBounds( 380, y, 70, 15 );
                        System.out.println("2nd: "+i);
                        open[i].addActionListener( this );
                        panelDisplay.add (open[i] );
                        System.out.println("3rd: "+i);


                        edit[i]=new JButton( "Edit" );
                        edit[i].setBounds( 460, y, 70, 15 );
                        edit[i].addActionListener( this );
                        panelDisplay.add( edit[i] );

                        delete[i]=new JButton( "Delete" );
                        delete[i].setBounds( 540, y, 70, 15 );  
                        delete[i].addActionListener( this );
                        panelDisplay.add( delete[i] );

                        System.out.println(""+i);
                    }

                    actionCount=open.length;
                    panelDisplay.setEnabled(false);
                    panelDisplay.setVisible(true);

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

            }       

    }

    for( int j=0;j<open.length;j++ )
    {
        if( ae.getSource() == open[j] )
        {
            System.out.println("open of"+j+"is clicked");
            fetchData(j);
        }

    }


//-----------------BUTTON EVENT ENDS----------------------------------------

}


    public void fetchData(int i )
    {
        panelDisplay.setEnabled(false);
        panelAddForm.setEnabled(false);
        panelDisplay.setVisible(false);
        panelAddForm.setVisible(false);
        remove(panelDisplay);
        remove(panelAddForm);

        JPanel showRecord=new JPanel();

        showRecord.setLayout(null);
        showRecord.setBounds(5, 300, 600, 700);

        int id=i;
        int uniqid=0;

        String firstName="", lastName="";
        try
        {
               Class.forName( driver ).newInstance(  );
               connection = DriverManager.getConnection( url, userName, password );
               statement = connection.createStatement(
                                    ResultSet.TYPE_SCROLL_SENSITIVE,
                                    ResultSet.CONCUR_UPDATABLE );

            resultSet = statement.executeQuery( "select * from record 
                                                             where  uniqid="+id );

            System.out.println( "Query executed" );
            while(resultSet.next())
            {
                firstName = resultSet.getString(1);
                lastName = resultSet.getString(3);
                uniqid = resultSet.getInt(11);
            }

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        System.out.println("name was:"+firstName+" id is"+uniqid);

        JLabel labelfirstName=new JLabel(firstName);
        labelfirstName.setBounds(30,30,60,30);
        showRecord.add(labelfirstName);

        JLabel labellastName=new JLabel(lastName);
        labellastName.setBounds(80,30,60,30);
        showRecord.add(labellastName);

        add(showRecord);
    }

}


class Registry {
    public static void main( String args[ ] ) {

           frameRegistry reg = new frameRegistry(  );


    }

}
4

1 回答 1

1

不要使用空布局和 setBounds。Swing 旨在与布局管理器一起使用。阅读有关布局管理器的 Swing 教程。

不要在文本字段上使用 KeyListeners。如果用户将文本粘贴到文本字段中会发生什么?相反,您应该使用 DocumentListener。阅读有关如何编写文档侦听器的教程。

我在将按钮添加到 JTable 时遇到问题

表格按钮列显示了执行此操作的一种方法。

于 2013-04-19T14:50:28.023 回答