HI all am trying to construct this hybrid of java and mysql. the data comes from a mysql database and I want it to display in the gui. this I have achieved thus far. However I have buttons that sort by surname, first name, ID tag etc....I need event handlers for these buttons but am quite unsure as to how to do it. any help would be much appreciated. Thanks in advance.

/* Student Contact Database GUI
* Phillip Wells 
*/
import java.awt.BorderLayout;	
// imports java class. All import class statements tell the compiler to use a class that is defined in the Java API.
// Borderlayout is a layout manager that assists GUI layout.
import javax.swing.*;			// imports java class. Swing enables the use of a GUI.
import javax.swing.JOptionPane;	// imports java class. JOptionPane displays messages in a dialog box as opposed to a console window.
import javax.swing.JPanel;		// imports java class. A component of a GUI.
import javax.swing.JFrame;		// imports java class. A component of a GUI.
import javax.swing.JButton;		// imports java class. A component of a GUI.
import javax.swing.JScrollPane;	// imports java class. A component of a GUI.
import javax.swing.JTable;		// imports java class. A component of a GUI.
import java.awt.*;			// imports java class. Similar to Swing but with different components and functions. 
import java.awt.event.*;		// imports java class. Deals with events.
import java.awt.event.ActionEvent;	// imports java class. Deals with events.
import java.awt.event.ActionListener;	// imports java class. Deals with events.
import java.sql.*;			// imports java class. Provides API for accessing and processing data stored in a data source.
import java.util.*;			// imports java class. Contains miscellaneous utility classes such as strings.






public class studentContact extends JFrame {	// public class declaration. The ‘public’ statement enables class availability to other java elements.  

    private JPanel jContentPane;    // initialises content pane
    private JButton snam, id, fname, exit;     // initialises Jbuttons
    String firstname = "firstname"; //initialises String firstname
     String secondname = "secondname"; //initialises String
   

    public studentContact() {
        Vector columnNames = new Vector(); 	// creates new vector object. Vectors are arrays that are expandable. 
        Vector data = new Vector();
        
        initialize();
        
        try {
            // Connect to the Database

            String driver = "com.mysql.jdbc.Driver"; // connect to JDBC driver
           
            String url = "jdbc:mysql://localhost/Studentprofiles"; //location of Database
            String userid = "root"; //user logon information for MySQL server
            String password = "";	//logon password for above

            Class.forName(driver); //reference to JDBC connector
            Connection connection = DriverManager.getConnection(url, userid,
                    password);	// initiates connection



            // Read data from a table

            String sql = "Select * from studentprofile order by "+ firstname; 
            //SQL query sent to database, orders results by firstname.
            Statement stmt = connection.createStatement
            (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); 
            //statement to create connection.
            //Scroll sensitive allows movement forth and back through results. 
            //Concur updatable allows updating of database.
            ResultSet rs = stmt.executeQuery(sql); // executes SQL query stated above and sets the results in a table 
            ResultSetMetaData md = rs.getMetaData();	// used to get the properties of the columns in a ResultSet object.
            int columns = md.getColumnCount(); // 

           
            for (int i = 1; i <= columns; i++) {
                columnNames.addElement(md.getColumnName(i));	// Get column names

            }

            
            while (rs.next()) {
                Vector row = new Vector(columns);		// vectors data from table

                for (int i = 1; i <= columns; i++) {	
                    row.addElement(rs.getObject(i));	// Get row data

                }

                data.addElement(row);	// adds row data
            }

            rs.close();	
            stmt.close();
        } catch (Exception e) {	// catches exceptions
            System.out.println(e);	// prints exception message
        }
        
        JTable table = new JTable(data, columnNames) {	//constructs JTable
            
            public Class getColumnClass(int column) {	
                for (int row = 0; row < getRowCount(); row++) {
                    Object o = getValueAt(row, column);

                    if (o != null) {
                        return o.getClass();
                    }
                }

                return Object.class;
            }
        };

        JScrollPane scrollPane = new JScrollPane( table );          // constructs scrollpane 'table'
        getContentPane().add(new JScrollPane(table), BorderLayout.SOUTH);   //adds table to a scrollpane
    }

