Results 1 to 4 of 4

Thread: [RESOLVED] Convert to using a list instead of the model

  1. #1

    Thread Starter
    PowerPoster Nightwalker83's Avatar
    Join Date
    Dec 2001
    Location
    Adelaide, Australia
    Posts
    13,344

    Resolved [RESOLVED] Convert to using a list instead of the model

    Hi,

    I need to know how to convert project to use a list of strings to populate the table without using the table model to populate the table with the data. This is my attempt at trying to make the project work without the table model but as you can see it has tons of errors.


    Files in the DAO:

    PencilDAO:
    java Code:
    1. package DAO;
    2.  
    3. import model.Pencil;
    4. import model.*;
    5. import java.sql.*;
    6. import java.util.*;
    7.  
    8. /**
    9.  * Data Access Class for the Pencil database
    10.  */
    11. public class PencilDAO extends PencilsApplicationDAO{
    12.  
    13.   /**
    14.    * The Prepared statement used for selecting Pencils
    15.    */
    16.   private static PreparedStatement selectAllPreparedStatement = null;
    17.  
    18.  
    19.   /**
    20.    * Retrieves all book records  from the tblPencils
    21.    * table in a database as a List of Pencil objects. Will create the
    22.    * selectAllPreparedStatement object only once (the first time the method
    23.    * is called, ie when selectAllPreparedStatement==null)
    24.    * @return A list of Pencil objects which are all of the records from the table
    25.    *         tblPencils.
    26.    *         Will be null if any error occurs (eg table does not exist)
    27.    */
    28.   public static List<Pencil> retrieveAllColourPencils() {
    29.     List<Pencil> results = null;
    30.     String SQLStatementStr =
    31.             "SELECT colour, size "+
    32.             "FROM tblPencils " +
    33.             "ORDER BY colour, size";
    34. //            "SELECT colourKey,length,colourName "+
    35. //            "FROM tblPencil,tblColour " +
    36. //            "WHERE tblColour.colourKey=tblColour.colourKey "+
    37. //            "ORDER BY colourKey";
    38.  
    39.     ResultSet rs;
    40.     try {
    41.       if (selectAllPreparedStatement == null) {
    42.         selectAllPreparedStatement = con.prepareStatement(SQLStatementStr);
    43.       }
    44.       rs = selectAllPreparedStatement.executeQuery();
    45.       results = new ArrayList<Pencil>();
    46.       while (rs.next()) {
    47.         Pencil record;
    48.         record = new Pencil(rs.getString("colour"), rs.getInt("size"));
    49.         results.add(record);
    50.       }
    51.     } catch (SQLException ex) {
    52.       results = null;
    53.     }
    54.     return results;
    55.   }
    56. }

    PencilsApplicationDAO:
    java Code:
    1. package DAO;
    2.  
    3. import model.Pencil;
    4. import java.sql.*;
    5. import java.util.*;
    6. import model.*;
    7.  
    8. /**
    9.  * General database access routines
    10.  */
    11. public class PencilsApplicationDAO {
    12.   /**
    13.    * The Prepared statement used for selecting Pencils for
    14.    * a particular colour
    15.    */
    16.   private static PreparedStatement selectColourPreparedStatement = null;
    17.  
    18.   /**
    19.    * The database for the Pencil Application
    20.    */
    21.   public static final String DB_NAME= "5IJA_DB";
    22.   /**
    23.    * The connection to the database
    24.    */
    25.   protected static Connection con=null;
    26.   /**
    27.    * Connects to the database assuming a suitable driver is available
    28.    * Will throw an exception if an error occurs. Otherwise a connection is
    29.    * established and the con class variable is ready to be used.
    30.    * @throws SQLException
    31.    */
    32.   public static void connectToDatabase() throws SQLException {
    33.  
    34. //    con = DriverManager.getConnection("jdbc:odbc:" + DB_NAME);
    35.  
    36.      con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+DB_NAME , "root", "password");
    37.   }
    38.  
    39.   /**
    40.    * Getter for connection object if needed
    41.    * @return the Connection object
    42.    */
    43.   public static Connection getConnection() {
    44.     return con;
    45.   }
    46.  
    47.     /**
    48.    * Retrieves all pencil records of a particular colour from the tblPencils
    49.    * table in a database as a List of Pencil objects. Will create the
    50.    * selectColourPreparedStatement object only once (the first time the method
    51.    * is called, ie when selectColourPreparedStatement==null)
    52.    * @param colour The colour of the pencils to retrieve
    53.    * @return A list of Pencil objects which are all of the records from the table
    54.    *         tblPencils with the colour as per the provided parameter.
    55.    *         Will be null if any error occurs (eg table does not exist)
    56.    */
    57.   public static List<Pencil> retrievePencils(String colour) {
    58.     List<Pencil> results = null;
    59.     String SQLStatementStr =
    60.             "SELECT colour, size "+
    61.             "FROM tblPencils " +
    62.             "WHERE colour = ? "+
    63.             "ORDER BY colour";
    64.  
    65.     ResultSet rs;
    66.     try {
    67.       if (selectColourPreparedStatement  == null) {
    68.         selectColourPreparedStatement = con.prepareStatement(SQLStatementStr);
    69.       }
    70.       selectColourPreparedStatement .setString(1, colour);
    71.       rs = selectColourPreparedStatement.executeQuery();
    72.       results = new ArrayList<Pencil>();
    73.       while (rs.next()) {
    74.         Pencil record;
    75.         record = new Pencil(rs.getString("colour"), rs.getInt("size"));
    76.         results.add(record);
    77.       }
    78.     } catch (SQLException ex) {
    79.       results = null;
    80.     }
    81.     return results;
    82.   }
    83. }


    Files in the Controller:

    PencilApplication:
    java Code:
    1. package controller;
    2.  
    3. import DAO.*;
    4. import view.*;
    5. import model.*;
    6. import java.sql.*;
    7. import java.util.*;
    8.  
    9. /**
    10.  * Displays and controls a simple view of a book table
    11.  */
    12. public class PencilApplication {
    13.  
    14.   private PencilMainViewFrame mainFrame;
    15.   private List<Pencil> data;
    16.   private List<String> colourList;
    17.  
    18.   public PencilApplication() {
    19.     // Create the view letting it know the controller
    20.     mainFrame = new PencilMainViewFrame(this);
    21.     mainFrame.setVisible(true);
    22.  
    23.     // Connect to DB. If this fails the view will need to display a
    24.     // message and program will abort
    25.     connectToDatabase();
    26.  
    27.     // Setup the model for the distinct publishers list box
    28.     List<String> colourList;
    29.     colourList = PencilsApplicationDAO.retrieveDistinctColours();
    30.     if (colourList == null) {
    31.       mainFrame.displayDatabaseUnExpectedError("Unable to Retrieve colour of pencils!");
    32.     } else {
    33.       mainFrame.displaynewListOfColours(colourList);
    34.     }
    35.     // Initial data of books is null until user makes a choice. This 'null' based
    36.     // model will at least allow the JTable column headings to be visible.
    37.     data = null;
    38.     //mainFrame.displaynewListOfColours;
    39.   }
    40.  
    41.   /**
    42.    * Uses the DAO to connect to the database.
    43.    * Will display a popup message dialogue if the connection fails and then
    44.    * exit the application. Otherwise a connection is established and the instance
    45.    * variable is ready to be used.
    46.    */
    47.   private void connectToDatabase() {
    48.     try {
    49.       PencilsApplicationDAO.connectToDatabase();
    50.     } catch (SQLException ex) {
    51.       mainFrame.displayDatabaseConnectionError();
    52.       System.exit(-1);
    53.     }
    54.   }
    55.  
    56.   /**
    57.    * User (through view) has requested display of Books of a particular
    58.    * pubName. These will be retrieved from the table using the DAO methods. Then
    59.    * the view will be asked to update itself using the new BookJTableModel or
    60.    * display an error if something goes wrong.
    61.    * @param pubName The pubName of the books to be displayed
    62.    */
    63.   public void displaycolourpencils(String colour) {
    64.     data = PencilDAO.retrievePencils(colour);
    65.     if (data == null) {
    66.       mainFrame.displayDatabaseUnExpectedError("Unable to Retrieve colour of pencils " + colour);
    67.     } else {
    68.       this.mainFrame.displayNewPencilData(data);
    69.     }
    70.   }
    71.  
    72.   /**
    73.    * Get everything going
    74.    * @param args Not used
    75.    */
    76.   public static void main(String args[]) {
    77.     new PencilApplication();
    78.   }
    79. }
    Thanks,


    Nightwalker
    Attached Images Attached Images  
    Last edited by Nightwalker83; Jun 20th, 2012 at 01:59 AM. Reason: Adding more!
    when you quote a post could you please do it via the "Reply With Quote" button or if it multiple post click the "''+" button then "Reply With Quote" button.
    If this thread is finished with please mark it "Resolved" by selecting "Mark thread resolved" from the "Thread tools" drop-down menu.
    https://get.cryptobrowser.site/30/4111672

  2. #2

    Thread Starter
    PowerPoster Nightwalker83's Avatar
    Join Date
    Dec 2001
    Location
    Adelaide, Australia
    Posts
    13,344

    Re: [RESOLVED] Convert to using a list instead of the model

    Files in the Model:

    ColourComboBoxModel:
    java Code:
    1. package model;
    2.  
    3. import java.util.*;
    4. import javax.swing.*;
    5.  
    6. /**
    7.  * A model for the colours JList
    8.  *
    9.  */
    10. public class ColourComboBoxModel extends AbstractListModel implements ComboBoxModel {
    11.  
    12.   /**
    13.    * The list of colours
    14.    */
    15.   private List<String> data;
    16.   private String selectedItem = "Make a Choice";
    17.  
    18.   /**
    19.    * Initialise the data to the provided list
    20.    * @param data The list of colours
    21.    */
    22.   public ColourComboBoxModel(List<String> data) {
    23.     this.data = data;
    24.   }
    25.  
    26.   /**
    27.    *
    28.    * @return The number of colours to display
    29.    */
    30.   public int getSize() {
    31.     if (data != null) {
    32.       return data.size();
    33.     } else {
    34.       return 0;
    35.     }
    36.   }
    37.  
    38.   /**
    39.    *
    40.    * @param index The position within the list
    41.    * @return the colours to display at that position. This would be taken from
    42.    *         the data list
    43.    */
    44.   public Object getElementAt(int index) {
    45.  
    46.     if (data == null) {
    47.       return "";
    48.     }
    49.  
    50.       String cellData;
    51.     cellData = data.get(index);
    52.     return cellData;
    53.   }
    54.   public void setSelectedItem(Object anItem) {
    55.     this.selectedItem = (String) anItem;
    56.   }
    57.  
    58.   public Object getSelectedItem() {
    59.     return this.selectedItem;
    60.   }
    61.  
    62.   public void setData(List<String> colourList) {
    63.     this.data = colourList;
    64.     fireContentsChanged(this, 0, 0);
    65.   }
    66. }

    Pencil:
    java Code:
    1. package model;
    2.  
    3. public class Pencil {
    4.  
    5.   public static final String DEF_COLOUR = "RED";
    6.   public static final int DEF_LENGTH = 0;
    7.   private String colour;
    8.   private int length;
    9.  
    10.   public Pencil() {
    11.     this(DEF_COLOUR, DEF_LENGTH);
    12.   }
    13.  
    14.   public Pencil(String colour, int length) {
    15.     this.colour = colour.toUpperCase();
    16.     this.length = length;
    17.   }
    18.  
    19.   /**
    20.    * Get the value of length
    21.    *
    22.    * @return the value of length
    23.    */
    24.   public int getLength() {
    25.     return length;
    26.   }
    27.  
    28.   public void setLength(int length) {
    29.     this.length = length;
    30.   }
    31.  
    32.   public String getColour() {
    33.     return colour;
    34.   }
    35.  
    36.   public void setColour(String colour) {
    37.     this.colour = colour.toUpperCase();
    38.   }
    39.  
    40.   public String toString() {
    41.     return super.toString() + "[" +
    42.             "colour=" + this.colour +
    43.             ",length=" + this.length +
    44.             "]";
    45.   }
    46.  
    47. }

    PencilJTableModel:
    java Code:
    1. package model;
    2.  
    3. import java.util.*;
    4. import javax.swing.table.*;
    5.  
    6. /**
    7.  * A model for the Pencil JTable
    8.  *
    9.  */
    10. public class PencilJTableModel extends AbstractTableModel {
    11.  
    12.   /**
    13.    * The list of Pencil objects used for the JTable display
    14.    */
    15.   private String[] columnNames = new String[]{"Colour", "Length"};
    16.   private List<Pencil> data;
    17.  
    18.   public PencilJTableModel() {
    19.     this(null);
    20.   }
    21.  
    22.   public PencilJTableModel(List<Pencil> data) {
    23.     this.data = data;
    24.   }
    25.  
    26.   /**
    27.    *
    28.    * @return The number of rows to be displayed which would be the size of the
    29.    * data list.
    30.    */
    31.   public int getRowCount() {
    32.     if (data != null) {
    33.       return data.size();
    34.     } else {
    35.       return 0;
    36.     }
    37.   }
    38.  
    39.   /**
    40.    *
    41.    * @return The number of columns to display
    42.    */
    43.   public int getColumnCount() {
    44.     return columnNames.length;
    45.   }
    46.  
    47.   /**
    48.    * Returns the value for the cell at rowIndex and columnIndex.
    49.    * Extracts the Pencil object at index rowIndex from the list data then
    50.    * extracts the Pencil data from that object according to the names in
    51.    * colNames
    52.    *
    53.    * @param rowIndex    the rowIndex whose value is to be queried
    54.    * @param columnIndex     the columnIndex whose value is to be queried
    55.    * @return    the value Object at the specified cell
    56.    */
    57.   public Object getValueAt(int rowIndex, int columnIndex) {
    58.     Pencil record;
    59.     Object cellData = null;
    60.     String colName;
    61.  
    62.     if (data == null) {
    63.       return "";
    64.     }
    65.  
    66.     record = data.get(rowIndex);
    67.  
    68.  
    69.     switch (columnIndex) {
    70.       case 0:
    71.         cellData = record.getColour();
    72.         break;
    73.       case 1:
    74.         cellData = record.getLength();
    75.         break;
    76.       default:
    77.         cellData = "unkown";
    78.         break;
    79.     }
    80.  
    81.     return cellData;
    82.   }
    83.  
    84.   /**
    85.    *  Returns the column names for the table Pencil column 0 is Colour and
    86.    *  column 1 is Length.
    87.    *  If column is not 0 or 1 will return a null String.
    88.    *
    89.    * @param column  the column being queried
    90.    * @return a string containing the  name of column
    91.    */
    92.   public String getColumnName(int column) {
    93.     return columnNames[column];
    94.   }
    95.  
    96.       public void setData(List<Pencil> data) {
    97.        this.data = data;
    98.        fireTableDataChanged();
    99.     }
    100. }
    Last edited by Nightwalker83; Jun 20th, 2012 at 01:57 AM. Reason: Adding more!
    when you quote a post could you please do it via the "Reply With Quote" button or if it multiple post click the "''+" button then "Reply With Quote" button.
    If this thread is finished with please mark it "Resolved" by selecting "Mark thread resolved" from the "Thread tools" drop-down menu.
    https://get.cryptobrowser.site/30/4111672

  3. #3

    Thread Starter
    PowerPoster Nightwalker83's Avatar
    Join Date
    Dec 2001
    Location
    Adelaide, Australia
    Posts
    13,344

    Re: [RESOLVED] Convert to using a list instead of the model

    In "Test" folder:

    SetupPenilData.java
    java Code:
    1. /*
    2.  * To change this template, choose Tools | Templates
    3.  * and open the template in the editor.
    4.  */
    5. package tests;
    6.  
    7. import DAO.PencilsApplicationDAO;
    8. import DAO.PencilDAO;
    9. import java.sql.*;
    10.  
    11. /**
    12.  *
    13.  */
    14. public class SetupPencilData {
    15.  
    16.   public static void main(String[] args) throws SQLException {
    17.     String sqlSt;
    18.  
    19.     try {
    20.       PencilsApplicationDAO.connectToDatabase();
    21.     } catch (SQLException ex) {
    22.       System.out.println("UNABLE to connect to database.");
    23.       System.exit(-1);
    24.     }
    25.  
    26.     Connection con = PencilDAO.getConnection();
    27.     Statement s = null;
    28.     s = con.createStatement();
    29.  
    30.     // Create tables
    31.     try {
    32.       sqlSt = "DROP TABLE tblPencils";
    33.       s.executeUpdate(sqlSt);
    34.     } catch (SQLException ex) {
    35.       if (ex.getMessage().contains("Unknown table") || ex.getMessage().contains("does not exist")) {
    36.         System.out.println("code="+ex.getErrorCode());
    37.         System.out.println("TABLE tblPencils does not exist but will be created.");
    38.       } else {
    39.         ex.printStackTrace();
    40.       }
    41.     }
    42.  
    43.     System.out.println("CREATING TABLES...");
    44.     sqlSt = "CREATE TABLE tblPencils (colour VARCHAR(50), size INT)";
    45.     s.executeUpdate(sqlSt);
    46.  
    47.     ResultSet rs;
    48.     int colourKey;
    49.     System.out.println("INSERTING pencil records...");
    50.     //INSERT Pencils Green
    51.     sqlSt = "INSERT into tblPencils values ('GREEN',10), ('GREEN',10), ('BLUE',20), ('RED',15), ('GREEN',10), ('BLACK',8)";
    52.     s.executeUpdate(sqlSt);
    53.  
    54.     con.close();
    55.   }
    56. }

    Files in the View:

    PencilJTableViewPanel.java
    java Code:
    1. package view;
    2.  
    3. import model.PencilJTableModel;
    4. import java.awt.BorderLayout;
    5. import javax.swing.*;
    6. import model.Pencil;
    7. import java.util.List;
    8. /**
    9.  * The JPanel for the JTable
    10.  */
    11. public class PencilJTableViewPanel extends JPanel {
    12.  
    13.   private JTable dataTable;
    14.   private JScrollPane scrollPane;
    15.  
    16.   /**
    17.    * Cretae the Panel for the JTable. Placing the JTable in a JScrollPane
    18.    */
    19.   public PencilJTableViewPanel() {
    20.  
    21.     dataTable = new JTable();
    22.     dataTable.setModel(new PencilJTableModel());
    23.     scrollPane = new JScrollPane(dataTable);
    24.     setLayout(new BorderLayout());
    25.     add(scrollPane, BorderLayout.CENTER);
    26.  
    27.   }
    28.     /**
    29.    *
    30.    * @return the model currently being used by the JTable
    31.    */
    32.   public PencilJTableModel getModel() {
    33.     return (PencilJTableModel) (dataTable.getModel());
    34.   }
    35.  
    36.   /**
    37.    * Change the data used by the JTable
    38.    * @param model The new data for the JTable
    39.    */
    40.   public void setModel(PencilJTableModel model) {
    41.     dataTable.setModel(model);
    42.   }
    43.  
    44.     /**
    45.    * Change the data used by the JTable
    46.    * @param model The new data for the JTable
    47.    */
    48.   public void setData(List<Pencil> data) {
    49.     this.getModel().setData(data);
    50.   }
    51.  
    52. }

    PencilMainViewFrame.java:
    java Code:
    1. package view;
    2.  
    3. import controller.*;
    4. import java.awt.*;
    5. import java.awt.event.*;
    6. import javax.swing.*;
    7. import model.*;
    8.  
    9. /**
    10.  * Displays a simple GUI allowing user to view a table of pencils of a
    11.  * chosen colour
    12.  */
    13. public class PencilMainViewFrame extends JFrame {
    14.  
    15.   private JLabel lblColours;
    16.   private JComboBox lstColours;
    17.   private JPanel panButtons;
    18.   private PencilJTableViewPanel panData;
    19.   private PencilApplication theController;
    20.  
    21.   /**
    22.    * Create the view Frame for this application
    23.    * @param theController Logic will be handled by this controller
    24.    * @param lstModel The data for for the JList
    25.    * @param tabModel The data for the JTable
    26.    */
    27.   public PencilMainViewFrame(PencilApplication theController) {
    28.     super("COLOUR PENCILS");
    29.  
    30.     this.theController = theController;
    31.  
    32.     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    33.  
    34.     lstColours = new JComboBox();
    35.     lstColours.setModel(new ColourComboBoxModel(null));
    36.     lblColours = new JLabel("Choose a colour: ");
    37.  
    38.     //Setup Button panel
    39.     panButtons = new JPanel(new FlowLayout(FlowLayout.CENTER));
    40.     panButtons.add(lblColours);
    41.     panButtons.add(lstColours);
    42.     panButtons.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    43.  
    44.     // Setup books data panel
    45.     panData = new PencilJTableViewPanel();
    46.  
    47.     //Add panels to frame
    48.     add(panButtons, BorderLayout.SOUTH);
    49.     add(panData, BorderLayout.CENTER);
    50.  
    51.     // Register event handlers
    52.     lstColours.addActionListener(new ComboPublisherEventHandler());
    53.  
    54.     //Finish off
    55.     setSize(600, 250);
    56.     setVisible(true);
    57.   }
    58.  
    59.   /**
    60.    * When the controller chooses to this will display new Book data in the JTable
    61.    * @param bookJTableModel The new data for the JTable
    62.    */
    63.   public void displayNewPencilData(java.util.List<Pencil> data) {
    64.     panData.setData(data);
    65.   }
    66.  
    67.   /**
    68.    * When the controller chooses to this will display an error connecting to database message
    69.    * @param bookJTableModel The new data for the JTable
    70.    */
    71.   public void displayDatabaseConnectionError() {
    72.     JOptionPane.showMessageDialog(this, "UNABLE TO CONNECT TO DATABASE");
    73.   }
    74.  
    75.   /**
    76.    * When the controller chooses to this will display an error connecting to database message
    77.    * @param bookJTableModel The new data for the JTable
    78.    */
    79.   public void displayDatabaseUnExpectedError(String message) {
    80.     JOptionPane.showMessageDialog(this, "UNEXPECTED DATABASE ERROR HAS OCCURED\n" + message);
    81.   }
    82.  
    83.   /**
    84.    * Change the data used by the JComboBox
    85.    * @param model The new data for the JComboBox
    86.    */
    87.   public void displaynewListOfColours(java.util.List<String> colours) {
    88.     ((ColourComboBoxModel)lstColours.getModel()).setData(colours);
    89.   }
    90.  
    91.   /**
    92.    * Inner class eventHandler for the JComboBox of Colours
    93.    */
    94.   class ComboPublisherEventHandler implements ActionListener {
    95.  
    96.     /**
    97.      * Responds to a new publisher being chosen from the JList
    98.      * @param e Details of the event
    99.      */
    100.     public void actionPerformed(ActionEvent e) {
    101.       String chosenColour;
    102.  
    103.       chosenColour = (String) (lstColours.getModel().getSelectedItem());
    104.       theController.displaycolourpencils(chosenColour);
    105.     }
    106.   }
    107. }
    when you quote a post could you please do it via the "Reply With Quote" button or if it multiple post click the "''+" button then "Reply With Quote" button.
    If this thread is finished with please mark it "Resolved" by selecting "Mark thread resolved" from the "Thread tools" drop-down menu.
    https://get.cryptobrowser.site/30/4111672

  4. #4

    Thread Starter
    PowerPoster Nightwalker83's Avatar
    Join Date
    Dec 2001
    Location
    Adelaide, Australia
    Posts
    13,344

    Re: [RESOLVED] Convert to using a list instead of the model

    Use my attempt at the above exercise I completed it by changing the following:

    1. In the retrieveDistinctColours() method, since there is no question mark in the sql statement you don't need (can't use) the setString() method. This will crash it.

    2. In the displaycolourpencils() method in PencilApplication.java, you're calling retrieveAllColourPencils() - you should be calling the retrievePencils method instead.

    3. In the DAO using the variable selectColourPreparedStatement in two methods retrievePencils and retrieveDistinctColours. You need to have two Prepared Statements (one for each method)

    4. In my database I had colour and length.
    when you quote a post could you please do it via the "Reply With Quote" button or if it multiple post click the "''+" button then "Reply With Quote" button.
    If this thread is finished with please mark it "Resolved" by selecting "Mark thread resolved" from the "Thread tools" drop-down menu.
    https://get.cryptobrowser.site/30/4111672

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width