Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Description of the Problem Write a GUI program that lets user maintain records i

ID: 3582333 • Letter: D

Question

Description of the Problem Write a GUI program that lets user maintain records in a file or database that contains the data for Book objects. Specifications • When the program is started, the data are automatically loaded from a file or database. The first record is initially displayed. The Update button is disabled until new text is entered in any of the text fields, as shown below: • To navigate through the book records, the user can click on the one of the buttons in the bottom row: the First button displays the first record in the file or database; the Prev button displays the previous record; the Next button displays the next record; and the Last button displays the last record. Whenever a new record is displayed, the Update button is disabled. • To modify the data for a book, user makes a change to the title or price fields. At that point, the Update button is enabled and the Add, Delete, and navigation buttons are disabled. Then, to save the changes to the file or database, the user clicks on the Update button. Hint: to enable or disable buttons, you can write a helper function, like this: private void enableButtons(boolean flag1) { boolean flag2 = false; if (!flag1) flag2 = true; updateButton.setEnabled(flag2); addButton.setEnabled(flag1); deleteButton.setEnabled(flag1); firstButton.setEnabled(flag1); nextButton.setEnabled(flag1); prevButton.setEnabled(flag1); lastButton.setEnabled(flag1); } • To add a record to the file or database, the user clicks on the Add button. This clears the text fields, enables the Update button, and disables the Add, Delete, and navigation buttons. Then, the user can enter the code, title, and price (with or without dollar sign) for a new book and click on the Update button to save the new record to the file or database. This record will be added at the end of the file or database. • To delete a record, the user navigates to that record and clicks on the Delete button. After it deletes the record from the file or database, the program displays the data for the next record (or the new last record if the deleted record was the last record). • To cancel any add or update operation, the user can press Esc key when the focus is in one of the text fields Hint: implement KeyListener: public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_ESCAPE) { // codeField.requestFocus(); // performBookDisplay(); // enableButtons(true); } • To exit from the program at any time, the user can click on the Exit button. This will cancel any change, addition, or deletion that’s in progress. • Design your application based on Object-oriented programming principle. Your GUIinterface should be separated from the operational logic. Changing the operational logic will not affect your GUI interface. Here is a sample design in UML: 1 1 1 1 1 1 1 1 1 BookFrame +windowClosing() BookPanel +actionPerformed() -enableButtons() +keyPressed() +keyReleased() +keyTyped() +insertUpdate() +removeUpdate() +changeUpdate() ActionListner DocumentListener KeyListener +loadDB() +saveDB() +moveFirst():Book +movePrevious():Book +moveNext():Book +moveLast():Book +addRecord(Book) +deleteRecord(Book) +findOnCode(String):Book BookDB Book -code:String -title:String -price:double +Book(bookCode:String, bookTitle:String, bookPrice:double) +getCode():String +getTitle():String +getPrice():double Requirements • Your program should follow the coding guideline. • Turn in the following 1. Source code 2. Sample interactions that demonstrate all of the features.

Explanation / Answer

//BookFrame.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.text.*;
import java.sql.*;

public class BookFrame extends JFrame{
public BookFrame(){
setTitle("Book Maintenance");
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
int width = 400, height = 200;
setBounds((d.width - width)/2, (d.height - height)/2, width, height);
setResizable(false);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
BookDB.close();
System.exit(0);
}
});
Container contentPane = getContentPane();
BookPanel panel = new BookPanel();
contentPane.add(panel);
}
public static void main(String[] args){
JFrame frame = new BookFrame();
frame.show();
}
}

