Java estate agent database with Swing GUI

Java estate agent database with Swing GUI

Object-Oriented Software Development 2

You are being asked to create a SWING GUI application for a house application. Currently, the
application consists of two programs: House.java and HouseApplication.java, which are used tostore and display a set of house records for an estate agent website using a Swing application withwhich the user can interact by means of buttons.
The House class represents a set of data about a house, along with a constructor method and a setof accessor methods for the class’s instance variables and two mutator methods (for the price andprice change of the house).
The HouseApplication frame is organised as follows:
• The labels and text fields for displaying the house data are organised on a top panel which usesthe MigLayout layout manager. All labels and text fields can grow horizontally (along the x-axis)and the label and text field for each attribute are on a separate line. The text fields are not initiallyeditable.
oEach house has an associated photo in JPG format whose location is stored in its
imageLocation attribute. This photo is used to create an ImageIcon object which can
then be used as the contents of the houseImageLabel label, with its alignment being set
to centered by passing in SwingConstants.CENTER as an alignment argument.
oThese photos are in a subfolder called images in the Zip file and should be placed in the
top level of your package structure.
oThe label containing the photo can push and grow and also span 2 columns.
• A set of buttons which allow the user to move to the first, previous, next and last records in thecollection (implemented as an ArrayList) and display their contents in the top panel, along with abutton allowing the user to edit the current record are stored on a panel using a GridLayoutlayout manager with 1 row and 5 columns. This panel in turn is added to a bottom panel usingFlowLayout to ensure that all buttons appear as being of the same size but do not occupy theentire bottom panel. The navigation buttons display images in PNG format which you will find inthe Zip file and which should be placed in the top level of your package structure.
oWhen the edit button is clicked, then its text changes to “Save” and the price text field is
made editable. Clicking on the button a second time causes the value in the price text
field to be stored in the current record, along with a new value for the price change which
is be stored in the record and displayed in the change text field, all text fields are reset to
be not editable, and a message box is displayed saying that the record has been
updated, and the text of the button is reset to “Edit”.
oWhen the navigation buttons are pressed, if the text fields are in an editable state, then
the current record is updated and the text fields and edit button returned to their original
state before we display the appropriate record.
• These top and bottom panels are added to the frame using a BorderLayout layout manager withthe top panel being positioned at CENTER and the bottom panel being positioned at SOUTH.

There is a menu bar at the top of the application with two menus: a Display menu with menu items tonavigate the records in the collection, and to edit the current record, in the top panel, and an Exitmenu with a menu item to close the window.
The application should initially look like this:

Clicking on the edit button should cause the application to look like this:

You are given code for House.java and HouseApplication.java. You should extend this code as
follows by reorganising the menus and associated functionality:

  1. The first menu will be called Modify. You should add options to this menu to allow you to Deletethe current record and to Create a new record at the end of the collection.
    All of these options should be password-protected. Add a static String variable called
    password with an initial value of “3175” to HouseApplication You should require theappropriate action listeners to call a getPassword() method which displays a dialog box like this:

getPassword() should return true if result matches the existing password, or display an error
message and return false if the two do not match.
The delete option displays a warning message that the current item will be deleted.

If ok is clicked the above password dialog is displayed. If the correct password is entered the
current record is removed from the collection and displays the next item in the collection (unlessthe record removed is the last record, in which case the previous record will be displayed).
The add option should cause a dialog of class CreateHouseDialog to be displayed if the correct
password is entered.

It displays a set of labels and data fields using MigLayout for the top panel into which the user
enters data for the new record. The buttons on the bottom panel are added using FlowLayout.
Clicking the Add button should cause a new record to be created provided that the data is valid:
i.) All fields should be non-null.
ii.) The value in the bedrooms and bathrooms fields should represent integers and
the value in the price field should represent a double.
2. The third menu should be called Reports. It should contain two commands – Search records andSummary report.
The Search records command should cause a dialog to be displayed using
JOptionPane.showInputDialog. This dialog contains a combo box which should be populated
with the ids of the records currently in the array list.

The user chooses an id by clicking OK and the record with that id should be displayed (NB: the
record with id x is not likely to be at position x in the array list so you will have to search).
The Summary report command should cause a frame of class HouseSummaryDialog to be
displayed which lists all record details and calculates and displays the average price of the
houses in the collection. (This example was created by using a GridLayout with enough rows for
the header containing the row titles, a row for each record in the collection, and the footer
displaying the average, and columns containing JLabels displaying each piece of data about the
records, but you could also use a JTextArea to display the data):

CreateHouseDialog.java 

package CA2;

import java.awt.BorderLayout;

import java.awt.FlowLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.ArrayList;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JTextField;

import net.miginfocom.swing.MigLayout;

public class CreateHouseDialog extends JFrame {

/* Code goes here */

} 

House.java 

package CA2;

public class House {

private int id;

private String imageLocation;

private String street;

private String city;

private int bedrooms;

private int bathrooms;

private double price;

private double change;

private String contactNo;

public static int count = 0;

public House(String street, String city, int bedrooms, int bathrooms, double price, String imageLocation, String contactNo) {

this.id = ++count;

this.street = street;

this.city = city;

this.bedrooms = bedrooms;

this.bathrooms = bathrooms;

this.price = price;

this.change = 0.0;

this.imageLocation = imageLocation;

this.contactNo = contactNo;

}

public int getId() {

return id;

}

public String getStreet() {

return street;

}

public String getCity() {

return city;

}

public int getBedrooms() {

return bedrooms;

}

public int getBathrooms() {

return bathrooms;

}

public double getPrice() {

return price;

}

public double getChange() {

return change;

}

public String getImageLocation() {

return imageLocation;

}

public String getContactNo() {

return contactNo;

}

public void setPrice(double price) {

this.price = price;

}

public void setChange(double change) {

this.change = change;

}

} 

