introduction Write an applet to handle book orders from a company specialized in
ID: 3680116 • Letter: I
Question
introduction
Write an applet to handle book orders from a company specialized in Java programming textbooks. This program should run with JDK’s appletviewer using the downloaded file BC.html. This program should allow various users:
- to enter orders for a number of customers,
- to decide the shipment status depending on stock availability
- to display all the orders information
In this assignment class Customer stores the customer information. You are given the complete Java code for this class and you should study it before using it in BookCentre.java.
Your Task
Your task is to write a BookCentre class as an applet. On this applet you have to create the following Graphics User Interface:
The Main Screen has on the left hand side 3 buttons presented in a column. These buttons have the labels: Input, Processing, Display. The user will click on these buttons to change the panels displayed in the right hand side of the screen (using the CardDeck layout manager). The following is the description of the right panels (the "cards"). Note that you have flexibility in organizing the layout of each panel, but a small percentage of the assignment mark will be associated with creating nice looking panels.
The Input panel uses labels to prompt the user. It contains a textfield to enter the customer name, and a JList object containing the following Java-related book titles: "Deitel-Java How to Program", "Horstmann-Big Java", "Lewis-Software Solutions", "Staugaard-Java for IS", "Sun-Core Java", "Hamilton-JDBC", "Jackson-Java By Example", "Riley-The Object of Java", "Geary-Graphic Java", "Santry-Advanced Java2", "Bishop-Java Gently", "Wigglesworth-Advanced Java", "Liang-Intro to Java", "Lambert-Java". From that JList object, which should show 10 titles, the user will select 3 books. A Button labeled "Submit" displayed at the bottom of the panel allows the user to enter this input data into an array with maximum 100 Customer objects. Do not forget to erase the content of the textfield when the Submit button is clicked and provide a label which shows how many customers were entered (for instance it should say "customer 5 out of 100").
The Processing panel is used for the shipment of books. At the top this panel has a JComboBox which presents all customer names entered in the database ( Hint: the creation of the JComboBox requires an array of strings as parameter. This array has to be created during the input process). When the user selects a name from the JComboBox, this program will get the corresponding object from the array of objects. The panel will present three labels with the 3 books stored in this object, and next to each book two radio buttons (one for “Can be shipped”, one for “Shipment delayed”). Initially all buttons “Shipment delayed” are checked, but the user will click some “Can be shipped” radio buttons.
Hint: You need a different ButtonGroup object for each book .
for (int j = 0; j < 3; j++) {
radioGroup[j] = new ButtonGroup();
accept[j] = new JRadioButton("Can be shipped ", false);
reject[j] = new JRadioButton("Shipment delayed ", true);
radioGroup[j].add(accept[j]);
radioGroup[j].add(reject[j]);
A "Submit" button at the bottom of this panel will trigger the method setShipment() which will change the content of the Customer objects. The Processing can then be continued with the selection of a new customer name.
The Display panel will present the content of the array of objects using a JTextArea object. The display uses Customer's method toString(). In this assignment the customers are displayed in alphabetic order (you need to sort the array of objects using the Bubble Sort algorithm). The text in the JTextArea is displayed with a Serif style font in Italic and 12-point size.
Please find in the Supporting Files the screenshots of a sample solution after three customers have been entered. Note that these are just provided to you so that you have an idea of what the applet could look like; your solutions do not have to look exactly the same.
Tests
You should enter 3-4 customers into the array of objects and then process a few book shipments. At the end just make sure that the display correctly illustrates the shipment situation and that the listing of customers is in alphabetic order. Please note that the user may switch back and forth between different panels.
_________________________________________________________________________
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BookCentre extends JApplet implements ActionListener, ItemListener {
private CardLayout cardManager;
private JPanel deck;
private JButton controls[];
private String names[] = {"Input", "Processing","Display"};
//card 1
private JTextField T1 = new JTextField();
private JLabel label2 = new JLabel("");
private JButton Button1=new JButton("Submit");
private String Name1[] = { "Deitel-Java How to Program", "Horstmann-Big Java", "Lewis-Software Solutions",
"Staugaard-Java for IS", "Sun-Core Java", "Hamilton-JDBC", "Jackson-Java By Example", "Riley-The Object of Java",
"Geary-Graphic Java", "Santry-Advanced Java2", "Bishop-Java Gently", "Wigglesworth-Advanced Java",
"Liang-Intro to Java", "Lambert-Java"};
private JList List1=new JList(Name1);
//card 2
private JPanel card2 = new JPanel();
private JComboBox custList = new JComboBox();
private JLabel label3 = new JLabel("");
private JButton Button2=new JButton("Submit");
private ButtonGroup radioGroup[]=new ButtonGroup[3];
private JRadioButton accept[]=new JRadioButton[3];
private JRadioButton reject[]=new JRadioButton[3];
private JLabel label4[] = new JLabel[3];
//card 3
private JPanel card3 = new JPanel();
private JTextArea custText = new JTextArea();
private static int INDEX=0;
private static final int MAX=100;
private Customer customer[]=new Customer[MAX];
// set up GUI
public void init(){
Container container = getContentPane();
// create the JPanel with CardLayout
deck = new JPanel();
cardManager = new CardLayout();
deck.setLayout(cardManager);
// add cards to JPanel deck
deck.add(card1Panel(),"c1");
deck.add(card2Panel(),"c2");
deck.add(card3Panel(),"c3");
// create and layout buttons that will control deck
JPanel buttons = new JPanel();
buttons.setLayout(new GridLayout( 3, 1 ));
controls = new JButton[names.length];
for ( int count = 0; count < controls.length; count++) {
controls[count] = new JButton(names[count]);
controls[count].addActionListener(this);
buttons.add(controls[count]);
}
// add JPanel deck and JPanel buttons to the applet
container.add(buttons,BorderLayout.WEST );
container.add(deck,BorderLayout.EAST );
setSize(700,500);
setVisible(true);
}// end constructor
public JPanel card1Panel(){
JLabel label6 = new JLabel("Enter Customer Information", SwingConstants.CENTER);
JLabel label1 = new JLabel("Customer Name:", SwingConstants.LEFT);
JLabel label7 = new JLabel("Choose exactly three books:(use CTRL or SHIFT)", SwingConstants.LEFT);
JPanel card1 = new JPanel();
List1.setVisibleRowCount(10);
List1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(5,1));
topPanel.add(label6);
topPanel.add(label2);
topPanel.add(label1);
topPanel.add(T1);
topPanel.add(label7);
card1.setLayout(new BorderLayout(20,20));
card1.add(topPanel,BorderLayout.NORTH);
card1.add(new JScrollPane(List1),BorderLayout.CENTER);
card1.add(Button1,BorderLayout.SOUTH);
Button1.addActionListener(this);
return card1;
}
public JPanel card2Panel(){
JLabel label2 = new JLabel("Processing", SwingConstants.CENTER);
JPanel subPanel = new JPanel();
subPanel.setLayout(new GridLayout(2,1));
subPanel.add(label2);
subPanel.add(custList);
JPanel subPanel2 = new JPanel();
subPanel2.setLayout(new GridLayout(3,3));
for (int j = 0; j < 3; j++) {
radioGroup[j] = new ButtonGroup();
accept[j] = new JRadioButton("Can be shipped ", false);
reject[j] = new JRadioButton("Shipment delayed ", true);
label4[j] = new JLabel("Book "+(j+1));
radioGroup[j].add(accept[j]);
radioGroup[j].add(reject[j]);
subPanel2.add(accept[j]);
subPanel2.add(reject[j]);
}
JPanel subPanel3 = new JPanel();
subPanel3.setLayout(new GridLayout(1,1));
subPanel3.add(Button2);
card2.setLayout(new BorderLayout(20,20));
card2.add(subPanel,BorderLayout.NORTH);
card2.add(subPanel2,BorderLayout.CENTER);
card2.add(subPanel3,BorderLayout.SOUTH);
Button2.addActionListener(this);
custList.addItemListener(this);
return card2;
}
public JPanel card3Panel(){
JLabel label8 = new JLabel("List of Customers and Order Status...");
JPanel topPanel = new JPanel();
//topPanel.setLayout(new GridLayout(1,1));
topPanel.add(label8);
card3.add(topPanel, BorderLayout.NORTH);
card3.add(custText, BorderLayout.CENTER);
custText.setFont(new Font("Serif",Font.ITALIC,12));
return card3;
}
// handle button events by switching cards
public void actionPerformed(ActionEvent event){
// show input
if ( event.getSource() == controls[0])
cardManager.first(deck);
// show processing
else if (event.getSource() == controls[1]){
custList.removeAllItems();
label3.setText("");
for (int i=0; i custList.addItem(customer[i]);
}cardManager.show(deck,"c2");
// show display
}else if (event.getSource() == controls[ 2 ] ){
custText.setText("");
// Bubble Sort
int i,j;
Customer tmp;
for (i=0;i for(j=0;j if(customer[j+1].getName().compareTo(customer[j].getName())<0){
tmp=customer[j];
customer[j]=customer[j+1];
customer[j+1]=tmp;
}
}
for (i=0; i custText.append(customer[i].toString() + " ");
}cardManager.last(deck);
}else if (event.getSource()==Button1){
String str="";
String cusName=T1.getText().toUpperCase();
boolean go=true;
int listIndex[]=List1.getSelectedIndices();
if(T1.getText().equals("")){
str="Error: Please enter your name.";
go=false;
}else if(listIndex.length!=3){
str="Error: Please select 3 books.";
go=false;
}
if(go){
str=cusName+" : You are the customer #"+(INDEX+1)+" out of 100.";
List1.clearSelection();
T1.setText("");
//new customer here
if (INDEX<=MAX){
String book0 = List1.getModel().getElementAt(listIndex[0]).toString();
String book1 = List1.getModel().getElementAt(listIndex[1]).toString();
String book2 = List1.getModel().getElementAt(listIndex[2]).toString();
customer[INDEX]=new Customer(cusName,book0,book1,book2); INDEX++;
}else{
str=cusName+"Sorry, no more new customers.";
}
}
label2.setText(str);
}else if (event.getSource()==Button2){
try{
Customer custCurr=(Customer)custList.getSelectedItem();
for (int j=0;j<3;j++) {
if(reject[j].isSelected())//check if radio is clicked
custCurr.removeShipment(j);
else
custCurr.setShipment(j);
}
//reset the radio when submitted
for (int j = 0; j < 3; j++) {
reject[j].setSelected(true);
}
}catch(Exception ex){}
}
}
// handle radio button events
public void itemStateChanged(ItemEvent event){
if (event.getStateChange()==ItemEvent.SELECTED){
Customer custCurr=(Customer)custList.getSelectedItem();
for(int i=0;i<3;i++){
label4[i].setText(custCurr.getBook(i));
}
}
}
}// end class BookCentre
_________________________________________________________________________
// UMUC CMSC 350
// Class BST
// Adapted by Ioan from original sources:
// Liang - Introduction to Java Programming, 9th Edition (Code Examples of Chapter 27 Binary Search Trees)
// Source code of the examples available at:
// http://www.cs.armstrong.edu/liang/intro9e/examplesource.html
public class BST> {
protected TreeNode root;
protected int size = 0;
/** Create a default binary tree */
public BST() {
}
/** Create a binary tree from an array of objects */
public BST(E[] objects) {
for (int i = 0; i < objects.length; i++)
insert(objects[i]);
}
/** Returns true if the element is in the tree */
public boolean search(E e) {
TreeNode current = root; // Start from the root
while (current != null) {
if (e.compareTo(current.element) < 0) {
current = current.left;
}
else if (e.compareTo(current.element) > 0) {
current = current.right;
}
else // element matches current.element
return true; // Element is found
}
return false;
}
/** Insert element o into the binary tree
* Return true if the element is inserted successfully */
public boolean insert(E e) {
if (root == null)
root = createNewNode(e); // Create a new root
else {
// Locate the parent node
TreeNode parent = null;
TreeNode current = root;
while (current != null)
if (e.compareTo(current.element) < 0) {
parent = current;
current = current.left;
}
else if (e.compareTo(current.element) > 0) {
parent = current;
current = current.right;
}
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (e.compareTo(parent.element) < 0)
parent.left = createNewNode(e);
else
parent.right = createNewNode(e);
}
size++;
return true; // Element inserted
}
protected TreeNode createNewNode(E e) {
return new TreeNode(e);
}
/** Inorder traversal from the root*/
public void inorder() {
inorder(root);
}
/** Inorder traversal from a subtree */
protected void inorder(TreeNode root) {
if (root == null) return;
inorder(root.left);
System.out.print(root.element + " ");
inorder(root.right);
}
/** Postorder traversal from the root */
public void postorder() {
postorder(root);
}
/** Postorder traversal from a subtree */
protected void postorder(TreeNode root) {
if (root == null) return;
postorder(root.left);
postorder(root.right);
System.out.print(root.element + " ");
}
/** Preorder traversal from the root */
public void preorder() {
preorder(root);
}
/** Preorder traversal from a subtree */
protected void preorder(TreeNode root) {
if (root == null) return;
System.out.print(root.element + " ");
preorder(root.left);
preorder(root.right);
}
/** This inner class is static, because it does not access
any instance members defined in its outer class */
public static class TreeNode> {
protected E element;
protected TreeNode left;
protected TreeNode right;
public TreeNode(E e) {
element = e;
}
}
/** Get the number of nodes in the tree */
public int getSize() {
return size;
}
/** Returns the root of the tree */
public TreeNode getRoot() {
return root;
}
/** Returns a path from the root leading to the specified element */
public java.util.ArrayList> path(E e) {
java.util.ArrayList> list =
new java.util.ArrayList>();
TreeNode current = root; // Start from the root
while (current != null) {
list.add(current); // Add the node to the list
if (e.compareTo(current.element) < 0) {
current = current.left;
}
else if (e.compareTo(current.element) > 0) {
current = current.right;
}
else
break;
}
return list; // Return an array of nodes
}
/** Delete an element from the binary tree.
* Return true if the element is deleted successfully
* Return false if the element is not in the tree */
public boolean delete(E e) {
// Locate the node to be deleted and also locate its parent node
TreeNode parent = null;
TreeNode current = root;
while (current != null) {
if (e.compareTo(current.element) < 0) {
parent = current;
current = current.left;
}
else if (e.compareTo(current.element) > 0) {
parent = current;
current = current.right;
}
else
break; // Element is in the tree pointed at by current
}
if (current == null)
return false; // Element is not in the tree
// Case 1: current has no left children
if (current.left == null) {
// Connect the parent with the right child of the current node
if (parent == null) {
root = current.right;
}
else {
if (e.compareTo(parent.element) < 0)
parent.left = current.right;
else
parent.right = current.right;
}
}
else {
// Case 2: The current node has a left child
// Locate the rightmost node in the left subtree of
// the current node and also its parent
TreeNode parentOfRightMost = current;
TreeNode rightMost = current.left;
while (rightMost.right != null) {
parentOfRightMost = rightMost;
rightMost = rightMost.right; // Keep going to the right
}
// Replace the element in current by the element in rightMost
current.element = rightMost.element;
// Eliminate rightmost node
if (parentOfRightMost.right == rightMost)
parentOfRightMost.right = rightMost.left;
else
// Special case: parentOfRightMost == current
parentOfRightMost.left = rightMost.left;
}
size--;
return true; // Element inserted
}
/** Obtain an iterator. Use inorder. */
public java.util.Iterator iterator() {
return new InorderIterator();
}
// Inner class InorderIterator
private class InorderIterator implements java.util.Iterator {
// Store the elements in a list
private java.util.ArrayList list =
new java.util.ArrayList();
private int current = 0; // Point to the current element in list
public InorderIterator() {
inorder(); // Traverse binary tree and store elements in list
}
/** Inorder traversal from the root*/
private void inorder() {
inorder(root);
}
/** Inorder traversal from a subtree */
private void inorder(TreeNode root) {
if (root == null)return;
inorder(root.left);
list.add(root.element);
inorder(root.right);
}
/** More elements for traversing? */
public boolean hasNext() {
if (current < list.size())
return true;
return false;
}
/** Get the current element and move to the next */
public E next() {
return list.get(current++);
}
/** Remove the current element */
public void remove() {
delete(list.get(current)); // Delete the current element
list.clear(); // Clear the list
inorder(); // Rebuild the list
}
}
/** Remove all elements from the tree */
public void clear() {
root = null;
size = 0;
}
}
_________________________________________________________________________
class Customer {
private String name;
private String book0;
private String book1;
private String book2;
private boolean accept0;
private boolean accept1;
private boolean accept2;
public Customer (String n, String u0, String u1, String u2){
name=n;
book0=u0;
book1=u1;
book2=u2;
accept0=accept1=accept2=false;
}
public void setShipment(int which){
switch(which){
case 0: accept0=true; break;
case 1: accept1=true; break;
case 2: accept2=true; break;
}
}
public void removeShipment(int which){
switch(which){
case 0: accept0=false; break;
case 1: accept1=false; break;
case 2: accept2=false; break;
}
}
public boolean getShipment(int which){
switch(which){
case 0: return accept0;
case 1: return accept1;
case 2: return accept2;
default : return false;
}
}
public String getBook(int which){
switch(which){
case 0: return book0;
case 1: return book1;
case 2: return book2;
default : return "Invalid";
}
}
public String getName(){
return name;
}
public String toString(){
String result = name + " ";
result += book0;
if (accept0) result += " - shipped ";
else result += " - delayed ";
result += book1;
if (accept1) result += " - shipped ";
else result += " - delayed ";
result += book2;
if (accept2) result += " - shipped ";
else result += " - delayed ";
return result;
}
}
Explanation / Answer
I have my own code :
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import java.awt.BorderLayout;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JButton;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
public class AddBookApplet extends JApplet {
JTextField t1, t2, t3, t4, t5, t6;
JTextArea a1, a2, a3, a5, a4, a6, a7;
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b10;
JLabel l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12, l13, l14;
JPanel jp1, jp2, jp3, jp4, jp5, jp6, panel;
//FileReader rd1;
JTextField read1;
//FileWriter wr1;
private JTextField textField_4;
private static ArrayList<JLabel> images = new ArrayList<JLabel>();
String bookname, author, publication, issDate, retDate, custid, image, pdf;
File f, f1;
//Statement statement = null;
//private ResultSet result;
/**
* Create the applet.
*/
public AddBookApplet() {
panel = new JPanel();
panel.setBackground(SystemColor.activeCaptionBorder);
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception de) {
}
l1 = new JLabel("Book Name");
l1.setFont(new Font("Tahoma", Font.PLAIN, 12));
l1.setBounds(10, 24, 100, 14);
panel.add(l1);
t1 = new JTextField();
t1.setBounds(120, 22, 133, 20);
panel.add(t1);
t1.setColumns(10);
l2 = new JLabel("Book Author");
l2.setFont(new Font("Tahoma", Font.PLAIN, 12));
l2.setBounds(10, 64, 100, 14);
panel.add(l2);
t2 = new JTextField();
t2.setColumns(10);
t2.setBounds(120, 62, 133, 20);
panel.add(t2);
l3 = new JLabel("Book Publication");
l3.setFont(new Font("Tahoma", Font.PLAIN, 12));
l3.setBounds(10, 104, 100, 14);
panel.add(l3);
t3 = new JTextField();
t3.setColumns(10);
t3.setBounds(120, 102, 133, 20);
panel.add(t3);
//added
l6 = new JLabel("Cover Image");
l6.setFont(new Font("Tahoma", Font.PLAIN, 12));
l6.setBounds(10, 144, 100, 14);
panel.add(l6);
t6 = new JTextField();
t6.setBounds(120, 142, 133, 20);
t6.setEditable(false);
panel.add(t6);
// ***l7 => Cover Image****
l7 = new JLabel();
l7.setBounds(362, 33, 140, 215);
panel.add(l7);
b4 = new JButton("Browse");
b4.setBounds(262, 142, 89, 25);
panel.add(b4);
l6 = new JLabel("Image Preview:");
l6.setFont(new Font("Tahoma", Font.PLAIN, 12));
l6.setBounds(362, 10, 100, 14);
l6.setVisible(false);
panel.add(l6);
//end add
l4 = new JLabel("PDF File");
l4.setFont(new Font("Tahoma", Font.PLAIN, 12));
l4.setBounds(10, 184, 100, 14);
panel.add(l4);
t4 = new JTextField();
t4.setColumns(10);
t4.setBounds(120, 182, 133, 20);
t4.setEditable(false);
panel.add(t4);
t4.setText("");
b5 = new JButton("Browse");
b5.setBounds(262, 182, 89, 25);
panel.add(b5);
//moved buttons lower
b1 = new JButton("Save");
b1.setBounds(10, 222, 89, 25);
panel.add(b1);
b2 = new JButton("Reset");
b2.setBounds(121, 222, 89, 25);
panel.add(b2);
b3 = new JButton("Cancel");
b3.setBounds(231, 222, 89, 25);
panel.add(b3);
//end changes
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(t1.getText() == null || t1.getText().equals("")){
JOptionPane.showMessageDialog((Component) null,
"Book Must Have a Title",
"Library Management(Pravin Rane)",
JOptionPane.OK_OPTION);
}
else{
try {
bookname = t1.getText();
author = t2.getText();
publication = t3.getText();
issDate = "-";
retDate = "-";
custid = "-";
image = t6.getText();
pdf = t4.getText();
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
//Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://sql3.freemysqlhosting.net:3306/sql322429", "sql322429", "xK5*kT6!");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://dbinstance.cdet1nwidztk.us-west-2.rds.amazonaws.com:3306/ClassCalc", "john", "R17A2FZa");
//Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://gorcruxcom.ipagemysql.com:3306/lmsdatabase", "tyler", "Ambition8143");
PreparedStatement statement = null;
statement = (PreparedStatement) con.prepareStatement("INSERT INTO " +
"LibraryDB(bookname, author, publication, issuedate, rturndate, custid, image, pdf) " +
"VALUES(?, ?, ?, ?, ?, ?, ?, ?)");
statement.setString(1, bookname);
statement.setString(2, author);
statement.setString(3, publication);
statement.setString(4, issDate);
statement.setString(5, retDate);
statement.setString(6, custid);
statement.setString(7, image);
statement.setString(8, pdf);
statement.executeUpdate();
statement.close();
con.close();
/*
images.add(l7);
*/
LibraryApplet library = new LibraryApplet();
library.init();
library.start();
panel.setVisible(false);
setLayout(new BorderLayout(800, 600));
add("Center", library);
}
catch (SQLException e1){
e1.printStackTrace();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
} catch (Exception gr) {
}
}
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
t1.setText("");
t2.setText("");
t3.setText("");
t4.setText("");
t6.setText("");
}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LibraryApplet library = new LibraryApplet();
library.init();
library.start();
panel.setVisible(false);
setLayout(new BorderLayout(800, 600));
add("Center", library);
}
});
//added
// source: http://stackoverflow.com/questions/14142932/gui-with-java-gui-builder-for-uploading-an-image-and-displaying-to-a-panelinsid
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
while(true){
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
f = chooser.getSelectedFile();
if(f != null){
String filename = f.getAbsolutePath();
if(filename.endsWith(".jpg")){
t6.setText(filename);
try {
ImageIcon ii=new ImageIcon(scaleImage(140, 215, ImageIO.read(new File(f.getAbsolutePath()))));
l7.setIcon(ii);
l6.setForeground(Color.BLACK);
l6.setText("Image Preview: ");
l6.setVisible(true);
break;
} catch (Exception ex) {
}
}
else{
l6.setForeground(Color.RED);
l6.setText("Must be .jpg File");
l6.setVisible(true);
}
}
break;
}
}
});
//end add
//Added by Zach. Button to get the chosen file and put its name in the text field.
//this name is used by the pdfviewer to display the file.
b5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(f1 != null){
String filename = f1.getAbsolutePath();
t4.setText(filename);
}
while(true){
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
f1 = chooser.getSelectedFile();
if(f1 != null){
String filename = f1.getAbsolutePath();
if(filename.endsWith(".pdf")){
t4.setText(filename);
l6.setVisible(false);
break;
}
else{
l6.setForeground(Color.RED);
l6.setText("Must be .pdf File");
l6.setVisible(true);
}
}
break;
}
}
});
}
//added
// source: http://stackoverflow.com/questions/14142932/gui-with-java-gui-builder-for-uploading-an-image-and-displaying-to-a-panelinsid
public static BufferedImage scaleImage(int w, int h, BufferedImage img) throws Exception {
BufferedImage bi;
bi = new BufferedImage(w, h, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(img, 0, 0, w, h, null);
g2d.dispose();
return bi;
}
//end add
/*
public static JLabel getImage(int index){
return images.get(index);
}
public static void deleteImage(int index){
images.remove(index);
}
*/
}
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import java.awt.BorderLayout;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JButton;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
public class AddBookApplet extends JApplet {
JTextField t1, t2, t3, t4, t5, t6;
JTextArea a1, a2, a3, a5, a4, a6, a7;
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b10;
JLabel l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12, l13, l14;
JPanel jp1, jp2, jp3, jp4, jp5, jp6, panel;
//FileReader rd1;
JTextField read1;
//FileWriter wr1;
private JTextField textField_4;
private static ArrayList<JLabel> images = new ArrayList<JLabel>();
String bookname, author, publication, issDate, retDate, custid, image, pdf;
File f, f1;
//Statement statement = null;
//private ResultSet result;
/**
* Create the applet.
*/
public AddBookApplet() {
panel = new JPanel();
panel.setBackground(SystemColor.activeCaptionBorder);
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception de) {
}
l1 = new JLabel("Book Name");
l1.setFont(new Font("Tahoma", Font.PLAIN, 12));
l1.setBounds(10, 24, 100, 14);
panel.add(l1);
t1 = new JTextField();
t1.setBounds(120, 22, 133, 20);
panel.add(t1);
t1.setColumns(10);
l2 = new JLabel("Book Author");
l2.setFont(new Font("Tahoma", Font.PLAIN, 12));
l2.setBounds(10, 64, 100, 14);
panel.add(l2);
t2 = new JTextField();
t2.setColumns(10);
t2.setBounds(120, 62, 133, 20);
panel.add(t2);
l3 = new JLabel("Book Publication");
l3.setFont(new Font("Tahoma", Font.PLAIN, 12));
l3.setBounds(10, 104, 100, 14);
panel.add(l3);
t3 = new JTextField();
t3.setColumns(10);
t3.setBounds(120, 102, 133, 20);
panel.add(t3);
//added
l6 = new JLabel("Cover Image");
l6.setFont(new Font("Tahoma", Font.PLAIN, 12));
l6.setBounds(10, 144, 100, 14);
panel.add(l6);
t6 = new JTextField();
t6.setBounds(120, 142, 133, 20);
t6.setEditable(false);
panel.add(t6);
// ***l7 => Cover Image****
l7 = new JLabel();
l7.setBounds(362, 33, 140, 215);
panel.add(l7);
b4 = new JButton("Browse");
b4.setBounds(262, 142, 89, 25);
panel.add(b4);
l6 = new JLabel("Image Preview:");
l6.setFont(new Font("Tahoma", Font.PLAIN, 12));
l6.setBounds(362, 10, 100, 14);
l6.setVisible(false);
panel.add(l6);
//end add
l4 = new JLabel("PDF File");
l4.setFont(new Font("Tahoma", Font.PLAIN, 12));
l4.setBounds(10, 184, 100, 14);
panel.add(l4);
t4 = new JTextField();
t4.setColumns(10);
t4.setBounds(120, 182, 133, 20);
t4.setEditable(false);
panel.add(t4);
t4.setText("");
b5 = new JButton("Browse");
b5.setBounds(262, 182, 89, 25);
panel.add(b5);
//moved buttons lower
b1 = new JButton("Save");
b1.setBounds(10, 222, 89, 25);
panel.add(b1);
b2 = new JButton("Reset");
b2.setBounds(121, 222, 89, 25);
panel.add(b2);
b3 = new JButton("Cancel");
b3.setBounds(231, 222, 89, 25);
panel.add(b3);
//end changes
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(t1.getText() == null || t1.getText().equals("")){
JOptionPane.showMessageDialog((Component) null,
"Book Must Have a Title",
"Library Management(Pravin Rane)",
JOptionPane.OK_OPTION);
}
else{
try {
bookname = t1.getText();
author = t2.getText();
publication = t3.getText();
issDate = "-";
retDate = "-";
custid = "-";
image = t6.getText();
pdf = t4.getText();
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
//Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://sql3.freemysqlhosting.net:3306/sql322429", "sql322429", "xK5*kT6!");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://dbinstance.cdet1nwidztk.us-west-2.rds.amazonaws.com:3306/ClassCalc", "john", "R17A2FZa");
//Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://gorcruxcom.ipagemysql.com:3306/lmsdatabase", "tyler", "Ambition8143");
PreparedStatement statement = null;
statement = (PreparedStatement) con.prepareStatement("INSERT INTO " +
"LibraryDB(bookname, author, publication, issuedate, rturndate, custid, image, pdf) " +
"VALUES(?, ?, ?, ?, ?, ?, ?, ?)");
statement.setString(1, bookname);
statement.setString(2, author);
statement.setString(3, publication);
statement.setString(4, issDate);
statement.setString(5, retDate);
statement.setString(6, custid);
statement.setString(7, image);
statement.setString(8, pdf);
statement.executeUpdate();
statement.close();
con.close();
/*
images.add(l7);
*/
LibraryApplet library = new LibraryApplet();
library.init();
library.start();
panel.setVisible(false);
setLayout(new BorderLayout(800, 600));
add("Center", library);
}
catch (SQLException e1){
e1.printStackTrace();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
} catch (Exception gr) {
}
}
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
t1.setText("");
t2.setText("");
t3.setText("");
t4.setText("");
t6.setText("");
}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LibraryApplet library = new LibraryApplet();
library.init();
library.start();
panel.setVisible(false);
setLayout(new BorderLayout(800, 600));
add("Center", library);
}
});
//added
// source: http://stackoverflow.com/questions/14142932/gui-with-java-gui-builder-for-uploading-an-image-and-displaying-to-a-panelinsid
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
while(true){
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
f = chooser.getSelectedFile();
if(f != null){
String filename = f.getAbsolutePath();
if(filename.endsWith(".jpg")){
t6.setText(filename);
try {
ImageIcon ii=new ImageIcon(scaleImage(140, 215, ImageIO.read(new File(f.getAbsolutePath()))));
l7.setIcon(ii);
l6.setForeground(Color.BLACK);
l6.setText("Image Preview: ");
l6.setVisible(true);
break;
} catch (Exception ex) {
}
}
else{
l6.setForeground(Color.RED);
l6.setText("Must be .jpg File");
l6.setVisible(true);
}
}
break;
}
}
});
//end add
//Added by Zach. Button to get the chosen file and put its name in the text field.
//this name is used by the pdfviewer to display the file.
b5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(f1 != null){
String filename = f1.getAbsolutePath();
t4.setText(filename);
}
while(true){
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
f1 = chooser.getSelectedFile();
if(f1 != null){
String filename = f1.getAbsolutePath();
if(filename.endsWith(".pdf")){
t4.setText(filename);
l6.setVisible(false);
break;
}
else{
l6.setForeground(Color.RED);
l6.setText("Must be .pdf File");
l6.setVisible(true);
}
}
break;
}
}
});
}
//added
// source: http://stackoverflow.com/questions/14142932/gui-with-java-gui-builder-for-uploading-an-image-and-displaying-to-a-panelinsid
public static BufferedImage scaleImage(int w, int h, BufferedImage img) throws Exception {
BufferedImage bi;
bi = new BufferedImage(w, h, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(img, 0, 0, w, h, null);
g2d.dispose();
return bi;
}
//end add
/*
public static JLabel getImage(int index){
return images.get(index);
}
public static void deleteImage(int index){
images.remove(index);
}
*/
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.