class BookPanel extends JPanel implements ActionListener,
DocumentListener, KeyListener{

private JButton addButton, updateButton, deleteButton, exitButton,
firstButton, prevButton, nextButton, lastButton;
private JLabel codeLabel, titleLabel, priceLabel;
private JTextField codeField, titleField, priceField;
public static boolean addFlag = false;
public static NumberFormat currency = NumberFormat.getCurrencyInstance();
Book currentBook = null;

public BookPanel(){

codeLabel = new JLabel("Code: ");
codeField = new JTextField("", 7);
titleLabel = new JLabel("Title: ");
titleField = new JTextField("", 26);
priceLabel = new JLabel("Price: ");
priceField = new JTextField("", 7);

JPanel updatePanel = new JPanel();
addButton = new JButton("Add");
updateButton = new JButton("Update");
deleteButton = new JButton("Delete");
exitButton = new JButton("Exit");
updatePanel.add(addButton);
updatePanel.add(updateButton);
updatePanel.add(deleteButton);
updatePanel.add(exitButton);

JPanel navigationPanel = new JPanel();
firstButton = new JButton("First");
prevButton = new JButton("Prev");
nextButton = new JButton("Next");
lastButton = new JButton("Last");
navigationPanel.add(firstButton);
navigationPanel.add(prevButton);
navigationPanel.add(nextButton);
navigationPanel.add(lastButton);

addButton.addActionListener(this);
updateButton.addActionListener(this);
deleteButton.addActionListener(this);
exitButton.addActionListener(this);
firstButton.addActionListener(this);
prevButton.addActionListener(this);
nextButton.addActionListener(this);
lastButton.addActionListener(this);
codeField.addKeyListener(this);
titleField.addKeyListener(this);
priceField.addKeyListener(this);
codeField.getDocument().addDocumentListener(this);
titleField.getDocument().addDocumentListener(this);
priceField.getDocument().addDocumentListener(this);

setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 100;
c.weighty = 100;
c.ipadx = 5;

c.anchor = GridBagConstraints.EAST;
c = getConstraints(c, 1, 1, 1, 1);
add(codeLabel, c);
c = getConstraints(c, 1, 2, 1, 1);
add(titleLabel, c);
c = getConstraints(c, 1, 3, 1, 1);
add(priceLabel, c);

c.anchor = GridBagConstraints.WEST;
c = getConstraints(c, 2, 1, 3, 1);
add(codeField, c);
c = getConstraints(c, 2, 2, 3, 1);
add(titleField, c);
c = getConstraints(c, 2, 3, 3, 1);
add(priceField, c);

c.anchor = GridBagConstraints.CENTER;
c = getConstraints(c, 1, 4, 4, 1);
add(updatePanel, c);
c = getConstraints(c, 1, 5, 4, 1);
add(navigationPanel, c);

try{
BookDB.connect();
BookDB.open();
currentBook = BookDB.moveFirst();

}
catch (ClassNotFoundException e){
JOptionPane.showMessageDialog(null, e.getMessage());
System.exit(1);
}
catch (SQLException e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
performBookDisplay();
enableButtons(true);
}

private GridBagConstraints getConstraints(GridBagConstraints c,
int x, int y, int width, int height){
c.gridx = x;
c.gridy = y;
c.gridwidth = width;
c.gridheight = height;
return c;
}

private void performBookDisplay(){
codeField.setText(currentBook.getCode());
titleField.setText(currentBook.getTitle());
priceField.setText(currency.format(currentBook.getPrice()));
}

private void enableButtons(boolean flag1){
boolean flag2 = false;
if (flag1 == false)
flag2 = true;
updateButton.setEnabled(flag2);
addButton.setEnabled(flag1);
deleteButton.setEnabled(flag1);
firstButton.setEnabled(flag1);
nextButton.setEnabled(flag1);
prevButton.setEnabled(flag1);
lastButton.setEnabled(flag1);
}

private double parseCurrency(String currencyString){
if (currencyString.charAt(0) == '$')
currencyString = currencyString.substring(1);
return Double.parseDouble(currencyString);
}

public void actionPerformed(ActionEvent e){
try{
Object source = e.getSource();
if (source == exitButton){
BookDB.close();
System.exit(0);
}
else if (source == firstButton){
currentBook = BookDB.moveFirst();
performBookDisplay();
enableButtons(true);
}
else if (source == prevButton){
currentBook = BookDB.movePrevious();
performBookDisplay();
enableButtons(true);
}
else if (source == nextButton){
currentBook = BookDB.moveNext();
performBookDisplay();
enableButtons(true);
}
else if (source == lastButton){
currentBook = BookDB.moveLast();
performBookDisplay();
enableButtons(true);
}
else if (source == addButton){
codeField.requestFocus();
enableButtons(false);
codeField.setText("");
titleField.setText("");
priceField.setText("");
addFlag = true;
}
else if (source == updateButton){
double price = parseCurrency(priceField.getText());
Book book = new Book(codeField.getText(),
titleField.getText(),
price);
if (addFlag == false){
BookDB.updateRecord(book);
currentBook = book;
}
if (addFlag == true){
BookDB.addRecord(book);
currentBook = BookDB.moveFirst();
addFlag = false;
}
currentBook = book;
performBookDisplay();
enableButtons(true);
}
else if(source == deleteButton){
BookDB.deleteRecord(currentBook.getCode());
firstButton.requestFocus();
firstButton.doClick();
performBookDisplay();
enableButtons(true);
}
}
catch (NumberFormatException nfe){
JOptionPane.showMessageDialog(this, nfe.getMessage());
}
catch (SQLException sqle){
JOptionPane.showMessageDialog(this, sqle.getMessage());
}
}

public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_ESCAPE){
performBookDisplay();
enableButtons(true);
codeField.requestFocus();
}
}
public void keyReleased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}