HouseApplication.java 

package CA2;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import net.miginfocom.swing.MigLayout;

import java.text.NumberFormat;

import java.util.*;

public class HouseApplication extends JFrame {

ArrayList<House> houseList = new ArrayList<House>();

JMenuBar menuBar;

JMenu modifyMenu, reportMenu, closeMenu;

JMenuItem createItem,  deleteItem,  searchItem, summaryItem, closeApp;

JButton firstItemButton, nextItemButton, prevItemButton, lastItemButton, editItemButton;

JLabel houseImageLabel, idLabel, streetLabel, cityLabel, bedroomsLabel, bathroomsLabel, priceLabel, changeLabel, contactNoLabel;

JTextField idTextField, streetTextField, cityTextField, bedroomsTextField, bathroomsTextField, priceTextField, changeTextField, contactNoTextField;

String[][] records = { {“113 The Maltings”, “Dublin 8”, “2”, “1”, “155500.00”, “House1.jpg”, “(087) 9011135”},

{“78 Newington Lodge”, “Dublin 14”, “3”, “2”, “310000.00”, “House2.jpg”, “(087) 9010580”},

{“62 Bohernabreena Road”, “Dublin 24”, “3”, “1”, “220000.00”, “House3.jpg”, “(087) 6023159”},

{“18 Castledevitt Park”, “Dublin 15”, “3”, “3”, “325000.00”, “House4.jpg”, “(087) 9010580”},

{“40 Dunsawny Road”, “Swords”, “3”, “19”, “245000.00”, “House5.jpg”, “(087) 9011135”}

};

int currentItem;

ActionListener first, next, prev, last, edit;

public HouseApplication() {

super(“Estate Agent Application”);

for (int i = 0; i < records.length; i++) {

houseList.add(new House(records[i][0], records[i][1], Integer.parseInt(records[i][2]),

Integer.parseInt(records[i][3]), Double.parseDouble(records[i][4]), records[i][5], records[i][6]));

}

currentItem = 0;

initComponents();

}

public void initComponents() {

setLayout(new BorderLayout());

JPanel displayPanel = new JPanel(new MigLayout());

// Ensures that image is centred in label

houseImageLabel = new JLabel(new ImageIcon(), SwingConstants.CENTER);

displayPanel.add(houseImageLabel, “push, grow, span 2, wrap”);

idLabel = new JLabel(“House ID: “);

idTextField = new JTextField(3);

idTextField.setEditable(false);

displayPanel.add(idLabel, “growx, pushx”);

displayPanel.add(idTextField, “growx, pushx, wrap”);

streetLabel = new JLabel(“Address Line 1: “);

streetTextField = new JTextField(15);

streetTextField.setEditable(false);

displayPanel.add(streetLabel, “growx, pushx”);

displayPanel.add(streetTextField, “growx, pushx, wrap”);

cityLabel = new JLabel(“Address Line 2: “);

cityTextField = new JTextField(15);

cityTextField.setEditable(false);

displayPanel.add(cityLabel, “growx, pushx”);

displayPanel.add(cityTextField, “growx, pushx, wrap”);

bedroomsLabel = new JLabel(“Number of bedrooms: “);

bedroomsTextField = new JTextField(3);

bedroomsTextField.setEditable(false);

displayPanel.add(bedroomsLabel, “growx, pushx”);

displayPanel.add(bedroomsTextField, “growx, pushx, wrap”);

bathroomsLabel = new JLabel(“Number of bathrooms: “);

bathroomsTextField = new JTextField(3);

bathroomsTextField.setEditable(false);

displayPanel.add(bathroomsLabel, “growx, pushx”);

displayPanel.add(bathroomsTextField, “growx, pushx, wrap”);

priceLabel = new JLabel(“Price: “);

priceTextField = new JTextField(10);

priceTextField.setEditable(false);

displayPanel.add(priceLabel, “growx, pushx”);

displayPanel.add(priceTextField, “growx, pushx, wrap”);

changeLabel = new JLabel(“Price change: “);

changeTextField = new JTextField(10);

changeTextField.setEditable(false);

displayPanel.add(changeLabel, “growx, pushx”);

displayPanel.add(changeTextField, “growx, pushx, wrap”);

contactNoLabel = new JLabel(“Contact number: “);

contactNoTextField = new JTextField(15);

contactNoTextField.setEditable(false);

displayPanel.add(contactNoLabel, “growx, pushx”);

displayPanel.add(contactNoTextField, “growx, pushx, wrap”);

add(displayPanel, BorderLayout.CENTER);

JPanel buttonPanel = new JPanel(new GridLayout(1, 5));

firstItemButton = new JButton(new ImageIcon(“first.png”));

nextItemButton = new JButton(new ImageIcon(“next.png”));

editItemButton = new JButton(“Edit”);

prevItemButton = new JButton(new ImageIcon(“prev.png”));

lastItemButton = new JButton(new ImageIcon(“last.png”));

buttonPanel.add(firstItemButton);

buttonPanel.add(prevItemButton);

buttonPanel.add(editItemButton);

buttonPanel.add(nextItemButton);

buttonPanel.add(lastItemButton);

JPanel bottomPanel = new JPanel();

bottomPanel.add(buttonPanel);

add(bottomPanel, BorderLayout.SOUTH);

menuBar = new JMenuBar();

setJMenuBar(menuBar);

/* Set up your menus and menu items here */

displayDetails(currentItem);

// Because each pair of corresponding buttons and menu items have the same functionality, instead

// of repeating the same code in two locations, we can define an ActionListener object that both

// components will share by having it added as their action listener.

first = new ActionListener() {

public void actionPerformed(ActionEvent e) {

if (editItemButton.getText().equals(“Save”) ) {

// Here we make sure that any updated values are saved to the record before

// we display the next record.

// This behaviour is performed by next, prev and edit, so we move it into a

// separate method so as to avoid unnecessary repetition of code.

saveOpenValues();

}

currentItem = 0;

displayDetails(currentItem);

}

};

next = new ActionListener() {

public void actionPerformed(ActionEvent e) {

// No next if at end of list

if (currentItem != (houseList.size() – 1)) {

if (editItemButton.getText().equals(“Save”) ) {

// Here we make sure that any updated values are saved to the record before

// we display the next record.

// This behaviour is performed by next, prev and edit, so we move it into a

// separate method so as to avoid unnecessary repetition of code.

saveOpenValues();

}

currentItem++;

displayDetails(currentItem);

}

}

};

prev = new ActionListener() {

public void actionPerformed(ActionEvent e) {

// No previous if at beginning of list

if (currentItem != 0) {

if (editItemButton.getText().equals(“Save”) ) {

saveOpenValues();

}

currentItem–;

displayDetails(currentItem);

}

}

};

last = new ActionListener() {

public void actionPerformed(ActionEvent e) {

if (editItemButton.getText().equals(“Save”) ) {

// Here we make sure that any updated values are saved to the record before

// we display the next record.

// This behaviour is performed by next, prev and edit, so we move it into a

// separate method so as to avoid unnecessary repetition of code.

saveOpenValues();

}

currentItem = houseList.size() – 1;                                                displayDetails(currentItem);

}

};

edit = new ActionListener() {

public void actionPerformed(ActionEvent e) {

if (e.getActionCommand() == “Edit”) {

// Allow data to be edited

editItemButton.setText(“Save”);

priceTextField.setEditable(true);

}

else if (e.getActionCommand() == “Save”) {

saveOpenValues();

}

}

};

firstItemButton.addActionListener(first);

nextItemButton.addActionListener(next);

prevItemButton.addActionListener(prev);

lastItemButton.addActionListener(last);

editItemButton.addActionListener(edit);

}

private void saveOpenValues() {

// Save data and revert to other state.

// Update appearance of button.

editItemButton.setText(“Edit”);

// Try to save items to record.

try {

double oldPrice = houseList.get(currentItem).getPrice();

double newPrice = Double.parseDouble(priceTextField.getText());

double change = newPrice – oldPrice;

houseList.get(currentItem).setPrice(newPrice);

houseList.get(currentItem).setChange(change);

NumberFormat nf = NumberFormat.getCurrencyInstance();

priceTextField.setText(nf.format(newPrice));

changeTextField.setText(nf.format(change));

if (change > 0.0)

changeTextField.setForeground(Color.GREEN);

else if (change < 0.0)

changeTextField.setForeground(Color.RED);

else

changeTextField.setForeground(Color.BLACK);

}

catch (NumberFormatException ex) {

JOptionPane.showMessageDialog(null, “Not a valid value for price”);

// Reset contents of text field.

priceTextField.setText(houseList.get(currentItem).getPrice() + “”);

}

// Disable text fields.

priceTextField.setEditable(false);

// Display message.

JOptionPane.showMessageDialog(this, “Record updated”);

}

public void displayDetails(int currentItem) {

houseImageLabel.setIcon(new ImageIcon(houseList.get(currentItem).getImageLocation()));

idTextField.setText(houseList.get(currentItem).getId() + “”);

streetTextField.setText(houseList.get(currentItem).getStreet());

cityTextField.setText(houseList.get(currentItem).getCity());

bedroomsTextField.setText(houseList.get(currentItem).getBedrooms() + “”);

bathroomsTextField.setText(houseList.get(currentItem).getBathrooms() + “”);

NumberFormat nf = NumberFormat.getCurrencyInstance();

priceTextField.setText(nf.format(houseList.get(currentItem).getPrice()));

double change = houseList.get(currentItem).getChange();

changeTextField.setText(nf.format(change));

if (change > 0.0)

changeTextField.setForeground(Color.GREEN);

else if (change < 0.0)

changeTextField.setForeground(Color.RED);

else

changeTextField.setForeground(Color.BLACK);

contactNoTextField.setText(houseList.get(currentItem).getContactNo());

}

public static void main(String[] args) {

HouseApplication ha = new HouseApplication();

ha.pack();

ha.setSize(400, 550);

ha.setVisible(true);

}

} 

