Example 1: Creating Jframe - Texas Tech...

30
Jerry S. Rawls College of Business Administration Area of ISQS Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected] ISQS 6337 Lecture 08 (Swing Components) 1 Example 1: Creating Jframe import javax.swing.*; public class MyFrame { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(400, 300); frame.setVisible(true); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); } } Example 2: CenterFrame import javax.swing.*; import java.awt.*; public class CenterFrame { public static void main(String[] args) { JFrame frame = new JFrame("Centered Frame"); frame.setSize(400, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Get the dimension of the screen Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int screenWidth = screenSize.width; int screenHeight = screenSize.height; // Get the dimension of the frame Dimension frameSize = frame.getSize(); int x = (screenWidth - frameSize.width)/2; int y = (screenHeight - frameSize.height)/2; frame.setLocation(x, y); frame.setVisible(true); } }

Transcript of Example 1: Creating Jframe - Texas Tech...

Page 1: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

1

Example 1: Creating Jframe

import javax.swing.*; public class MyFrame { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(400, 300); frame.setVisible(true); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); }

} Example 2: CenterFrame

import javax.swing.*; import java.awt.*; public class CenterFrame { public static void main(String[] args) { JFrame frame = new JFrame("Centered Frame"); frame.setSize(400, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Get the dimension of the screen Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int screenWidth = screenSize.width; int screenHeight = screenSize.height; // Get the dimension of the frame Dimension frameSize = frame.getSize(); int x = (screenWidth - frameSize.width)/2; int y = (screenHeight - frameSize.height)/2; frame.setLocation(x, y); frame.setVisible(true); } }

Page 2: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

2

Example 3: Tax

MyFrame.java

import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.text.DecimalFormat; public class MyFrame extends JFrame{ JLabel labelSal, labelTR, labelTax; JTextField tfSal, tfTR, tfTax; JButton buttonComp, buttonClear, buttonEnd; public MyFrame() { Container c = getContentPane(); //gets hold of the output screen c.setLayout(new GridLayout(5,2)); labelSal = new JLabel ("Enter your salary"); tfSal = new JTextField(); labelTR = new JLabel("Enter Tax rate here"); tfTR= new JTextField(); labelTax = new JLabel("Your tax is: "); tfTax = new JTextField(); buttonComp = new JButton("Compute Tax"); buttonClear = new JButton("Clear"); buttonEnd = new JButton("End"); c.add(labelSal); c.add(tfSal); c.add(labelTR); c.add(tfTR); c.add (labelTax); c.add(tfTax); c.add(buttonComp); c.add(buttonClear); c.add(buttonEnd); ButtonHandler handler = new ButtonHandler();

Page 3: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

3

buttonComp.addActionListener(handler); buttonClear.addActionListener(handler); buttonEnd.addActionListener(handler); pack(); setVisible(true); } private class ButtonHandler implements ActionListener { public void actionPerformed (ActionEvent e) { if (e.getSource() == buttonComp) {double sal, rate,tax; sal = Double.parseDouble(tfSal.getText()); rate =Double.parseDouble(tfTR.getText()); tax = sal * rate/100.0; DecimalFormat myFor = new DecimalFormat("0.00"); tfTax.setText(String.valueOf(myFor.format(tax))); } if(e.getSource() == buttonClear) { tfSal.setText(""); tfTR.setText(""); tfTax.setText(""); } if(e.getSource() == buttonEnd) { System.exit(0);} } } }

MyApp.java

public class MyApp { public static void main (String args[]) { MyFrame myTax= new MyFrame(); myTax.addWindowListener( new WindowAdapter(){ public void windowClosing( WindowEvent e) { System.exit(0); } } ); } }

Page 4: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

4

Example 4: Inventory Create the GUI for an inventory application that calculates the number of textbooks received by a college bookstore.

Application Requirements TTU bookstore receives cartons of textbooks. In each shipment, each carton contains the same number of textbooks. The inventory manger wants to use a compute to calculate the total number of textbooks arriving at the bookstore for each shipment. The inventory manage will enter the number of cartons received and the fixed number of textbooks in each carton of the shipment; the application should then calculate and display the total number of textbooks in the shipment

Inventory.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Inventory extends JFrame { private JLabel jlCartons; private JTextField jtfCartons; private JLabel jlItems; private JTextField jtfItems; private JLabel jlTotal; private JTextField jtfTotalResult; private JButton jbtCalculate; public Inventory() { createUserInterface(); } public void createUserInterface() {

Page 5: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

5

Container c = getContentPane(); c.setLayout( null ); jlCartons = new JLabel(); jlCartons.setText( "Cartons per shipment:" ); jlCartons.setBounds( 16, 16, 130, 21 ); c.add( jlCartons ); jlItems = new JLabel(); jlItems.setText( "Items per carton:" ); jlItems.setBounds( 16, 48, 104, 21 ); c.add( jlItems ); // set up jlTotal jlTotal = new JLabel(); jlTotal.setText( "Total:" ); jlTotal.setBounds( 204, 16, 40, 21 ); c.add( jlTotal ); // set up jtfCartons jtfCartons = new JTextField(); jtfCartons.setText( "0" ); jtfCartons.setBounds( 148, 16, 40, 21 ); jtfCartons.setHorizontalAlignment( JTextField.RIGHT ); c.add( jtfCartons ); // set up jtfItems jtfItems = new JTextField(); jtfItems.setText( "0" ); jtfItems.setBounds( 148, 48, 40, 21 ); jtfItems.setHorizontalAlignment( JTextField.RIGHT ); c.add( jtfItems ); // set up jtfTotalResult jtfTotalResult = new JTextField(); jtfTotalResult.setBounds( 244, 16, 86, 21 ); jtfTotalResult.setHorizontalAlignment( JTextField.RIGHT ); jtfTotalResult.setEditable( false ); c.add( jtfTotalResult ); // set up jbtCalculate jbtCalculate = new JButton(); jbtCalculate.setText( "Calculate Total" ); jbtCalculate.setBounds( 204, 48, 126, 24 ); c.add( jbtCalculate ); ButtonHandler h = new ButtonHandler(); jbtCalculate.addActionListener(h); setTitle( "Inventory" ); // set title bar text setSize( 354, 112 ); // set window size

Page 6: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

6

setVisible( true ); // display window } public class ButtonHandler implements ActionListener{ public void actionPerformed( ActionEvent e) { if (e.getSource() == jbtCalculate) // multiply values input and display result in the text field jtfTotalResult.setText( String.valueOf( Integer.parseInt( jtfCartons.getText() ) * Integer.parseInt( jtfItems.getText() ) ) ); } // end method jbtCalculateActionPerformed } } // end class Inventory MyApp.java class MyApp { public static void main(String[] args) { Inventory application = new Inventory(); } }

Page 7: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

7

Example 5: Add List

Class: Button Variable or Component Name

Data Type Description

txtDept TextField Input the department strDept String Store the department txtName TextField strName String txtPhone TextField Input the phone extension strPhone String Store the phone extension btnAdd Button Add to phone list and clear fields txaPhoneList TextArea Holds a list of names and phone

numbers Methods Access Mode Return Type Method Name Pseudocode public void main Control the program Public Button Default constructor

- Add components to the container Public Void actionPerformed Transfer data from text boxes

Concatenate the data Append line to text area Clear text fields Reset the focus

Page 8: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

8

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Button extends JFrame{ //Declare components JTextField txtDept = new JTextField(20); JTextField txtName = new JTextField(20); JTextField txtPhone = new JTextField(5); JTextArea txaPhoneList = new JTextArea(10, 30); JButton btnAdd = new JButton("Add to List"); //Declare variables String strDept; String strName; String strPhone; public Button() { //Place components to the Container Container c = getContentPane(); c.setLayout(new BorderLayout()); JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(4,2)); p1.add(new JLabel("Department: "), BorderLayout.NORTH); p1.add(txtDept, BorderLayout.NORTH); p1.add(new JLabel("Name: ")); p1.add(txtName); p1.add(new JLabel("Extension: ")); p1.add(txtPhone); p1.add(btnAdd); c.add(p1, BorderLayout.NORTH); c.add(txaPhoneList, BorderLayout.CENTER); txtDept.requestFocus(); pack(); setVisible(true); //Add action listeners ButtonHandler handler= new ButtonHandler(); btnAdd.addActionListener(handler); } public static void main (String args[]) { Button MyApp = new Button(); MyApp.addWindowListener( new WindowAdapter( ) { public void windowClosing(WindowEvent e)

Page 9: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

9

{ System.exit(0); } } ); } private class ButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent e) { if (e.getSource()==btnAdd) { String strOutputLine; //Declare local variable //Assign the text fields to variables strDept = txtDept.getText(); strName = txtName.getText(); strPhone = txtPhone.getText(); //Concatenate the variables strOutputLine = strDept + "\t" + strName + "\t" + strPhone; //Append the concatenated line to the phone list txaPhoneList.append(strOutputLine + "\n"); //Clear the text fields txtDept.setText(""); txtName.setText(""); txtPhone.setText(""); txtDept.requestFocus(); } } } }

Page 10: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

10

Example 06: Car Payment System

Application Requirements Typically, banks offer car loans for periods ranging from two to five years (24 to 60 months). Borrowers repay the loans in fixed monthly payments. The amount of each monthly payment is based on the length of the loan, the amount of borrowed and the interest rate. Create an application that allows the customer to enter the price of a car, the down payment amount and the annual interest rate of the loan. The application should display the loan’s duration in months and the monthly payments for two-, three-, four-, and five-year loans

Car payment system displays for loan lengths of two, three, four and five years. The above requirement indicates that the application must repeat a calculation four times- a repetition statement will be needed to solve this problem.

CarPayment.java import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.text.DecimalFormat; public class CarPayment extends JFrame { private JLabel jlPrice; private JTextField jtfPrice; private JLabel jlDownPayment;

Page 11: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

11

private JTextField jtfDownPayment; private JLabel jlInterest; private JTextField jtfInterest; private JButton jbtnCalculate; private JTextArea jtaPayments; public CarPayment() { createUserInterface(); } // create and position GUI components; register event handlers private void createUserInterface() { // get content pane and set layout to null Container c = getContentPane(); c.setLayout( null ); // set up jlPrice jlPrice = new JLabel(); jlPrice.setBounds( 40, 24, 80, 21 ); jlPrice.setText( "Price:" ); c.add( jlPrice ); // set up jtfPrice jtfPrice = new JTextField(); jtfPrice.setBounds( 184, 24, 56, 21 ); jtfPrice.setHorizontalAlignment( JTextField.RIGHT ); c.add( jtfPrice ); // set up jlDownPayment jlDownPayment = new JLabel(); jlDownPayment.setBounds( 40, 56, 96, 21 ); jlDownPayment.setText( "Down payment:" ); c.add( jlDownPayment ); // set up jtfDownPayment jtfDownPayment = new JTextField(); jtfDownPayment.setBounds( 184, 56, 56, 21 ); jtfDownPayment.setHorizontalAlignment(JTextField.RIGHT ); c.add( jtfDownPayment ); // set up jlInterest jlInterest = new JLabel(); jlInterest.setBounds( 40, 88, 120, 21 ); jlInterest.setText( "Annual interest rate:" ); c.add( jlInterest ); // set up jtfInterest

Page 12: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

12

jtfInterest = new JTextField(); jtfInterest.setBounds( 184, 88, 56, 21 ); jtfInterest.setHorizontalAlignment( JTextField.RIGHT ); c.add( jtfInterest ); // set up jbtnCalculate and register its event handler jbtnCalculate = new JButton(); jbtnCalculate.setBounds( 92, 128, 94, 24 ); jbtnCalculate.setText( "Calculate" ); c.add( jbtnCalculate ); ButtonHandler h = new ButtonHandler(); jbtnCalculate.addActionListener(h); // set up jtaPayments jtaPayments = new JTextArea(); jtaPayments.setBounds( 28, 168, 232, 90 ); jtaPayments.setEditable( false ); c.add( jtaPayments ); // set properties of application's window setTitle( "Car Payment Calculator" ); // set title bar text setSize( 288, 302 ); // set window's size setVisible( true ); // display window } // end method createUserInterface public class ButtonHandler implements ActionListener{ // method called when user clicks jbtnCalculate public void actionPerformed( ActionEvent e) { int years = 2; // length of the loan in years int months; // payment period double monthlyPayment; // monthly payment if (e.getSource()==jbtnCalculate) { // clear jtaPayments jtaPayments.setText( "" ); // add header to jtaPayments jtaPayments.append( "Months\tMonthly Payments" ); // retrieve user input int price = Integer.parseInt( jtfPrice.getText() ); int downPayment = Integer.parseInt( jtfDownPayment.getText() ); double interest = Double.parseDouble( jtfInterest.getText() ); // calculate loan amount and monthly interest int loanAmount = price - downPayment;

Page 13: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

13

double monthlyInterest = interest / 1200; // format to display monthlyPayment in currency format DecimalFormat currency = new DecimalFormat( "$0.00" ); // while years is less than or equal to five years while ( years <= 5 ) { // calculate payment period months = 12 * years; // get monthlyPayment monthlyPayment = calculateMonthlyPayment(monthlyInterest, months, loanAmount ); // insert result into jtaPayments jtaPayments.append( "\n" + months + "\t" + currency.format( monthlyPayment ) ); years++; // increment counter } // end while } //end if statement } // end method jbtnCalculateActionPerformed } //end ButtonHandler class // method to clear JTextArea contents private void clearJTextArea() { jtaPayments.setText( "" ); // clear JTextArea contents } // calculate monthlyPayment private double calculateMonthlyPayment( double monthlyInterest, int months, int loanAmount ) { double base = Math.pow( 1 + monthlyInterest, months ); return loanAmount * monthlyInterest / ( 1 - ( 1 / base ) ); } } // end class CarPayment

Page 14: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

14

Example 07: Detanl Application

Application Requirements A dentist has asked you to create an application that employees can use to bill patients. Your application must allow the user to enter the patient’s name and specify which services were performed during the visit. Your application must then calculate the total charges. If a user attempts to calculate the total of a bill before any services are specified or before the patient’s name is entered, an error message should be displayed

Pseudocode: When the user clicks the Calculate button: Obtain patient name for JTextField If user has not entered a patient name or has not selected any JCheckBoxes display error message in Dialog Else if Cleaning JCheckBox is selected Add cost of cleaning to total if Cavity Filling is selected Add cost of Cavity to total if X-Ray is selected add cost of X-ray total Display total price of services rendered in dollar format

Action Component/class/object event Lable the application’s components jlbDetalPaymentForm,

jlbPantionentName, jlTotal, jlCleaningPrice, jlCavityFilling, jlXrayPrice, jcbCavityFilling, jcbCleaning, jcbXray, jbtnCalcuate

Obtain patient name for JTextField jtfPatientName user has not entered a patient name or has not selected any JCheckBoxes

jcbCleaning, jcbCavityFilling, jcbXray

display error message in Dialog JOptionPane Else if Cleaning JCheckBox is selected Add cost of cleaning to total

jcbCleaning

if Cavity Filling is selected Add cost of Cavity to total

jcbCavityFilling

if X-Ray is selected Add cost of X-ray total

jcbXray

Display total price of services rendered in dollar format

jtfTotal, dollar (DecimalFormat)

Page 15: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

15

DentalPayment.java import java.awt.*; import java.awt.event.*; import java.text.*; import javax.swing.*; public class DentalPayment extends JFrame { private JLabel jlDentalPaymentForm; private JLabel jlPatientName; private JTextField jtfPatientName; private JCheckBox jcbCleaning; private JLabel jlCcleaningPrice; private JCheckBox jcbCavityFilling; private JLabel jlCavityFillingPrice; private JCheckBox jcbXRay; private JLabel xRayPriceJLabel; private JLabel jlTotal; private JTextField jtfTotal; private JButton jbtnCalculate; public DentalPayment() { createUserInterface();

Page 16: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

16

} private void createUserInterface() { // get content pane for attaching GUI components Container c= getContentPane(); // set up jlDentalPaymentForm jlDentalPaymentForm = new JLabel(); jlDentalPaymentForm.setBounds( 19, 19, 235, 28 ); jlDentalPaymentForm.setText( "Dental Payment Form" ); jlDentalPaymentForm.setFont(new Font( "Default", Font.PLAIN, 22 ) ); jlDentalPaymentForm.setHorizontalAlignment(JLabel.CENTER ); c.add( jlDentalPaymentForm ); // set up jlPatientName jlPatientName = new JLabel(); jlPatientName.setBounds( 19, 65, 91, 21 ); jlPatientName.setText( "Patient name:" ); c.add( jlPatientName ); // set up jtfPatientName jtfPatientName = new JTextField(); jtfPatientName.setBounds( 132, 65, 117, 21 ); c.add( jtfPatientName ); // set up jcbCleaning jcbCleaning = new JCheckBox(); jcbCleaning.setBounds( 16, 112, 122, 24 ); jcbCleaning.setText( "Cleaning" ); c.add( jcbCleaning ); // set up jlCcleaningPrice jlCcleaningPrice = new JLabel(); jlCcleaningPrice.setBounds( 211, 112, 38, 24 ); jlCcleaningPrice.setText( "$35" ); jlCcleaningPrice.setHorizontalAlignment( JLabel.RIGHT ); c.add( jlCcleaningPrice ); // set up jcbCavityFilling jcbCavityFilling = new JCheckBox(); jcbCavityFilling.setBounds( 16, 159, 122, 24 ); jcbCavityFilling.setText( "Cavity Filling" ); c.add( jcbCavityFilling ); // set up jlCavityFillingPrice jlCavityFillingPrice = new JLabel(); jlCavityFillingPrice.setBounds( 211, 159, 38, 24 ); jlCavityFillingPrice.setText( "$150" ); jlCavityFillingPrice.setHorizontalAlignment(JLabel.RIGHT );

Page 17: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

17

c.add( jlCavityFillingPrice ); // set up jcbXRay jcbXRay = new JCheckBox(); jcbXRay.setBounds( 16, 206, 122, 24 ); jcbXRay.setText( "X-Ray" ); c.add( jcbXRay ); // set up xRayPriceJLabel xRayPriceJLabel = new JLabel(); xRayPriceJLabel.setBounds( 211, 206, 38, 24 ); xRayPriceJLabel.setText( "$85" ); xRayPriceJLabel.setHorizontalAlignment( JLabel.RIGHT ); c.add( xRayPriceJLabel ); // set up jlTotal jlTotal = new JLabel(); jlTotal.setBounds( 144, 256, 41, 21 ); jlTotal.setText( "Total:" ); c.add( jlTotal ); // set up jtfTotal jtfTotal = new JTextField(); jtfTotal.setBounds( 192, 256, 56, 21 ); jtfTotal.setEditable( false ); jtfTotal.setHorizontalAlignment( JTextField.CENTER ); c.add( jtfTotal ); // set up jbtnCalculate jbtnCalculate = new JButton(); jbtnCalculate.setBounds( 155, 296, 94, 24 ); jbtnCalculate.setText( "Calculate" ); c.add( jbtnCalculate ); ButtonHandler h = new ButtonHandler(); jbtnCalculate.addActionListener(h); setTitle( "Dental Payment" ); // set title bar string setSize( 272, 364 ); // set window size setVisible( true ); // display window } // calculate cost of patient's visit public class ButtonHandler implements ActionListener{ public void actionPerformed( ActionEvent e) { if (e.getSource()==jbtnCalculate) { String patient = jtfPatientName.getText();

Page 18: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

18

// display error message if no name entered or no JCheckBox is selected if ( ( patient.equals( "" ) ) ||( !jcbCleaning.isSelected() && !jcbCavityFilling.isSelected() && !jcbXRay.isSelected() ) ) { // display error message JOptionPane.showMessageDialog( null, "Please enter a name and check at least one item.", "Missing Information", JOptionPane.ERROR_MESSAGE ); } else // otherwise, do calculations { double total = 0.0; // if patient had a cleaning if ( jcbCleaning.isSelected() ) { total += 35; } // if patient had cavity filled if ( jcbCavityFilling.isSelected() ) { total += 150; } // if patient had x-ray taken if ( jcbXRay.isSelected() ) { total += 85; } DecimalFormat dollars = new DecimalFormat( "$0.00" ); jtfTotal.setText( dollars.format( total ) ); } // end else } } } } // end class DentalPayment MyApp.java class MyApp { public static void main( String[] args ) { DentalPayment application = new DentalPayment(); } // end method main }

Page 19: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

19

Example 08: RadioButton

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class RadioButton extends JFrame{ private JTextField t; private JRadioButton plain, bold, italic; private Font plainFont, boldFont, italicFont; public RadioButton() { super ("Radio Button"); Container c = getContentPane(); c.setLayout(new FlowLayout()); t = new JTextField ("Font Change", 25); c.add(t); //Crate radio button plain = new JRadioButton ("Plain", true); c.add(plain); bold = new JRadioButton ("Bold", false); c.add(bold); italic = new JRadioButton ("Italic", false); c.add(italic); //Register event RadioButtonHandler handler=new RadioButtonHandler(); plain.addItemListener( handler); bold.addItemListener( handler); italic.addItemListener( handler); //Create logical relationship ButtonGroup radioGroup = new ButtonGroup(); radioGroup.add(plain); radioGroup.add(bold); radioGroup.add(italic); plainFont = new Font("TimesRoman", Font.PLAIN, 14); boldFont = new Font("TimesRoman", Font.BOLD, 14); italicFont = new Font("TimesRoman", Font.ITALIC, 14); t.setFont(plainFont); setSize(300,100); show(); } public static void main(String args[]) {

Page 20: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

20

RadioButton MyApp = new RadioButton(); MyApp.addWindowListener( new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.exit(0); } } ); } public class RadioButtonHandler implements ItemListener{ public void itemStateChanged (ItemEvent e) { if(e.getSource() ==plain) t.setFont(plainFont); else if (e.getSource() ==bold) t.setFont(boldFont); else if (e.getSource () == italic) t.setFont(italicFont); t.repaint(); } }

}

Page 21: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

21

Example 09:ComboBox This example creates a Swing application for EventHandlers Incorporated that allows the user to choose a party favor and displays the favor price. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JComboDemo extends JFrame{ JComboBox jcbBox; JLabel jlList, jlEvent; JTextField jtfPrice; JPanel p1, p2; int favorPrice[ ] = { 0, 725, 325, 125, 135}; int totalPrice = 0; String partyItem[ ] = {"None", "Hats", "Streamers", "Noise Makers", "Ballons"}; String output; int FavorNum; public JComboDemo() { super ("JComboBox Demo"); Container c = getContentPane(); c.setLayout(new BorderLayout()); p1 = new JPanel(); p1.setLayout(new GridLayout(1,2)); jlList = new JLabel("Favor List: "); p1.add(jlList); jcbBox = new JComboBox(partyItem); jcbBox.setMaximumRowCount(3); p1.add(jcbBox); c.add(p1, BorderLayout.NORTH); p2 = new JPanel(); p2.setLayout(new GridLayout(2,1)); jlEvent = new JLabel("Event Handlers Incorporated"); p2.add(jlEvent); jtfPrice = new JTextField (10); p2.add(jtfPrice); c.add(p2, BorderLayout.CENTER);

Page 22: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

22

ItemHandler h = new ItemHandler( ); jcbBox.addItemListener(h); pack(); setVisible(true); } public static void main (String args[]) { JComboDemo app = new JComboDemo(); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public class ItemHandler implements ItemListener{ public void itemStateChanged(ItemEvent e) { if (e.getStateChange( )== ItemEvent.SELECTED) { int favorNum = jcbBox.getSelectedIndex( ); totalPrice = favorPrice[favorNum]; output = "Favor Price $ " + totalPrice; jtfPrice.setText (output); } /* if (e.getSource( ) == jcbBox) { int favorNum = jcbBox.getSelectedIndex( ); totalPrice = favorPrice[favorNum]; output = "Favor Price $ " + totalPrice; jtfPrice.setText (output); }*/ } } }

Page 23: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

23

Example10: JToolBar JToolBarDemo.java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JToolBarDemo extends JFrame{ JTextArea jtaEdit = new JTextArea (); JScrollPane scroll = new JScrollPane(jtaEdit, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); JPanel p1 = new JPanel(); ImageIcon image1 = new ImageIcon("Nam1.jpg"); ImageIcon image2 = new ImageIcon("Nam2.jpg"); ImageIcon image3 = new ImageIcon("Nam3.jpg"); JButton btnB1 = new JButton ("About Me", image1); JButton btnB2 = new JButton ("My Phone", image2); JButton btnB3 = new JButton ("My Address", image3); JToolBar bar = new JToolBar(); public JToolBarDemo() { super("Personal Information"); Container c = getContentPane(); bar.add(btnB1); bar.add(btnB2); bar.add(btnB3); ButtonHandler h = new ButtonHandler(); btnB1.addActionListener(h); btnB2.addActionListener(h); btnB3.addActionListener(h); p1.setLayout(new BorderLayout()); p1.add(bar, BorderLayout.NORTH); p1.add(scroll); c.add(p1); setSize(700, 300); setVisible(true); } public class ButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ if (e.getSource() ==btnB1) { jtaEdit.append ("\n Daniel and David"); }

Page 24: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

24

else if (e.getSource()==btnB2) { jtaEdit.append("\n Hi All"); } else if (e.getSource() == btnB3) { jtaEdit.append("\n I am Jaeki"); } } } } MyApp.java public class MyApp { public static void main (String args[]) { JToolBarDemo jt = new JToolBarDemo(); } }

Page 25: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

25

Example 11: JList

import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public class List extends JFrame{ private JList colorList; private Container c; private String colorNames[] = {"Cyan", "Magenta", "Yellow", "Black", "Blue", "Red" }; private Color colors[]= {Color.cyan, Color.magenta, Color.yellow, Color.black, Color.blue, Color.red}; public List() { super("List"); c = getContentPane(); c.setLayout(new FlowLayout()); //Create a list with teh items in the colorNames array colorList = new JList (colorNames); colorList.setVisibleRowCount(3); //do not allow multiple selections colorList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //add a JscrollPane containing teh JList to teh content pane c.add (new JScrollPane(colorList)); ListHandler l = new ListHandler (); colorList.addListSelectionListener(l); setSize(250,150); show(); }

Page 26: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

26

public class ListHandler implements ListSelectionListener{ public void valueChanged(ListSelectionEvent e) { c.setBackground(colors[colorList.getSelectedIndex()]); } } public static void main(String args[]) { List MyApp = new List(); MyApp.addWindowListener( new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.exit(0); } } ); } }

Page 27: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

27

Example 12: Menu

1. MenuApp.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MenuApp extends JFrame{ JFrame frmMenu; JLabel lblName; JMenuBar mnuMain; JMenu mnuFile, mnuEdit, mnuHelp, mnuEditColor; JMenuItem mnuFileSave, mnuFileExit; JCheckBoxMenuItem mnuEditBold; Font fntBold, fntPlain; public MenuApp() { Container c = getContentPane(); //Declare components frmMenu = new JFrame("Menu Demo");

Page 28: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

28

lblName = new JLabel("Your Name"); fntBold = new Font("Times New Roman", Font.BOLD, 12); fntPlain = new Font("Times New Roman", Font.PLAIN, 12); //Menu components mnuMain = new JMenuBar(); mnuFile = new JMenu("File"); mnuEdit = new JMenu("Edit"); mnuHelp = new JMenu("Help"); mnuEditColor = new JMenu("Color"); //Menu items mnuFileSave = new JMenuItem("Save"); mnuFileExit = new JMenuItem("Exit"); mnuEditBold = new JCheckBoxMenuItem("Bold", true); //Create the menu bar //File menu mnuMain.add(mnuFile); mnuFile.add(mnuFileSave); mnuFileSave.setEnabled(false); mnuFile.addSeparator(); ActionHandler handler1 = new ActionHandler(); mnuFile.add(mnuFileExit).addActionListener(handler1); //Edit menu mnuMain.add(mnuEdit); mnuEdit.addActionListener(handler1); mnuEdit.add(mnuEditBold); ItemHandler handler2 = new ItemHandler(); mnuEditBold.addItemListener(handler2); mnuEdit.add(mnuEditColor); mnuEditColor.add("Red").addActionListener(handler1); mnuEditColor.add("Blue").addActionListener(handler1); mnuEditColor.add("Green").addActionListener(handler1); //Help menu mnuMain.add(mnuHelp); mnuHelp.add(new JMenuItem("About")).addActionListener(handler1); //Attach the menu bar to the frame setJMenuBar(mnuMain); //Set up the components and the frame lblName.setFont(fntBold); c.add(lblName); } private class ActionHandler implements ActionListener { public void actionPerformed(ActionEvent e)

Page 29: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

29

{ //Determine which menu item was selected String strMenuItem = e.getActionCommand(); if (strMenuItem.equals("Exit")) System.exit(0); //Exit to the operating system else if (strMenuItem.equals("Red")) lblName.setForeground(Color.red); else if (strMenuItem.equals("Blue")) lblName.setForeground(Color.blue); else if (strMenuItem.equals("Green")) lblName.setForeground(Color.green); else if (strMenuItem.equals("About")) { AboutDialog frmAbout = new AboutDialog(frmMenu);} } } public class ItemHandler implements ItemListener { public void itemStateChanged(ItemEvent event) { //Determine state of Checkbox menu item int intState = event.getStateChange(); if (intState == event.SELECTED) lblName.setFont(fntBold); else lblName.setFont(fntPlain); } } } 2. AboutDialog.java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class AboutDialog extends Dialog{ JButton btnOK = new JButton("OK"); JLabel lblProgrammer = new JLabel(" Programmer: Jaeki Song "); //Constructor public AboutDialog(Frame frmParent) { super(frmParent, "About My Application", true); //Call the parent's constructor setLayout(new FlowLayout()); add(lblProgrammer); add(btnOK); ButtonHandler handler3 = new ButtonHandler();

Page 30: Example 1: Creating Jframe - Texas Tech Universityjsong.ba.ttu.edu/ISQS2341/Fall05/Lecture08_Example.pdf · 2005-11-03 · Jerry S. Rawls College of Business Administration Area of

Jerry S. Rawls College of Business Administration Area of ISQS

Jaeki Song, Ph.D. Box 42101 Lubbock, TX, 79409-2101 PH: 806 784 0435 [email protected]

ISQS 6337 Lecture 08 (Swing Components)

30

btnOK.addActionListener(handler3); //Listen for close box addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent event) { dispose(); //Destroy the dialog } }); setSize(220, 100); show(); } public class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent event) { //Destroy the dialog when OK is pressed Object objSource = event.getSource(); if(objSource == btnOK) dispose(); //Destroy the dialog } } } 3. MyApp.java import java.awt.*; import java.awt.event.*; public class MyApp { public static void main(String args[]) { MenuApp myMenuApp = new MenuApp(); myMenuApp.setSize(400, 200); myMenuApp.setVisible(true); myMenuApp.addWindowListener( new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.exit(0); } } ); } }