public void insertUpdate(DocumentEvent e){
enableButtons(false);
}
public void removeUpdate(DocumentEvent e){
enableButtons(false);
}
public void changedUpdate(DocumentEvent e){
}

}

==================================================================================

//BookDB.java

import java.sql.*;
import javax.swing.JOptionPane;

public class BookDB{
private static Connection connection;
private static Statement scrollStatement;
private static ResultSet books;

public static void connect() throws ClassNotFoundException, SQLException{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:MurachBooks";
String user = "Admin";
String password = "";
connection = DriverManager.getConnection(url, user, password);
}

public static void open() throws SQLException{
scrollStatement = connection.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String query = "SELECT BookCode, BookTitle, BookPrice "
+ "FROM Books ORDER BY BookCode ASC";
books = scrollStatement.executeQuery(query);
}
public static void close(){
try{
books.close();
scrollStatement.close();
}
catch(SQLException sqle){
System.err.println(sqle.getMessage());
}
}

public static Book moveFirst() throws SQLException{
books.first();
Book firstBook = new Book(books.getString("BookCode"),
books.getString("BookTitle"),
books.getDouble("BookPrice"));
return firstBook;
}

public static Book movePrevious() throws SQLException{
if (books.isFirst() == false)
books.previous();
else
books.first();
Book previousBook = new Book(books.getString(1),
books.getString(2),
books.getDouble(3));
return previousBook;

}
public static Book moveNext() throws SQLException{
if (books.isLast() == false)
books.next();
else
books.last();
Book nextBook = new Book(books.getString(1),
books.getString(2),
books.getDouble(3));
return nextBook;

}

public static Book moveLast() throws SQLException{
books.last();
Book lastBook = new Book(books.getString(1),
books.getString(2),
books.getDouble(3));
return lastBook;
}
public static void addRecord(Book book) throws SQLException{
String query = "INSERT INTO Books (BookCode, BookTitle, BookPrice) " +
"VALUES ('" + book.getCode() + "', " +
"'" + book.getTitle() + "', " +
"'" + book.getPrice() + "')";
Statement statement = connection.createStatement();
statement.executeUpdate(query);
statement.close();
close();
open();
}

public static void updateRecord(Book book) throws SQLException{
String query = "UPDATE Books SET " +
"BookCode = '" + book.getCode() + "', " +
"BookTitle = '" + book.getTitle() + "', " +
"BookPrice = '" + book.getPrice() + "' " +
"WHERE BookCode = '" + book.getCode() + "'";
Statement statement = connection.createStatement();
statement.executeUpdate(query);
statement.close();
}

public static void deleteRecord(String bookCode) throws SQLException{
String query = "DELETE FROM Books " +
"WHERE BookCode = '" + bookCode + "'";
Statement statement = connection.createStatement();
statement.executeUpdate(query);
statement.close();
close();
open();
}

}

==============================================================================

//Book.java

public class Book{
private String code;
private String title;
private double price;

public Book(){
this("", "", 11.95);
}

public Book(String bookCode, String bookTitle, double bookPrice){
code = bookCode;
title = bookTitle;
price = bookPrice;
}

public String getCode(){return code;}
public String getTitle(){return title;}
public double getPrice(){return price;}

public void setCode(String bookCode){code = bookCode;}
public void setTitle(String bookTitle){title = bookTitle;}
public void setPrice(double bookPrice){price = bookPrice;}

public String toString(){
return "Code: " + code + " " +
"Title: " + title + " " +
"Price: " + price + " ";
}

}

============================================================================