HouseSummaryDialog.java 

package CA2;

import java.text.NumberFormat;

import java.util.ArrayList;

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class HouseSummaryDialog extends JFrame {

/* Code goes here */

} 

Solution 

CreateHouseDialog.java 

package CA2;

import java.awt.BorderLayout;

import java.awt.FlowLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.ArrayList;

import java.awt.*;

import javax.swing.JButton;

import javax.swing.JDialog;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JTextField;

import javax.swing.border.LineBorder;

import javax.swing.event.DocumentEvent;

import javax.swing.event.DocumentListener;

import net.miginfocom.swing.MigLayout;

public class CreateHouseDialog extends JDialog {

public String PhotoFileName;

public String AddressLine1;

public String AddressLine2;

public String NoBedrooms;

public String NoBathRooms;

public String Price;

public String ContactNo;

private JButton btnAdd;

private JButton btnCancel;

private JTextField photoF;

private JTextField AddL1;

private JTextField AddL2;

private JTextField NoBed;

private JTextField NoBat;

private JTextField Pr;

private JTextField Con;

private JButton add;

private JButton cancel;

private boolean succeeded;

/* Code goes here */

public boolean isSucceeded(){

return succeeded;

}

public boolean checkEmpty(){

if (!photoF.getText().isEmpty() && !AddL1.getText().isEmpty() && !AddL2.getText().isEmpty() && !NoBed.getText().isEmpty() && !NoBat.getText().isEmpty() && !Pr.getText().isEmpty() && !Con.getText().isEmpty()){

//System.out.println(“heree”);

try

{

Double.parseDouble(Pr.getText());

}

catch(NumberFormatException e)

{

return false;

//not a double

}

if(!isInteger(NoBed.getText()) && !isInteger(NoBat.getText()) ){

return false;

}

return true;

}

return false;

}

public static boolean isInteger(String s) {

return isInteger(s,10);

}

public static boolean isInteger(String s, int radix) {

if(s.isEmpty()) return false;

for(int i = 0; i < s.length(); i++) {

if(i == 0 && s.charAt(i) == ‘-‘) {

if(s.length() == 1) return false;

else continue;

}

if(Character.digit(s.charAt(i),radix) < 0) return false;

}

return true;

}

public CreateHouseDialog(Frame parent){

super(parent,”Add House Details”,true);

JPanel panel = new JPanel(new GridBagLayout());

GridBagConstraints cs = new GridBagConstraints();

cs.fill = GridBagConstraints.HORIZONTAL;

JLabel lbPhoto = new JLabel(“Photo FIle Name : “);

JLabel lbAd1 = new JLabel(“Address Line 1 : “);

JLabel lbAd2 = new JLabel(“Address Line 2 : “);

JLabel lbBed = new JLabel(“No of Bedrooms : “);

JLabel lbBat = new JLabel(“No of Bathrooms : “);

JLabel lbPrice = new JLabel(“Price : “);

JLabel lbcont = new JLabel(“Contact No : “);

//1

cs.gridx =0;

cs.gridy=0;

cs.gridwidth =1;

panel.add(lbPhoto,cs);

photoF = new JTextField(20);

cs.gridx =1;

cs.gridy=0;

cs.gridwidth =2;

panel.add(photoF,cs);

//2

cs.gridx =0;

cs.gridy=1;

cs.gridwidth =1;

panel.add(lbAd1,cs);

AddL1 = new JTextField(20);

cs.gridx =1;

cs.gridy=1;

cs.gridwidth =2;

panel.add(AddL1,cs);

//3

cs.gridx =0;

cs.gridy=2;

cs.gridwidth =1;

panel.add(lbAd2,cs);

AddL2 = new JTextField(20);

cs.gridx =1;

cs.gridy=2;

cs.gridwidth =2;

panel.add(AddL2,cs);

//4

cs.gridx =0;

cs.gridy=3;

cs.gridwidth =1;

panel.add(lbBed,cs);

NoBed = new JTextField(20);

cs.gridx =1;

cs.gridy=3;

cs.gridwidth =2;

panel.add(NoBed,cs);

//5

cs.gridx =0;

cs.gridy=4;

cs.gridwidth =1;

panel.add(lbBat,cs);

NoBat = new JTextField(20);

cs.gridx =1;

cs.gridy=4;

cs.gridwidth =2;

panel.add(NoBat,cs);

//6

cs.gridx =0;

cs.gridy=5;

cs.gridwidth =1;

panel.add(lbPrice,cs);

Pr = new JTextField(20);

cs.gridx =1;

cs.gridy=5;

cs.gridwidth =2;

panel.add(Pr,cs);

//7

cs.gridx =0;

cs.gridy=6;

cs.gridwidth =1;

panel.add(lbcont,cs);

Con = new JTextField(20);

cs.gridx =1;

cs.gridy=6;

cs.gridwidth =2;

panel.add(Con,cs);

btnAdd = new JButton(“Add”);

btnAdd.addActionListener(new ActionListener(){

@Override

public void actionPerformed(ActionEvent e) {

if(checkEmpty()){

PhotoFileName = photoF.getText();

AddressLine1 = AddL1.getText();

AddressLine2 = AddL2.getText();

NoBedrooms = NoBed.getText();

NoBathRooms = NoBat.getText();

Price = Pr.getText();

ContactNo = Con.getText();

succeeded = true;

dispose();

}

else{

JOptionPane.showMessageDialog(CreateHouseDialog.this,

“Please Fill All Fields with valid info”);

succeeded = false;

}

//throw new UnsupportedOperationException(“Not supported yet.”); //To change body of generated methods, choose Tools | Templates.

}

});

btnCancel = new JButton(“Cancel”);

btnCancel.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

dispose();

}

});

