EXAMPLES FOR DAY8 EXAMPLES ************************ // Project KidsDB // Class Main import java.sql.*; public class Main { public static void main(String[] a) throws ClassNotFoundException, SQLException { // Check if the JdbcOdbc driver is found in // the class library. If not, throw a // ClassNotFoundException. This check is // optional. It is useful for debugging when // working with large class libraries. System.out.println(Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver")); System.out.println(); // Set up string identifying the Odbc // entry for the database on the machine // where you want to access the database. String db = "jdbc:odbc:Kids"; // Set up the connection to the database. Connection c = DriverManager.getConnection(db); // Set up the Statement object for the // connection. A Statement object manipulates // the database using SQL expressions. Statement s = c.createStatement(); // A ResultSet object holds the rows in the // table resulting from an SQL SELECT statement. ResultSet r = s.executeQuery( "SELECT * FROM Roster"); // When a ResultSet object is created, the // cursor is positioned immediately before // the first row in the result table. // The method call r.next() moves the cursor // to the next row in the result table. // r.next() returns false when it moves past // the end of the table. while (r.next()) System.out.println( // r.getString(i) returns the ith // column of the current row of the // table as a string. r.getString(1) + " " + r.getString(2) + " " + r.getString(3) + " " + r.getString(4)); // Close the Connection object c when finished. c.close(); } } ************************ // Project KidsDB2 // Class Main import java.sql.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Main { public static void main(String[] a) throws SQLException, ClassNotFoundException { MyFrame f = new MyFrame(); f.show(); } } ************************ // Project KidsDB2 // Class MyFrame import java.sql.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MyFrame extends JFrame { // Instance variables. JTextField name, id, gender, age; JLabel namelabel, idlabel, genderlabel, agelabel, padlabel; JButton first; JButton next; boolean atEOF; JPanel panel; String db; Connection c; Statement s; ResultSet r; MyListener a; public MyFrame() throws SQLException, ClassNotFoundException { // Set caption in parent constructor. super("Grades"); setSize(400, 100); // Allocate space for text fields. name = new JTextField(10); id = new JTextField(10); gender = new JTextField(10); age = new JTextField(10); // Allocate space for labels. namelabel = new JLabel("Name"); idlabel = new JLabel("ID"); genderlabel = new JLabel("Gender"); agelabel = new JLabel("Age"); padlabel = new JLabel(""); first = new JButton("First Kid"); next = new JButton("Next Kid"); panel = new JPanel(new GridLayout(3, 4, 5, 5)); atEOF = false; // Add controls to user interface. panel.add(name); panel.add(id); panel.add(gender); panel.add(age); panel.add(namelabel); panel.add(idlabel); panel.add(genderlabel); panel.add(agelabel); panel.add(padlabel); panel.add(first); panel.add(next); setContentPane(panel); // Create and add action listener. a = new MyListener(); first.addActionListener(a); next.addActionListener(a); // Set up database stuff. // Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); db = "jdbc:odbc:Kids"; c = DriverManager.getConnection(db); } public class MyListener implements ActionListener { public void actionPerformed(ActionEvent event) { try { if (event.getSource() == first) { String str = "SELECT * FROM Roster"; s = c.createStatement(); r = s.executeQuery(str); atEOF = !r.next(); name.setText(r.getString(1)); id.setText(r.getString(2)); gender.setText(r.getString(3)); age.setText(r.getString(4)); } else { if (!atEOF) atEOF = !r.next(); if (!atEOF) { name.setText(r.getString(1)); id.setText(r.getString(2)); gender.setText(r.getString(3)); age.setText(r.getString(4)); } } } catch(SQLException e) { System.out.println("SQLException"); } } } } ************************ // Project KidsDB3 // Class Main import java.sql.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Main { public static void main(String[] a) throws SQLException, ClassNotFoundException { MyFrame f = new MyFrame(); f.show(); } } ************************ // Class KidsDB3 // Project MyFrame import java.sql.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MyFrame extends JFrame { // Instance variables. JTextField name, id, gender, age; JLabel namelabel, idlabel, genderlabel, agelabel, padlabel; JButton first; JButton next; boolean atEOF; JPanel panel; String db; Connection c; Statement s; ResultSet r; MyListener a; public MyFrame() throws SQLException, ClassNotFoundException { // Set caption in parent constructor. super("Grades"); setSize(400, 100); // Allocate space for text fields. name = new JTextField(10); id = new JTextField(10); gender = new JTextField(10); age = new JTextField(10); // Allocate space for labels. namelabel = new JLabel("Name"); idlabel = new JLabel("ID"); genderlabel = new JLabel("Gender"); agelabel = new JLabel("Age"); padlabel = new JLabel(""); first = new JButton("First Kid"); next = new JButton("Next Kid"); panel = new JPanel(new GridLayout(3, 4, 5, 5)); atEOF = false; // Add controls to user interface. panel.add(name); panel.add(id); panel.add(gender); panel.add(age); panel.add(namelabel); panel.add(idlabel); panel.add(genderlabel); panel.add(agelabel); panel.add(padlabel); panel.add(first); panel.add(next); setContentPane(panel); // Create and add action listener. a = new MyListener(); first.addActionListener(a); next.addActionListener(a); // Set up database stuff. // Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); db = "jdbc:odbc:Kids"; c = DriverManager.getConnection(db); } public class MyListener implements ActionListener { public void actionPerformed(ActionEvent event) { try { if (event.getSource() == first) { String str = "SELECT * FROM Roster WHERE Name = '" + name.getText() + "'"; s = c.createStatement(); r = s.executeQuery(str); if (atEOF = !r.next()) return; else { id.setText(r.getString(2)); gender.setText(r.getString(3)); age.setText(r.getString(4)); } } else { if (!atEOF) atEOF = !r.next(); if (!atEOF) { id.setText(r.getString(2)); gender.setText(r.getString(3)); age.setText(r.getString(4)); } } } catch(SQLException e) { System.out.println("SQLException"); } } } } ************************ // Project ByGender // Class Main import java.sql.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Main { public static void main(String[] a) throws SQLException, ClassNotFoundException { MyFrame f = new MyFrame(); f.show(); } } ************************ // Project ByGender // Class MyFrame import java.sql.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MyFrame extends JFrame { // Instance variables for controls. JTextArea textArea; JRadioButton allButton; JRadioButton boysButton; JRadioButton girlsButton; ButtonGroup buttonGroup; JPanel panel; MyListener a; // Instance variables for database access. String db; Connection c; Statement s; ResultSet r; // Miscellaneous instance variable. boolean atEOF; public MyFrame() throws SQLException, ClassNotFoundException { // Set caption in parent constructor. super("Grades"); setSize(350, 300); // Allocate space for controls. allButton = new JRadioButton("All"); boysButton = new JRadioButton("Boys"); girlsButton = new JRadioButton("Girls"); textArea = new JTextArea(10, 20); buttonGroup = new ButtonGroup(); panel = new JPanel(); atEOF = false; // Add radio buttons to button group. buttonGroup.add(allButton); buttonGroup.add(boysButton); buttonGroup.add(girlsButton); // Add controls to user interface. panel.add(allButton); panel.add(boysButton); panel.add(girlsButton); panel.add(textArea); setContentPane(panel); // Create and add action listener. a = new MyListener(); allButton.addActionListener(a); boysButton.addActionListener(a); girlsButton.addActionListener(a); // Set up database stuff. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); db = "jdbc:odbc:Kids"; c = DriverManager.getConnection(db); s = c.createStatement(); } public class MyListener implements ActionListener { public void actionPerformed(ActionEvent event) { try { if (event.getSource() == boysButton) { String sqlStr = "SELECT * FROM Roster " + "WHERE Gender = 'M'"; // s = c.createStatement(); r = s.executeQuery(sqlStr); displayKids(); } else if (event.getSource() == girlsButton) { String sqlStr = "SELECT * FROM Roster " + "WHERE Gender = 'F'"; // s = c.createStatement(); r = s.executeQuery(sqlStr); displayKids(); } else { String sqlStr = "SELECT * FROM Roster"; // s = c.createStatement(); r = s.executeQuery(sqlStr); displayKids(); } } catch(SQLException e) { System.out.println("SQLException"); } } } private void displayKids() { try { textArea.setText(""); while(r.next()) { String str = "\n" + r.getString(1) + " " + r.getString(2) + " " + r.getString(3) + " " + r.getString(4) + " "; textArea.append(str); } } catch(SQLException e) { System.out.println("SQLException"); } } } ************************ // Project WindowClosing // Class Main public class Main { public static void main(String[] args) { MyFrame x = new MyFrame(); x.show(); } } ************************ // Project WindowClosing // Class MyFrame import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.JOptionPane; public class MyFrame extends JFrame { JButton closeButton; JPanel panel; MyFrame saveThis; public MyFrame() { super("Window Closing"); setSize(200, 100); closeButton = new JButton("Close Window"); panel = new JPanel(new FlowLayout()); panel.add(closeButton); setContentPane(panel); saveThis = this; // Add WindowListener to frame. this.addWindowListener(new WindowCloser()); // Add ButtonListener to button. closeButton.addActionListener(new ButtonListener()); } private class WindowCloser implements WindowListener { // Occurs then the close button in the window // control box is clicked. public void windowClosing(WindowEvent e) { JOptionPane.showMessageDialog(saveThis, "Window Closed by Control Box"); // The following line is need to close the // application when the window is closed. System.exit(0); } // Headers with empty method bodies to // satisfy implements WindowListener. // A class that implements an interface must // provide definitions for ALL methods in the // interface. public void windowClosed(WindowEvent e) { } public void windowOpened(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowIconified(WindowEvent e) { } } private class ButtonListener implements ActionListener { // This code is executed when the Close Window // button is clicked. public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(saveThis, "Window Closed by \"Close Window\" Button"); dispose(); System.exit(0); } } } ************************ // Project WindowEvents // Class Main public class Main { public static void main(String[] args) { MyFrame x = new MyFrame(); x.show(); } } ************************ // Project WindowEvents // Class MyFrame import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.JOptionPane; public class MyFrame extends JFrame { private JTextField message; private JPanel panel; private MyFrame savedThis; boolean windowActivated, windowDeactivated; public MyFrame() { super("Window Closing"); setSize(250, 100); message = new JTextField(15); panel = new JPanel(); savedThis = this; windowActivated = false; windowDeactivated = false; panel.add(message); setContentPane(panel); // Add WindowListener to frame. this.addWindowListener(new MyWindowListener()); } private class MyWindowListener implements WindowListener { // Occurs then the close button in the window // control box is clicked. public void windowClosing(WindowEvent e) { JOptionPane.showMessageDialog(savedThis, "Window Closing Event"); } public void windowClosed(WindowEvent e) { JOptionPane.showMessageDialog(savedThis, "Window Closed Event"); } public void windowOpened(WindowEvent e) { JOptionPane.showMessageDialog(savedThis, "Window Opened Event"); } public void windowActivated(WindowEvent e) { if (!windowActivated) { message.setText( "Window Activated Event"); windowDeactivated = false; windowActivated = true; } } public void windowDeactivated(WindowEvent e) { if (!windowDeactivated) { message.setText( "Window Deactivated Event"); windowDeactivated = true; windowActivated = false; } } public void windowDeiconified(WindowEvent e) { } { JOptionPane.showMessageDialog(savedThis, "Window Deiconified Event"); } public void windowIconified(WindowEvent e) { JOptionPane.showMessageDialog(savedThis, "Window Iconified Event"); } } } ************************ // Project MouseClicks // Class Main public class Main { public static void main(String[] str) { MyFrame x = new MyFrame(); x.show(); } } ************************ // Project MouseClicks // Class MyFrame import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MyFrame extends JFrame { private MyPanel panel; public MyFrame() { super("Mouse Clicks"); setSize(300, 300); panel = new MyPanel(); setContentPane(panel); } } ************************ // Project MouseClicks // Class MyPanel import javax.swing.*; import java.awt.*; import java.awt.event.*; class MyPanel extends JPanel { private int[] x, y; private int nPoints; public MyPanel() { // x and y arrays keep track of mouse clicks. x = new int[100]; y = new int[100]; nPoints = 0; addMouseListener(new ClickListener()); } // This method is called automatically // everytime part of the screen needs // repainting. public void paintComponent(Graphics g) { super.paintComponent(g); int i; g.setColor(Color.black); for(i = 0; i < nPoints; i++) g.fillRect(x[i] - 3, y[i] - 3, 6, 6); } private class ClickListener implements MouseListener { public void mouseClicked(MouseEvent e) { // The following line can be // used for debugging. // System.out.println(e); x[nPoints] = (int) e.getPoint().getX(); y[nPoints] = (int) e.getPoint().getY(); nPoints++; repaint(); } // Method headers with empty bodies to // satisfy the MouseListener interface. public void mouseReleased(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } } } ************************ // Project ComboBox // Class Main public class Main { public static void main(String[] args) { MyFrame x = new MyFrame(); } } ************************ // Project ComboBox // Class Main public class Main { public static void main(String[] args) { MyFrame x = new MyFrame(); } } ************************ // Project ComboBox // Class MyFrame import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MyFrame extends JFrame { JPanel panel; JComboBox backgroundColor; public MyFrame() { super("Test of JComboBox"); setSize(300, 300); // Allocate space for combo box. backgroundColor = new JComboBox(); panel = new JPanel(); panel.add(backgroundColor); setContentPane(panel); // Use an action listener to detect // clicks on the combo box. backgroundColor.addActionListener( new ColorListener()); // Add strings to combo box. backgroundColor.addItem("Black"); backgroundColor.addItem("Blue"); backgroundColor.addItem("Green"); backgroundColor.addItem("Red"); backgroundColor.addItem("White"); backgroundColor.addItem("Yellow"); show(); } private class ColorListener implements ActionListener { public void actionPerformed(ActionEvent e) { String color; // Get selected string from combo box. color = (String) backgroundColor.getSelectedItem(); // Set background color according to // selected string from combo box. if(color.equals("Black")) panel.setBackground(Color.black); else if(color.equals("Blue")) panel.setBackground(Color.blue); else if(color.equals("Green")) panel.setBackground(Color.green); else if(color.equals("Red")) panel.setBackground(Color.red); else if(color.equals("White")) panel.setBackground(Color.white); else if(color.equals("Yellow")) panel.setBackground(Color.yellow); } } } ************************ // Project Vector // Class Main // Using the Java Vector collection class. import java.util.Vector; public class Main { public static void main(String[] args) { Vector stooges; stooges = new Vector(); stooges.addElement("Moe"); stooges.addElement("Larry"); stooges.addElement("Curly"); stooges.addElement("Shemp"); stooges.addElement("Joe"); System.out.println(stooges); System.out.println("Stooge #3 is " + stooges.elementAt(3)); stooges.removeElement("Shemp"); System.out.println(stooges); System.out.println(); Vector kids; kids = new Vector(); kids.addElement(new Kid("Jessica", 37463, 'F', 9)); kids.addElement(new Kid("Kevin", 55986, 'M', 10)); kids.addElement(new Kid("Katie", 86372, 'F', 11)); kids.addElement(new Kid("William", 48347, 'M', 10)); System.out.println(kids); System.out.println("Kid #2 is " + kids.elementAt(2)); Kid temp = (Kid) kids.elementAt(2); kids.removeElement(temp); System.out.println(kids); System.out.println(); Vector values = new Vector(); // Use the Integer wrapper class for adding // ints because only classes can be added to // a Vector object. values.addElement(new Integer(43)); values.addElement(new Integer(97)); values.addElement(new Integer(28)); values.addElement(new Integer(13)); values.addElement(new Integer(77)); System.out.println(values); System.out.println("Value #4 is " + values.elementAt(4)); Object x = values.elementAt(4); values.removeElement(x); System.out.println(values); System.out.println(); } } ************************ // Vector Project // Class Kid public class Kid { // Private instance variables. private String name; private int id; private char gender; private short age; // Default constructor. public Kid() { // Initialize to default values. name = "Unknown"; id = 99999; gender = 'U'; age = -1; } // Parameterized constructor. public Kid(String aName, int anId, char aGender, int anAge) { // name is not the null string. if (aName.equals("")) name = "Unknown"; else name = aName; // id is between 0 and 99999. if (anId < 0 || anId > 99998) id = 99999; else id = anId; // Gender is 'F', 'M', or 'U'. if (aGender != 'F' && aGender != 'M') gender = 'U'; else gender = aGender; // Age is nonnegative. if (anAge < 0) age = (short) -1; age = (short) anAge; } // Accessor method for name. public String getName() { return name; } // Accessor method for id. public int getId() { return id; } // Accessor method for gender. public char getGender() { return gender; } // Accessor method for age. public short getAge() { return (short) age; } // Mutator method for age. public void hasBirthday() { age++; } // Print method. public void print() { System.out.print("name=" + name + " " ); System.out.print("id=" + id + " " ); System.out.print("gender=" + gender + " "); System.out.println("age=" + age + '\n'); } public String toString() { return "<" + name + ";" + id + ";" + gender + ";" + age + ">"; } } ************************ // Project Recursive // Class Main // Practice problem: predict the output by first // drawing the recursion tree. public class Main { public static void main(String[] args) { f(3); } public static void f(int n) { if (n > 0) { System.out.print(n + " "); f(n - 1); System.out.print(n + " "); f(n - 2); System.out.print((n + 1) + " "); } } } ************************ // Project FamilyTree // Class Main import java.util.Vector; public class Main { public static void main(String[] args) { Person root = new Person("John"); Person temp; // Add children of John. root.children.addElement(new Person("Mary")); root.children.addElement(new Person("William")); root.children.addElement(new Person("Agnes")); // Add children of Mary ((Person) root.children.elementAt(0)).children. addElement(new Person("Tamera")); ((Person) root.children.elementAt(0)).children. addElement(new Person("Scott")); // Add children of William temp = (Person) (root.children.elementAt(1)); temp.children.addElement(new Person("Susan")); temp.children.addElement(new Person("Jerry")); // Add child of Agnes. temp = (Person) (root.children.elementAt(2)); temp.children.addElement(new Person("Winston")); // Add child of Susan. temp = (Person) ((Person) (root.children.elementAt(1))). children.elementAt(0); temp.children.addElement(new Person("Brittany")); root.print(); } } ************************ // Project FamilyTree // Class Person import java.util.Vector; public class Person { public String name; public Vector children; public Person(String aName) { name = aName; children = new Vector(); } // Recursive print routine. public void print() { int i; System.out.println(name); for(i = 0; i < children.size(); i++) ((Person) (children.elementAt(i))).print(); } } ************************