    private void initialize() {
        this.setContentPane(getJContentPane());
        this.setTitle("Student Contact Database");	// sets title of table
        
        ButtonListener b1 = new ButtonListener();	// constructs button listener
        
        snam = new JButton ("Sort by surname");	 // constructs Jbutton 
        snam.addActionListener(b1);	// adds action listener 
        jContentPane.add(snam);		//adds button to pane
        
        id = new JButton ("Sort by ID");	 // constructs Jbutton 
        id.addActionListener(b1);	// adds action listener 
        jContentPane.add(id);		//adds button to pane

        fname = new JButton ("Sort by first name");	 // constructs Jbutton 
        fname.addActionListener(b1);	// adds action listener 
        jContentPane.add(fname);		//adds button to pane

        exit = new JButton ("Exit");	// constructs Jbutton
        exit.addActionListener(b1);	// adds action listener
        jContentPane.add(exit);		//adds button to pane
       
       
    }


    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();		// constructs new panel
            jContentPane.setLayout(new FlowLayout());	// sets new layout manager
           
        }
        return jContentPane;	// returns Jcontentpane
    }

    private class ButtonListener implements ActionListener {	// create inner class button listener that uses action listener
        public void actionPerformed (ActionEvent e)
        {
            if (e.getSource () == exit)	// adds listener to button exit.
            {
               System.exit(0);	// exits the GUI
            }
            if (e.getSource () == snam)
            {
             
            }
            if (e.getSource () == id)
            {
             
            }
            if (e.getSource () == fname)
            {
             
            }
        }   
    }
    

  
    
    public static void main(String[] args) {	// declaration of main method
        
        
        studentContact frame = new studentContact();	// constructs new frame
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);	//exits frame on closing
        frame.setSize(600, 300);		// set size of frame
        frame.setVisible(true);	// displays frame

        
    }

}

Recommended Answers

All 7 Replies

Get rid of ALL your comments except the header comments.
Replace them all by a proper Javadoc block per method.

Close ALL your JDBC resources as soon as you're done with them. General rule: never let them survive outside the method in which they're used.

Concentrate all database operations in their own class.

Create a special class to hold your records.

Use a custom TableModel to hold the information.

ok thanks for the advice will give it a bash, sorry about comments did not realise they would look so unsightly!

I'm fairly new to GUI coding, but what I would have done is to separate out the routine that populates the table, passing into it the sort order as a parameter. Then when the user asks the data to be resorted, you can simply call this routine with the sort order required.
A couple of things about the code as well, make sure that you ALWAYS close any database resources you use, ResultSets, Statements and ( for Oracle anyway ) Connections. To help in this I've always put the close of these resources in the finally clause of the try/catch block that allocates and uses these resources. This means that if your ResultSet fails for some reason, the Statement and Connection are closed, or if your statement is invalid and the executeQuery fails - the Connection gets closed. Unless anyone know a better way of doing this.
Nige

just had a thought, is there a way of sorting the data once it is in the table, through swing commands...? am about to check API now

brilliant, have found what I need. BY inserting 'table.setAutoCreateRowSorter(true);' the titles of the table (when doube tapped) sort appropriately. Got that straight from API - great :)

If you take a look in your JDK installation folder under "demo\jfc\TableExample", there are several table example programs, including a TableSorter.

I've also attached a zip file containing a JSortTable implementation from Java Pro magazine. I was going to link to it in the archives, but it seems Java Pro got swallowed up by another company and I can't locate the archives.

Edit: Oops, guess you found something hehe. Didn't know they had rolled that into the api in 1.6.

lol thanks for the assistance anyhow. you must have been typing that whilst my message was sent. cheers!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.