JPanel bp = new JPanel();

bp.add(btnAdd);

bp.add(btnCancel);

panel.setBorder(new LineBorder(Color.GRAY));

getContentPane().add(panel,BorderLayout.CENTER);

getContentPane().add(bp,BorderLayout.PAGE_END);

pack();

setResizable(false);

}

} 

deleteConfirm.java 

/*

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

package CA2;

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Frame;

import java.awt.GridBagConstraints;

import java.awt.GridBagLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JDialog;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.border.LineBorder;

public class deleteConfirm extends JDialog {

boolean delete;

public deleteConfirm(Frame parent){

super(parent,”Warning”,true);

JPanel panel = new JPanel();

JLabel del = new JLabel(“This will delete the record. Are you sure you want to continue ?”);

panel.add(del);

JButton btnOk = new JButton(“Ok”);

btnOk.addActionListener(new ActionListener(){

@Override

public void actionPerformed(ActionEvent e) {

delete = true;

dispose();

//throw new UnsupportedOperationException(“Not supported yet.”); //To change body of generated methods, choose Tools | Templates.

}

});

JButton btnCancel = new JButton(“Cancel”);

btnCancel.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

delete = false;

dispose();

}

});

JPanel bp = new JPanel();

bp.add(btnOk);

bp.add(btnCancel);

getContentPane().add(panel,BorderLayout.CENTER);

getContentPane().add(bp,BorderLayout.PAGE_END);

pack();

setResizable(false);

}

} 

House.java 

package CA2;

public class House {

private int id;

private String imageLocation;

private String street;

private String city;

private int bedrooms;

private int bathrooms;

private double price;

private double change;

private String contactNo;

public static int count = 1;

public House(String street, String city, int bedrooms, int bathrooms, double price, String imageLocation, String contactNo) {

this.id = ++count;

this.street = street;

this.city = city;

this.bedrooms = bedrooms;

this.bathrooms = bathrooms;

this.price = price;

this.change = 0.0;

this.imageLocation = imageLocation;

this.contactNo = contactNo;

}

public int getId() {

return id;

}

public String getStreet() {

return street;

}

public String getCity() {

return city;

}

public int getBedrooms() {

return bedrooms;

}

public int getBathrooms() {

return bathrooms;

}

public double getPrice() {

return price;

}

public double getChange() {

return change;

}

public String getImageLocation() {

return imageLocation;

}

public String getContactNo() {

return contactNo;

}

public void setPrice(double price) {

this.price = price;

}

public void setChange(double change) {

this.change = change;

}

} 

 HouseApplication.java

 package CA2;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import net.miginfocom.swing.MigLayout;

import java.text.NumberFormat;

import java.util.*;

public class HouseApplication extends JFrame {

ArrayList<House> houseList = new ArrayList<House>();

JMenuBar menuBar;

JMenu modifyMenu, reportMenu, closeMenu;

JMenuItem createItem, deleteItem, searchItem, summaryItem, closeApp;

JButton firstItemButton, nextItemButton, prevItemButton, lastItemButton, editItemButton;

JLabel houseImageLabel, idLabel, streetLabel, cityLabel, bedroomsLabel, bathroomsLabel, priceLabel, changeLabel, contactNoLabel;

JTextField idTextField, streetTextField, cityTextField, bedroomsTextField, bathroomsTextField, priceTextField, changeTextField, contactNoTextField;

String[][] records = {{“113 The Maltings”, “Dublin 8”, “2”, “1”, “155500.00”, “House1.jpg”, “(087) 9011135”},

{“78 Newington Lodge”, “Dublin 14”, “3”, “2”, “310000.00”, “House2.jpg”, “(087) 9010580”},

{“62 Bohernabreena Road”, “Dublin 24”, “3”, “1”, “220000.00”, “House3.jpg”, “(087) 6023159”},

{“18 Castledevitt Park”, “Dublin 15”, “3”, “3”, “325000.00”, “House4.jpg”, “(087) 9010580”},

{“40 Dunsawny Road”, “Swords”, “3”, “19”, “245000.00”, “House5.jpg”, “(087) 9011135”}

};

int currentItem;

ActionListener first, next, prev, last, edit;

public HouseApplication() {

super(“Estate Agent Application”);

for (int i = 0; i < records.length; i++) {

houseList.add(new House(records[i][0], records[i][1], Integer.parseInt(records[i][2]),

Integer.parseInt(records[i][3]), Double.parseDouble(records[i][4]), records[i][5], records[i][6]));

}

currentItem = 0;

initComponents();

}

public void initComponents() {

setLayout(new BorderLayout());

JPanel displayPanel = new JPanel(new MigLayout());

// Ensures that image is centred in label

houseImageLabel = new JLabel(new ImageIcon(), SwingConstants.CENTER);

displayPanel.add(houseImageLabel, “push, grow, span 2, wrap”);

idLabel = new JLabel(“House ID: “);

idTextField = new JTextField(3);

idTextField.setEditable(false);

displayPanel.add(idLabel, “growx, pushx”);

displayPanel.add(idTextField, “growx, pushx, wrap”);

streetLabel = new JLabel(“Address Line 1: “);

streetTextField = new JTextField(15);

streetTextField.setEditable(false);

displayPanel.add(streetLabel, “growx, pushx”);

displayPanel.add(streetTextField, “growx, pushx, wrap”);

cityLabel = new JLabel(“Address Line 2: “);

cityTextField = new JTextField(15);

cityTextField.setEditable(false);

displayPanel.add(cityLabel, “growx, pushx”);

displayPanel.add(cityTextField, “growx, pushx, wrap”);

bedroomsLabel = new JLabel(“Number of bedrooms: “);

bedroomsTextField = new JTextField(3);

bedroomsTextField.setEditable(false);

displayPanel.add(bedroomsLabel, “growx, pushx”);

displayPanel.add(bedroomsTextField, “growx, pushx, wrap”);

bathroomsLabel = new JLabel(“Number of bathrooms: “);

bathroomsTextField = new JTextField(3);

bathroomsTextField.setEditable(false);

displayPanel.add(bathroomsLabel, “growx, pushx”);

displayPanel.add(bathroomsTextField, “growx, pushx, wrap”);

priceLabel = new JLabel(“Price: “);

priceTextField = new JTextField(10);

priceTextField.setEditable(false);

displayPanel.add(priceLabel, “growx, pushx”);

displayPanel.add(priceTextField, “growx, pushx, wrap”);

changeLabel = new JLabel(“Price change: “);

changeTextField = new JTextField(10);

changeTextField.setEditable(false);

displayPanel.add(changeLabel, “growx, pushx”);

displayPanel.add(changeTextField, “growx, pushx, wrap”);

contactNoLabel = new JLabel(“Contact number: “);

contactNoTextField = new JTextField(15);

contactNoTextField.setEditable(false);

displayPanel.add(contactNoLabel, “growx, pushx”);

displayPanel.add(contactNoTextField, “growx, pushx, wrap”);

add(displayPanel, BorderLayout.CENTER);

JPanel buttonPanel = new JPanel(new GridLayout(1, 5));

firstItemButton = new JButton(new ImageIcon(“src/images/first.png”));

nextItemButton = new JButton(new ImageIcon(“src/images/next.png”));

editItemButton = new JButton(“Edit”);

prevItemButton = new JButton(new ImageIcon(“src/images/prev.png”));

lastItemButton = new JButton(new ImageIcon(“src/images/last.png”));

buttonPanel.add(firstItemButton);

buttonPanel.add(prevItemButton);

buttonPanel.add(editItemButton);

buttonPanel.add(nextItemButton);

buttonPanel.add(lastItemButton);

JPanel bottomPanel = new JPanel();

bottomPanel.add(buttonPanel);

add(bottomPanel, BorderLayout.SOUTH);

menuBar = new JMenuBar();

setJMenuBar(menuBar);

/* Set up your menus and menu items here */

JMenu modifyMenu = new JMenu(“Modify”);

JMenu reportMenu = new JMenu(“Report”);

JMenu closeMenu = new JMenu(“Close”);

closeMenu.addMouseListener(new MouseListener() {

@Override

public void mouseClicked(MouseEvent e) {

System.exit(0);

throw new UnsupportedOperationException(“Not supported yet.”); //To change body of generated methods, choose Tools | Templates.

}

@Override

public void mousePressed(MouseEvent e) {

//throw new UnsupportedOperationException(“Not supported yet.”); //To change body of generated methods, choose Tools | Templates.

}

@Override

public void mouseReleased(MouseEvent e) {

//throw new UnsupportedOperationException(“Not supported yet.”); //To change body of generated methods, choose Tools | Templates.

}

@Override

public void mouseEntered(MouseEvent e) {

//throw new UnsupportedOperationException(“Not supported yet.”); //To change body of generated methods, choose Tools | Templates.

}

@Override

public void mouseExited(MouseEvent e) {

//throw new UnsupportedOperationException(“Not supported yet.”); //To change body of generated methods, choose Tools | Templates.

}

});

JMenuItem create = new JMenuItem(“Create”);

JMenuItem delete = new JMenuItem(“Delete”);

JMenuItem search = new JMenuItem(“Search Records”);

JMenuItem summary = new JMenuItem(“Summary”);

String pass;

JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(displayPanel);

//action listeners for menu items

create.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

passwordDialog pa = new passwordDialog(topFrame);

pa.setVisible(true);

if (pa.isSucceeded()) {

JOptionPane.showMessageDialog(displayPanel,

“Password Authenticated”);

CreateHouseDialog ch = new CreateHouseDialog(topFrame);

ch.setVisible(true);

if(ch.isSucceeded()){

houseList.add(new House(ch.AddressLine1,ch.AddressLine2,Integer.parseInt(ch.NoBedrooms),Integer.parseInt(ch.NoBathRooms),Double.parseDouble(ch.Price),ch.PhotoFileName,ch.ContactNo));

}

}

//throw new UnsupportedOperationException(“Not supported yet.”); //To change body of generated methods, choose Tools | Templates.

}

});

delete.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

passwordDialog pa = new passwordDialog(topFrame);

pa.setVisible(true);

if (pa.isSucceeded()) {

deleteConfirm del = new deleteConfirm(topFrame);

del.setVisible(true);

if(del.delete){

houseList.remove(currentItem);

if(currentItem<houseList.size()-1){

currentItem++;

}

else if(currentItem>0){

currentItem–;

}

displayDetails(currentItem);

}

}

//throw new UnsupportedOperationException(“Not supported yet.”); //To change body of generated methods, choose Tools | Templates.

}

});

search.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

InputDialog inpD = new InputDialog(topFrame,houseList.size());

inpD.setVisible(true);

//System.out.println(“here”);

String x= (String)inpD.c.getSelectedItem();

//System.out.println(“here211”);

int sel =Integer.parseInt(x);

int ind=0;

while(ind<houseList.size()){

if(houseList.get(ind).getId()==sel){

currentItem = ind;

displayDetails(currentItem);

break;

}

ind++;

}

//throw new UnsupportedOperationException(“Not supported yet.”); //To change body of generated methods, choose Tools | Templates.

}

});

summary.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

HouseSummaryDialog hd = new HouseSummaryDialog(topFrame,houseList);

hd.setVisible(true);

//throw new UnsupportedOperationException(“Not supported yet.”); //To change body of generated methods, choose Tools | Templates.

}

});

////

modifyMenu.add(create);

modifyMenu.add(delete);

reportMenu.add(search);

reportMenu.add(summary);

menuBar.add(modifyMenu);

menuBar.add(reportMenu);

menuBar.add(closeMenu);

displayDetails(currentItem);

// Because each pair of corresponding buttons and menu items have the same functionality, instead

// of repeating the same code in two locations, we can define an ActionListener object that both

// components will share by having it added as their action listener.

first = new ActionListener() {

public void actionPerformed(ActionEvent e) {

if (editItemButton.getText().equals(“Save”)) {

// Here we make sure that any updated values are saved to the record before

// we display the next record.

// This behaviour is performed by next, prev and edit, so we move it into a

// separate method so as to avoid unnecessary repetition of code.

saveOpenValues();

}

currentItem = 0;

displayDetails(currentItem);

}

};

next = new ActionListener() {

public void actionPerformed(ActionEvent e) {

// No next if at end of list

if (currentItem != (houseList.size() – 1)) {

if (editItemButton.getText().equals(“Save”)) {

// Here we make sure that any updated values are saved to the record before

// we display the next record.

// This behaviour is performed by next, prev and edit, so we move it into a

// separate method so as to avoid unnecessary repetition of code.

saveOpenValues();

}

currentItem++;

displayDetails(currentItem);

}

}

};

prev = new ActionListener() {

public void actionPerformed(ActionEvent e) {

// No previous if at beginning of list

if (currentItem != 0) {

if (editItemButton.getText().equals(“Save”)) {

saveOpenValues();

}

currentItem–;

displayDetails(currentItem);

}

}

};

last = new ActionListener() {

public void actionPerformed(ActionEvent e) {

if (editItemButton.getText().equals(“Save”)) {

// Here we make sure that any updated values are saved to the record before

// we display the next record.

// This behaviour is performed by next, prev and edit, so we move it into a

// separate method so as to avoid unnecessary repetition of code.

saveOpenValues();

}

currentItem = houseList.size() – 1;

displayDetails(currentItem);

}

};

edit = new ActionListener() {

public void actionPerformed(ActionEvent e) {

if (e.getActionCommand() == “Edit”) {

// Allow data to be edited

editItemButton.setText(“Save”);

priceTextField.setEditable(true);

} else if (e.getActionCommand() == “Save”) {

saveOpenValues();

}

}

};

firstItemButton.addActionListener(first);

nextItemButton.addActionListener(next);

prevItemButton.addActionListener(prev);

lastItemButton.addActionListener(last);

editItemButton.addActionListener(edit);

}

private void saveOpenValues() {

// Save data and revert to other state.

// Update appearance of button.

editItemButton.setText(“Edit”);

// Try to save items to record.

try {

double oldPrice = houseList.get(currentItem).getPrice();

double newPrice = Double.parseDouble(priceTextField.getText());

double change = newPrice – oldPrice;

houseList.get(currentItem).setPrice(newPrice);

houseList.get(currentItem).setChange(change);

NumberFormat nf = NumberFormat.getCurrencyInstance();

priceTextField.setText(nf.format(newPrice));

changeTextField.setText(nf.format(change));

if (change > 0.0) {

changeTextField.setForeground(Color.GREEN);

} else if (change < 0.0) {

changeTextField.setForeground(Color.RED);

} else {

changeTextField.setForeground(Color.BLACK);

}

} catch (NumberFormatException ex) {

JOptionPane.showMessageDialog(null, “Not a valid value for price”);

// Reset contents of text field.

priceTextField.setText(houseList.get(currentItem).getPrice() + “”);

}

// Disable text fields.

priceTextField.setEditable(false);

// Display message.

JOptionPane.showMessageDialog(this, “Record updated”);

}

public void displayDetails(int currentItem) {

houseImageLabel.setIcon(new ImageIcon(“src/images/” + houseList.get(currentItem).getImageLocation()));

idTextField.setText(houseList.get(currentItem).getId() + “”);

streetTextField.setText(houseList.get(currentItem).getStreet());

cityTextField.setText(houseList.get(currentItem).getCity());

bedroomsTextField.setText(houseList.get(currentItem).getBedrooms() + “”);

bathroomsTextField.setText(houseList.get(currentItem).getBathrooms() + “”);

NumberFormat nf = NumberFormat.getCurrencyInstance();

priceTextField.setText(nf.format(houseList.get(currentItem).getPrice()));

double change = houseList.get(currentItem).getChange();

changeTextField.setText(nf.format(change));

if (change > 0.0) {

changeTextField.setForeground(Color.GREEN);

} else if (change < 0.0) {

changeTextField.setForeground(Color.RED);

} else {

changeTextField.setForeground(Color.BLACK);

}

contactNoTextField.setText(houseList.get(currentItem).getContactNo());

}

public static void main(String[] args) {

HouseApplication ha = new HouseApplication();

ha.pack();

ha.setSize(400, 550);

ha.setVisible(true);

ha.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

} 

HouseSummaryDialog.java 

package CA2;

import java.text.NumberFormat;

import java.util.ArrayList;

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.border.LineBorder;

public class HouseSummaryDialog extends JDialog {

/* Code goes here */

public HouseSummaryDialog(Frame parent,ArrayList<House> hl){

super(parent,”Summary”,true);

JPanel panel = new JPanel(new GridBagLayout());

GridBagConstraints cs = new GridBagConstraints();

cs.fill = GridBagConstraints.HORIZONTAL;

JLabel id = new JLabel(“ID”);

JLabel AddressLine1 = new JLabel(“Address Line 1”);

JLabel AddressLine2 = new JLabel(“Address Line 2”);

JLabel NoBed = new JLabel(“Number of Bedrooms”);

JLabel NoBat = new JLabel(“Number of Bathrooms”);

JLabel Price = new JLabel(“Price”);

JLabel Con = new JLabel(“Contact Number”);

cs.gridx =0;

cs.gridy=0;

cs.gridwidth =1;

panel.add(id,cs);

cs.gridx =1;

panel.add(AddressLine1,cs);

cs.gridx =2;

panel.add(AddressLine2,cs);

cs.gridx =3;

panel.add(NoBed,cs);

cs.gridx =4;

panel.add(NoBat,cs);

cs.gridx =5;

panel.add(Price,cs);

cs.gridx =6;

panel.add(Con,cs);

double TotPrice=0;

for(int i=1;i<=hl.size();i++){

House h = hl.get(i-1);

TotPrice+=h.getPrice();

cs.gridx =0;

cs.gridy=i;

cs.gridwidth =1;

panel.add(new JLabel(Integer.toString(i)),cs);

cs.gridx =1;

panel.add(new JLabel(h.getStreet()),cs);

cs.gridx =2;

panel.add(new JLabel(h.getCity()),cs);

cs.gridx =3;

panel.add(new JLabel(Integer.toString(h.getBedrooms())),cs);

cs.gridx =4;

panel.add(new JLabel(Integer.toString(h.getBathrooms())),cs);;

cs.gridx =5;

panel.add(new JLabel(Double.toString(h.getPrice())),cs);

cs.gridx =6;

panel.add(new JLabel(h.getContactNo()),cs);

getContentPane().add(panel,BorderLayout.CENTER);

pack();

setResizable(false);

}

cs.gridx =0;

cs.gridy=hl.size()+1;

cs.gridwidth =2;

panel.add(new JLabel(“Average Price : “),cs);

cs.gridx =3;

double AvgPrice = TotPrice / hl.size();

panel.add(new JLabel(Double.toString(AvgPrice)),cs);

panel.setBorder(new LineBorder(Color.GRAY));

getContentPane().add(panel,BorderLayout.CENTER);

pack();

setResizable(false);

}

} 

InputDialog.java 

/*

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

package CA2;

import java.awt.BorderLayout;

import java.awt.Frame;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JComboBox;

import javax.swing.JDialog;

import javax.swing.JLabel;

import javax.swing.JPanel;

/**

*

* @author Mayora13

*/

public class InputDialog extends JDialog {

public JComboBox c;

public boolean searched;

public InputDialog(Frame parent,int size){

super(parent,”Search Records”,true);

JPanel panel = new JPanel();

c = new JComboBox();

for(int i=1; i<=size;i++){

c.addItem(Integer.toString(i));

}

JLabel ser = new JLabel(“Choose House Id”);

panel.add(ser);

panel.add(c);

JButton btnOk = new JButton(“Ok”);

btnOk.addActionListener(new ActionListener(){

@Override

public void actionPerformed(ActionEvent e) {

searched = true;

dispose();

//throw new UnsupportedOperationException(“Not supported yet.”); //To change body of generated methods, choose Tools | Templates.

}

});

JButton btnCancel = new JButton(“Cancel”);

btnCancel.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

searched = false;

dispose();

}

});

JPanel bp = new JPanel();

bp.add(btnOk);

bp.add(btnCancel);

getContentPane().add(panel,BorderLayout.CENTER);

getContentPane().add(bp,BorderLayout.PAGE_END);

pack();

setResizable(false);

}

} 

passwordDialog.java 

/*

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

package CA2;

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.FlowLayout;

import java.awt.Frame;

import java.awt.GridBagConstraints;

import java.awt.GridBagLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.ArrayList;

import javax.swing.border.*;

import javax.swing.JButton;

import javax.swing.JDialog;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JPasswordField;

import javax.swing.JTextField;

import javax.swing.border.LineBorder;

import net.miginfocom.swing.MigLayout;

public class passwordDialog extends JDialog {

private JPasswordField pfPassword;

private String password = “3175”;

private JLabel lbPassword;

JButton btnOk;

JButton btnCancel;

private boolean succeeded;

public boolean AuthenticatePass(String pass){

if(pass.equals(password)){

return true;

}

return false;

}

public String getPassword(){

return new String(pfPassword.getPassword());

}

public boolean isSucceeded() {

return succeeded;

}

public passwordDialog(Frame parent){

super(parent,”Authenticate”,true);

JPanel panel = new JPanel(new GridBagLayout());

GridBagConstraints cs = new GridBagConstraints();

cs.fill = GridBagConstraints.HORIZONTAL;

lbPassword = new JLabel(“Password : “);

cs.gridx =0;

cs.gridy=0;

cs.gridwidth =1;

panel.add(lbPassword,cs);

pfPassword = new JPasswordField(20);

cs.gridx =1;

cs.gridy = 0;

cs.gridwidth=2;

panel.add(pfPassword,cs);

panel.setBorder(new LineBorder(Color.GRAY));

btnOk = new JButton(“Ok”);

btnOk.addActionListener(new ActionListener(){

@Override

public void actionPerformed(ActionEvent e) {

if (AuthenticatePass(getPassword())){

succeeded = true;

dispose();

}

else{

JOptionPane.showMessageDialog(passwordDialog.this,

“Invalid Password”);

succeeded = false;

pfPassword.setText(“”);

}

//throw new UnsupportedOperationException(“Not supported yet.”); //To change body of generated methods, choose Tools | Templates.

}

});

btnCancel = new JButton(“Cancel”);

btnCancel.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

dispose();

}

});

JPanel bp = new JPanel();

bp.add(btnOk);

bp.add(btnCancel);

getContentPane().add(panel,BorderLayout.CENTER);

getContentPane().add(bp,BorderLayout.PAGE_END);

pack();

setResizable(false);

}

}