Presentation is loading. Please wait.

Presentation is loading. Please wait.

Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar with common.

Similar presentations


Presentation on theme: "Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar with common."— Presentation transcript:

1 Graphical User Interfaces

2 Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar with common user-interface components, such as radio buttons, check boxes, and menus  To build programs that handle events generated by user ‑ interface components  To browse the Java documentation effectively Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 2

3 Introduction  Graphical User Interface (GUI):  a user-friendly mechanism for interacting with an application.  Pronounced “GOO-ee”  built from GUI components.  GUI Component:  an object with which the user interacts via the mouse, the keyboard or another form of input, such as voice recognition.  E.g. Frame, Label, TextFields  We will learn Swing GUI components from the javax.swing package. Page 3

4 Sample Demo  Download Swingset3 application and run:  download.java.net/javadesktop/swingset3/SwingSet3.jnlp  This application is a nice way for you to browse through the various GUI components provided by Java’s Swing GUI APIs.  Simply click a component name (e.g., JFrame, JTabbedPane, etc.) in the GUI Components area at the left of the window to see a demonstration of the GUI component in the right side of the window. The source code for each demo is shown in the text area at the bottom of the window. Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 4

5 From: Java How To Program – Dietel & Dietel Page 5 The menus, buttons and combo box are part of the application’s GUI. They enable you to interact with the application.

6 Simple GUI-Based Input/Output with JOptionPane  To interact with the user, applications use:  Windows OR classes: JFrame, JPanel  dialog boxes Classes: JOptionPane Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 6

7 Simple GUI-Based Input/Output with JOptionPane 1. Dialog boxes:  Output: display important messages to the user OR  Input: obtain information from the user.  Use Java’s JOptionPane class (package javax.swing) Refer JavaDoc API Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 7

8 Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 8

9 Page 9 parentComponent=null result in centering message in screen Unlike Scanner, which can be used to input values of several types from the user at the keyboard, an input dialog can input only Strings. If the user clicks Cancel button, showInputDialog returns null. Get user input: Display output:

10 Sample program for I/O dialogs  A sample program Addition that takes two numbers as user input, calculate sum and display calculated sum. Uses JOptionPane to get user input and display sum. Page 10 import javax.swing.JOptionPane; public class Addition { public static void main( String[] args ) { // obtain user input from JOptionPane input dialogs String firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); String secondNumber = JOptionPane.showInputDialog( "Enter second integer" ); // convert String inputs to int values for use in a calculation int number1 = Integer.parseInt( firstNumber ); int number2 = Integer.parseInt( secondNumber ); int sum = number1 + number2; // add numbers // display result in a JOptionPane message dialog JOptionPane.showMessageDialog( null, "The sum is " + sum, "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE ); }

11  Sample output from program: Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 11

12 Windows 2. Window (JFrame, JPanel):  Contain other GUI components on the window JLabel, JButton, JPanel etc.  JFrame = a heavy weight container used as the top-level window  JPanel = a light weight container used to organize GUI components  When a frame is created, the content pane ( Container holding GUI Objects in frame) is created with it Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 12

13 Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 13 X My First Frame Enter Student ID : Student Transcript: PRINTCANCELCLEAR frame panel1 panel2 panel3

14  Try following code in interaction window: import javax.swing.*; JPanel p = new JPanel(); JLabel l1 = new JLabel("Panel label"); p.add(l1); p.setVisible(true);  Now try this: JFrame f = new JFrame("First Frame"); JLabel l2 = new JLabel("Hello"); f.getContentPane().add(l2); f.getContentPane().add(p); f.setVisible(true); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 14

15 JFrame Class  Example empty JFrame window (with no GUI components inside): Page 15 import javax.swing.JFrame; import javax.swing.JLabel; public class MyFrame extends JFrame { public MyFrame(String title) { super(title); setSize(400,300); } public static void main(String[] args) { MyFrame f = new MyFrame("My First Frame"); f.setVisible(true); }

16  Output: Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 16

17  Example JFrame with a GUI object(JLabel) added: Page 17 import javax.swing.JFrame; import javax.swing.JLabel; Import java.awt.Container; public class MyFrame2 extends JFrame { public MyFrame(String title) { super(title); JLabel label = new JLabel("Hello World !"); //create a label getContentPane().add( label ); //add label to frame content pane setSize(400,300); } public static void main(String[] args) { MyFrame f = new MyFrame("My First Frame"); f.setVisible(true); }

18  Output: Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 18

19 JPanel Class  Example JFrame with a JPanel objects containing other JLabel objects: Page 19 import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JLabel; public class MyFrame extends JFrame { public MyFrame(String title) { super(title); //create a JPanel JPanel panel1 = new JPanel(); //create 3 labels JLabel label1 = new JLabel("Label 1"); JLabel label2 = new JLabel("Label 2"); JLabel label3 = new JLabel("Label 3"); //add 3 labels to panel1 panel1.add(label1); panel1.add(label2); panel1.add(label3); //add panel1 to frame content pane getContentPane().add( panel1 ); } public static void main(String[] args) { MyFrame f = new MyFrame("My First Frame"); f.setSize(200,200); f.setVisible(true); }

20  Output: Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 20

21 Layout Management  Each container has a layout manager that directs the arrangement of its components  Three useful layout managers are: 1) Border layout 2) Flow layout 3) Grid layout Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 21 Components are added to a container which uses a layout manager to place them

22 Flow Layout  Components are added from left to right  A JPanel uses flow layout by default panel = new JPanel(); panel.add(rateLabel); panel.add(rateField); panel.add(button); panel.add(resultLabel); panel = new JPanel(); panel.add(rateLabel); panel.add(rateField); panel.add(button); panel.add(resultLabel); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 22

23 Example: Page 23 import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JLabel; import java.awt.FlowLayout; public class FlowLayoutFrame extends JFrame{ public FlowLayoutFrame(String title) { super(title); JPanel panel = new JPanel(); FlowLayout layout = new FlowLayout(); //create a flow layout layout.setHgap(50); layout.setVgap(50); panel.setLayout(layout); //set panel layout to flow layout panel.add(new JLabel("One")); panel.add(new JLabel("Two")); panel.add(new JLabel("Three")); panel.add(new JLabel("Four")); panel.add(new JLabel("Five")); panel.add(new JLabel("Six")); getContentPane().add(panel); } public static void main(String[] args) { FlowLayoutFrame f = new FlowLayoutFrame("FlowLayoutDemo"); f.setSize(300,300); f.setVisible(true); }

24  Output: Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 24

25 Border Layout  Components are placed toward areas of a container  NORTH, EAST, SOUTH, WEST, or CENTER  Specify one when adding components  The content pane of a JFrame uses border layout by default panel.setLayout(new BorderLayout()); panel.add(component, BorderLayout.NORTH); panel.setLayout(new BorderLayout()); panel.add(component, BorderLayout.NORTH); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 25

26 Example Page 26 import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JButton; import java.awt.BorderLayout; public class BorderLayoutFrame extends Jframe { public BorderLayoutFrame(String title) { super(title); setSize(300,300); setDefaultCloseOperation(EXIT_ON_CLOSE); BorderLayout layout = new BorderLayout(); //create a borderlayout JPanel panel = new JPanel(); panel.setLayout(layout); //set panel layout to borderlayout panel.add(new JButton("One"),BorderLayout.NORTH); panel.add(new JButton("Two"), BorderLayout.SOUTH); panel.add(new JButton("Three"), BorderLayout.WEST); panel.add(new JButton("Four"), BorderLayout.EAST); panel.add(new JButton("Five"), BorderLayout.CENTER); getContentPane().add(panel); } public static void main(String[] args) { BorderLayoutFrame f = new BorderLayoutFrame("BorderLayout Demo"); f.setVisible(true); } Comment line where you add JButton to SOUTH and run

27  Output: Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 27

28 Grid Layout  Components are placed in boxes in a simple table arrangement  Specify the size (rows then columns) of the grid  Then add components which will be placed from the upper left, across, then down buttonPanel.add(button7); buttonPanel.add(button8); buttonPanel.add(button9); buttonPanel.add(button4);... buttonPanel.add(button7); buttonPanel.add(button8); buttonPanel.add(button9); buttonPanel.add(button4);... JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4, 3)); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4, 3)); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 28

29 Example Page 29 import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JButton; import java.awt.GridLayout; public class GrdLayoutFrame extends JFrame { public GrdLayoutFrame(String title) { super(title); GridLayout layout = new GridLayout(4,3); //create a flow layout setSize(300,300); setLayout(layout); //set panel layout to flow layout getContentPane().add(new JButton("7")); getContentPane().add(new JButton("8")); getContentPane().add(new JButton("9")); getContentPane().add(new JButton("4")); getContentPane().add(new JButton("5")); getContentPane().add(new JButton("6")); getContentPane().add(new JButton("1")); getContentPane().add(new JButton("2")); getContentPane().add(new JButton("3")); getContentPane().add(new JButton("0")); getContentPane().add(new JButton(".")); getContentPane().add(new JButton("CE")); } public static void main(String[] args) { GrdLayoutFrame f = new GrdLayoutFrame("GrdLayout Demo"); f.setVisible(true); }

30  Output: Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 30

31 Question  Which layout manager would be suitable for each component? Page 31 X Get Transcript Enter Student ID : Student Transcript: PRINTCANCELCLEAR frame panel1 panel2 panel3

32 Answer Page 32 X Get Transcript Enter Student ID : Student Transcript: PRINTCANCELCLEAR Frame (BorderLayout) Panel1 (FlowLayout ) In Frame.NORTH Panel2 (GridLayout) In Frame.CENTER Panel3 (FlowLayout) In Frame.SOUTH

33 Programming Question  Write a program CalculatorFrame that generates following GUI:  Hint: Creating a text field: Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 33 JTextField display = new JTextField(); Find program template in next slide

34 public class CalculatorFrame extends JFrame{ public CalculatorFrame(String title){ super(title); //TODO: create calculator panel //TODO: set layout of calculator panel to BorderLayout //TODO add display to calculator Panel //TODO: add key panel to calculator panel //TODO: add calculator panel to frame’s content pane setSize(300,300); } public static void main(String[] args) { CalculatorFrame f = new CalculatorFrame(“Calculator"); f.setVisible(true); } Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 34

35  Which layout manager will work best? Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 35

36 Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 36 calculatorPanel JPanel(BorderLayout) display JTextField = CalculatorPanel.NORTH keyPanel Jpanel = CalculatorPanel.CENTER (GridLayout)

37 Answer Page 37 import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JTextField; import java.awt.BorderLayout; import java.awt.GridLayout; public class CalculatorFrame extends JFrame{ public CalculatorFrame(String title){ super(title); JPanel calculatorPanel = new JPanel(); BorderLayout bLayout = new BorderLayout(); calculatorPanel.setLayout(bLayout); //add display JTextField display = new JTextField(); calculatorPanel.add(display, BorderLayout.NORTH); //add button panel JPanel keypadPanel = new JPanel(); GridLayout gLayout = new GridLayout(4,3); keypadPanel.setLayout(gLayout); keypadPanel.add(new JButton("7")); keypadPanel.add(new JButton("8")); keypadPanel.add(new JButton("9")); keypadPanel.add(new JButton("4")); keypadPanel.add(new JButton("5")); keypadPanel.add(new JButton("6")); keypadPanel.add(new JButton("1")); keypadPanel.add(new JButton("2")); keypadPanel.add(new JButton("3")); keypadPanel.add(new JButton("0")); keypadPanel.add(new JButton(".")); keypadPanel.add(new JButton("CE")); calculatorPanel.add(keypadPanel, BorderLayout.CENTER); setSize(300,300); getContentPane().add(calculatorPanel); } public static void main(String[] args) { CalculatorFrame f = new CalculatorFrame(“Calculator Panel"); f.setVisible(true); }

38  Output: Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 38

39 Processing Text Input  Most graphical programs collect text input through text fields  The JTextField class provides a text field  When you construct a text field, supply the width: –The approximate number of characters that you expect –If the user exceeds this number, text will ‘scroll’ left  A Label helps the user know what you want  Normally to the left of a textbox final int FIELD_WIDTH = 10; final JTextField rateField = new JTextField(FIELD_WIDTH); final int FIELD_WIDTH = 10; final JTextField rateField = new JTextField(FIELD_WIDTH); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 39

40 Processing Text Input  A Button with an actionPerformed method can be used to read the text from the textbox with the getText method  Note that getText returns a String, and must be converted to a numeric value if it will be used in calculations double rate = Double.parseDouble(rateField.getText()); double interest = account.getBalance() * rate / 100; account.deposit(interest); resultLabel.setText("balance: " + account.getBalance()); double rate = Double.parseDouble(rateField.getText()); double interest = account.getBalance() * rate / 100; account.deposit(interest); resultLabel.setText("balance: " + account.getBalance()); Page 40 Code to execute when button is clicked: rateLabel JLable rateField JTextField button JButton resultLabel JLable InvestmentFrame JFrame

41 Example Page 41 import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; /** A frame that shows the growth of an investment with variable interest. */ public class InvestmentFrame extends JFrame { private static final double DEFAULT_RATE = 5; private static final double INITIAL_BALANCE = 1000; private JLabel rateLabel; private JTextField rateField; private JButton button; private JLabel resultLabel; private double balance; Continued next page 

42 Example Page 42 public InvestmentFrame() { balance = INITIAL_BALANCE; resultLabel = new JLabel("Balance: " + balance); //createTextField rateLabel = new JLabel("Interest Rate: "); rateField = new JTextField(10); rateField.setText("" + DEFAULT_RATE); //createButton button = new JButton("Add Interest"); ActionListener listener = new AddInterestListener(); button.addActionListener(listener); //createPanel JPanel panel = new JPanel(); panel.add(rateLabel); panel.add(rateField); panel.add(button); panel.add(resultLabel); add(panel); setSize(450, 100); } Continued next page 

43 Example Page 43 /** Adds interest to the balance and updates the display. */ class AddInterestListener implements ActionListener { public void actionPerformed(ActionEvent event) { double rate = Double.parseDouble(rateField.getText()); double interest = balance * rate / 100; balance = balance + interest; resultLabel.setText("Balance: " + balance); } public static void main(String[] args) { JFrame frame = new InvestmentFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }

44 Text Areas  Create multi-line text areas with a JTextArea object  Set the size in rows and columns  Use the setText method to set the text of a text field or text area final int ROWS = 10; final int COLUMNS = 30; JTextArea textArea = new JTextArea(ROWS, COLUMNS); final int ROWS = 10; final int COLUMNS = 30; JTextArea textArea = new JTextArea(ROWS, COLUMNS); textArea.setText(“Account Balance”); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 44

45 Text Areas  The append method adds text to the end of a text area Use newline characters to separate lines  Use the setEditable method to control user input Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 45 textArea.append(account.getBalance() + "\n"); textArea.setEditable(false);

46 JTextField and JTextArea Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 46  To add scroll bars, use J ScrollPane: JScrollPane scrollPane = new JScrollPane(textArea);

47 Programming Question  Write InvestmentFrame2 (by modifying InvestmentFrame) to replace result label with a text area (with scroll bars). Every time the user clicks button, a new line should be added to text are showing updated total. Page 47

48 Answer import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; /** A frame that shows the growth of an investment with variable interest, using a text area. */ public class InvestmentFrame2 extends JFrame{ private static final double DEFAULT_RATE = 5; private static final double INITIAL_BALANCE = 1000; private JLabel rateLabel; private JTextField rateField; private JButton button; private JTextArea resultArea; private double balance; Page 48 Continued next page 

49 public InvestmentFrame2() { balance = INITIAL_BALANCE; //create text area resultArea = new JTextArea(10, 30); resultArea.setText(balance + "\n"); resultArea.setEditable(false); //createTextField rateLabel = new JLabel("Interest Rate: "); rateField = new JTextField(10); rateField.setText("" + DEFAULT_RATE); //createButton button = new JButton("Add Interest"); ActionListener listener = new AddInterestListener(); button.addActionListener(listener); //createPanel JPanel panel = new JPanel(); panel.add(rateLabel); panel.add(rateField); panel.add(button); JScrollPane scrollPane = new JScrollPane(resultArea); panel.add(scrollPane); add(panel); setSize(400, 250); } Page 49 Continued next page 

50 class AddInterestListener implements ActionListener { public void actionPerformed(ActionEvent event) { double rate = Double.parseDouble(rateField.getText()); double interest = balance * rate / 100; balance = balance + interest; resultArea.append(balance + "\n"); } public static void main(String[] args) { JFrame frame = new InvestmentFrame2(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } Page 50

51 19.3 Choices  In a modern graphical user interface program, there are commonly used devices to make different types of selections: Radio Buttons For a small set of mutually exclusive choices Check Boxes For a binary choice Combo Boxes For a large set of choices Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 51

52 FontViewer Layout  Title Bar  Label  Shows current font  Combo Box  Check Boxes  Radio Buttons Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 52

53 Grouping Radio Buttons  Add Radio Buttons into a ButtonGroup so that only one button in the group is selected at a time  Create the JRadioButton s first, then add them to the ButtonGroup JRadioButton smallButton = new JRadioButton("Small"); JRadioButton mediumButton = new JRadioButton("Medium"); JRadioButton largeButton = new JRadioButton("Large"); ButtonGroup group = new ButtonGroup(); group.add(smallButton); group.add(mediumButton); group.add(largeButton); JRadioButton smallButton = new JRadioButton("Small"); JRadioButton mediumButton = new JRadioButton("Medium"); JRadioButton largeButton = new JRadioButton("Large"); ButtonGroup group = new ButtonGroup(); group.add(smallButton); group.add(mediumButton); group.add(largeButton); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 53

54 Radio Button Panels  Use a panel for each set of radio buttons  The default border for a panel is invisible (no border)  You can add a border to a panel to make it visible along with a text label:  There are a large number of border styles available See the Swing documentation for more details JPanel panel = new JPanel(); panel.add(smallButton); panel.add(mediumButton); panel.add(largeButton); panel.setBorder(new TitledBorder(new EtchedBorder(),"Size")); JPanel panel = new JPanel(); panel.add(smallButton); panel.add(mediumButton); panel.add(largeButton); panel.setBorder(new TitledBorder(new EtchedBorder(),"Size")); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 54

55 Selecting Radio Buttons  It is customary to set one button as selected (the default) when using radio buttons  Use the button's setSelected method  Set the default button before making the enclosing frame visible  Call the isSelected method of each button to find out which one it is currently selected JRadioButton largeButton = new JRadioButton("Large"); largeButton.setSelected(true); JRadioButton largeButton = new JRadioButton("Large"); largeButton.setSelected(true); if (largeButton.isSelected()) { size = LARGE_SIZE; } if (largeButton.isSelected()) { size = LARGE_SIZE; } Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 55

56 Selecting Check Boxes  To setup a Check Box, use Swing JCheckBox  Call the isSelected method of a checkbox to find out whether it is currently selected or not JCheckBox italicCheckBox = new JCheckBox("Italic"); if (italicCheckBox.isSelected()) { style = style + Font.ITALIC } if (italicCheckBox.isSelected()) { style = style + Font.ITALIC } Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 56

57 Combo Boxes Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 57  Add text ‘items’ to a combo box that will show in the list:  Use the getSelectedItem method to return the selected item (as an Object )  Combo boxes can store other objects in addition to strings, so casting to a string may be required: JComboBox facenameCombo = new JComboBox(); facenameCombo.addItem("Serif"); facenameCombo.addItem("SansSerif");... JComboBox facenameCombo = new JComboBox(); facenameCombo.addItem("Serif"); facenameCombo.addItem("SansSerif");... String selectedString = (String) facenameCombo.getSelectedItem(); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 57

58 Try complete code for font viewer  Try it:  usr/people/classes/CS160/handouts/horstmann_bigjava_source_code/ch19/section_3 fontFrame (JFrame, BorderLayout) label(JLable: fontFrame.CENTER) controlPanel(JPanel: fontFrame.SOUTH) faceNamePanel(JPanel) styleGroupPanel(JPanel) sizeGroupPanel(JPanel)

59 Programming Question  Write a program CheckBoxFrame that creates following FontViewer:  When the checkboxes are selected, the font should change accordingly.  Hint: to change font of a text filed: textField.setFont( new Font( "Serif", Font.PLAIN, 14 ) ); textField.setFont( new Font( "Serif", Font.PLAIN+Font.ITALIC, 14 ) ); Page 59 Find Class template In next slide

60 public class CheckBoxFrame extends JFrame { private JTextField textField; // displays text in changing fonts private JCheckBox boldJCheckBox; // to select/deselect bold private JCheckBox italicJCheckBox; // to select/deselect italic private ActionListener listener; //action listener public CheckBoxFrame() { super( "JCheckBox Test" ); //TODO: set layout //TOD: set up JTextField and set its font //TODO: create bold and italic checkboxes and add them to the frame //TODO: register listeners for checkBoxes } //TODO: Implement ActionListner for checkboxes public static void main( String[] args ) { CheckBoxFrame checkBoxFrame = new CheckBoxFrame(); checkBoxFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); checkBoxFrame.setSize( 275, 100 ); // set frame size checkBoxFrame.setVisible( true ); // display frame } Page 60

61 Answer import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.JCheckBox; public class CheckBoxFrame extends JFrame { private JTextField textField; // displays text in changing fonts private JCheckBox boldJCheckBox; // to select/deselect bold private JCheckBox italicJCheckBox; // to select/deselect italic private ActionListener listener; public CheckBoxFrame(){ super( "JCheckBox Test" ); setLayout( new FlowLayout() ); // set frame layout // set up JTextField and set its font textField = new JTextField( "Watch the font style change", 20 ); textField.setFont( new Font( "Serif", Font.PLAIN, 14 ) ); add( textField ); // add textField to JFrame //create checkboxes boldJCheckBox = new JCheckBox( "Bold" ); // create bold checkbox italicJCheckBox = new JCheckBox( "Italic" ); // create italic add( boldJCheckBox ); // add bold checkbox to JFrame add( italicJCheckBox ); // add italic checkbox to JFrame // register listeners for JCheckBoxes listener = new CheckBoxListner(); boldJCheckBox.addActionListener( listener ); italicJCheckBox.addActionListener( listener ); } Page 61 CheckBoxFrame.java

62 class CheckBoxListner implements ActionListener { public void actionPerformed(ActionEvent event) { Font font = null; // stores the new Font // determine which CheckBoxes are checked and create Font if ( boldJCheckBox.isSelected() && italicJCheckBox.isSelected() ) font = new Font( "Serif", Font.BOLD + Font.ITALIC, 14 ); else if ( boldJCheckBox.isSelected() ) font = new Font( "Serif", Font.BOLD, 14 ); else if ( italicJCheckBox.isSelected() ) font = new Font( "Serif", Font.ITALIC, 14 ); else font = new Font( "Serif", Font.PLAIN, 14 ); textField.setFont( font ); // set textField's font } public static void main( String[] args ) { CheckBoxFrame checkBoxFrame = new CheckBoxFrame(); checkBoxFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); checkBoxFrame.setSize( 275, 100 ); // set frame size checkBoxFrame.setVisible( true ); // display frame } Page 62

63 Programming Question  Write a class RadioButtonFrame that generates following Font viewer GUI :  Hint: Use CheckBoxFrame.java as template.  When buttons are selected, the font should change accordingly. Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 63

64 Answer import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.JRadioButton; import javax.swing.ButtonGroup; public class RadioButtonFrame extends JFrame { private JTextField textField; // used to display font changes private JRadioButton plainJRadioButton; // selects plain text private JRadioButton boldJRadioButton; // selects bold text private JRadioButton italicJRadioButton; // selects italic text private JRadioButton boldItalicJRadioButton; // bold and italic private ButtonGroup radioGroup; // buttongroup to hold radio buttons Page 64 RadioButtonFrame.java

65 public RadioButtonFrame() { super( "RadioButton Test" ); setLayout( new FlowLayout() ); // set frame layout textField = new JTextField( "Watch the font style change", 25 ); add( textField ); // add textField to JFrame // create radio buttons plainJRadioButton = new JRadioButton( "Plain", true ); boldJRadioButton = new JRadioButton( "Bold", false ); italicJRadioButton = new JRadioButton( "Italic", false ); boldItalicJRadioButton = new JRadioButton( "Bold/Italic", false ); add( plainJRadioButton ); // add plain button to JFrame add( boldJRadioButton ); // add bold button to JFrame add( italicJRadioButton ); // add italic button to JFrame add( boldItalicJRadioButton ); // add bold and italic button // create logical relationship between JRadioButtons radioGroup = new ButtonGroup(); // create ButtonGroup radioGroup.add( plainJRadioButton ); // add plain to group radioGroup.add( boldJRadioButton ); // add bold to group radioGroup.add( italicJRadioButton ); // add italic to group radioGroup.add( boldItalicJRadioButton ); // add bold and italic textField.setFont( new Font( "Serif", Font.PLAIN, 14 ) ); // set initial font to plain // register events for JRadioButtons ActionListener listener = new RadioButtonListner(); plainJRadioButton.addActionListener(listener ); boldJRadioButton.addActionListener(listener ); italicJRadioButton.addActionListener(listener ); boldItalicJRadioButton.addActionListener(listener ); } Page 65

66 class RadioButtonListner implements ActionListener { public void actionPerformed(ActionEvent event) { Font font = null; // stores the new Font // determine which CheckBoxes are checked and create Font if(plainJRadioButton.isSelected()) font = new Font( "Serif", Font.PLAIN, 14 ); else if (boldJRadioButton.isSelected() ) font = new Font( "Serif", Font.BOLD, 14 ); else if ( italicJRadioButton.isSelected() ) font = new Font( "Serif", Font.ITALIC, 14 ); else if ( boldItalicJRadioButton.isSelected() ) font = new Font( "Serif", Font.BOLD + Font.ITALIC, 14 ); textField.setFont( font ); // set textField's font } public static void main( String[] args ) { RadioButtonFrame radioButtonFrame = new RadioButtonFrame(); radioButtonFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); radioButtonFrame.setSize( 275, 100 ); // set frame size radioButtonFrame.setVisible( true ); // display frame } // end main } Page 66

67 19.4 Menus  A frame can contain a menu bar  Menu items can be added to each Menu or subMenu public class MyFrame extends JFrame { public MyFrame() { JMenuBar menuBar = new JMenuBar(); //create a Menubar object setJMenuBar(menuBar); //add menubar to the frame... } public class MyFrame extends JFrame { public MyFrame() { JMenuBar menuBar = new JMenuBar(); //create a Menubar object setJMenuBar(menuBar); //add menubar to the frame... } Page 67

68 MenuBar and Menu Items  The MenuBar contains Menus Add JMenu objects to the MenuBar ( E.g. a file menu, a Edit menue etc. )  A Menu contains SubMenus and Menu items A Menu item has no further SubMenus JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenu fontMenu = new JMenu("Font"); menuBar.add(fileMenu); menuBar.add(fontMenu); JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenu fontMenu = new JMenu("Font"); menuBar.add(fileMenu); menuBar.add(fontMenu); Page 68 JMenuItem exitItem = new JMenuItem("Exit"); filemenu.add(exitItem); JMenuItem exitItem = new JMenuItem("Exit"); filemenu.add(exitItem);

69 Menu Item Events  Add action listeners to each Menu item  The listener is customized for each Menu item Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 69 JMenuItem item = new JMenuItem(name); ActionListener listener = new FaceItemListener(); item.addActionListener(listener); JMenuItem item = new JMenuItem(name); ActionListener listener = new FaceItemListener(); item.addActionListener(listener);

70 FaceEvent ActionListener (2)  Listener Inner Class version Page 70 class FaceItemListener implements ActionListener { public void actionPerformed(ActionEvent event) { facename = name; // Accesses the local variable name setLabelFont(); } class FaceItemListener implements ActionListener { public void actionPerformed(ActionEvent event) { facename = name; // Accesses the local variable name setLabelFont(); } Try complete code: handouts/source_code/ch19/section_4

71 Programming Question  Write class MenuFrame java that generates the following font viewer  Selecting a menu item should change font in text field appropriately Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 71 Find Class template In next slide

72 public class MenuFrame extends JFrame { private JTextField textField; private ActionListener listener; private JMenuBar bar; private JMenu fontMenu; private JMenuItem plainItem, boldItem, italicsItem, boldItalicsItem; public MenuFrame() { super( "JMenu Test" ); ///TODO:create and add the menu bar, font menu and menu items setLayout( new FlowLayout() ); //set layout textField = new JTextField( "Watch the font style change", 20 ); //create text field textField.setFont( new Font( "Serif", Font.PLAIN, 14 ) ); //set font of text field add( textField ); /add text field listener = new MenuItemListner(); //create a listener for menu items //TODO: register listeners for JMenuItems } class MenuItemListner implements ActionListener{ public void actionPerformed(ActionEvent event) { //TODO: change font base on selected menu item } public static void main( String[] args ) { MenuFrame checkBoxFrame = new MenuFrame(); checkBoxFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); checkBoxFrame.setSize( 275, 100 ); checkBoxFrame.setVisible( true ); } Page 72

73 Answer import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.JCheckBox; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; public class MenuFrame extends JFrame { private JTextField textField; private ActionListener listener; private JMenuBar bar; private JMenu fontMenu; private JMenuItem plainItem, boldItem, italicsItem, boldItalicsItem; Page 73 MenuFrame.java

74 Answer public MenuFrame() { super( "JMenu Test" ); bar = new JMenuBar(); fontMenu = new JMenu( "Font" ); plainItem = new JMenuItem( "Plain" ); boldItem = new JMenuItem( "Bold" ); italicsItem = new JMenuItem( "Italics" ); boldItalicsItem = new JMenuItem( "Bold+Italics" ); fontMenu.add( plainItem ); fontMenu.add( boldItem ); fontMenu.add( italicsItem ); fontMenu.add( boldItalicsItem ); bar.add( fontMenu ); setJMenuBar( bar ); setLayout( new FlowLayout() ); // set up JTextField and set its font textField = new JTextField( "Watch the font style change", 20 ); textField.setFont( new Font( "Serif", Font.PLAIN, 14 ) ); add( textField ); // register listeners for JMenuItems listener = new MenuItemListner(); plainItem.addActionListener( listener); boldItem.addActionListener( listener ); italicsItem.addActionListener( listener ); boldItalicsItem.addActionListener( listener ); } Page 74

75 Answer class MenuItemListner implements ActionListener { public void actionPerformed(ActionEvent event) { Font font = null; //if(event.getSource() == plainItem){ if(plainItem.isSelected()){ font = new Font( "Serif", Font.PLAIN, 14 ); } else if(event.getSource() == boldItem){ font = new Font( "Serif", Font.BOLD, 14 ); } else if(event.getSource() == italicsItem){ font = new Font( "Serif", Font.ITALIC, 14 ); } else if(event.getSource() == boldItalicsItem){ font = new Font( "Serif", Font.BOLD + Font.ITALIC, 14 ); } textField.setFont( font ); } public static void main( String[] args ) { MenuFrame checkBoxFrame = new MenuFrame(); checkBoxFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); checkBoxFrame.setSize( 275, 100 ); checkBoxFrame.setVisible( true ); } Page 75

76 JDesktopPane and JInternalFrame  Allow you to display child windows inside main/parent windows  Create Desktop pane inside JFrame:  Create an internal frame: or define a class that extend JInternalFrame and then: JInternalFrame internalFrame = new LoginInternalFrame();  Add internal frame to Desktop pane: Page 76 JDesktopPane theDesktop; theDesktop = new JDesktopPane(); add( theDesktop ); // add desktop pane to JFrame JInternalFrame internalFrame = new JInternalFrame("Internal Frame", true, true, true, true ); theDesktop.add( internalFrame ); // attach internal frame

77 Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 77

78 Complete Example public class DesktopFrameDemo extends JFrame { private JDesktopPane theDesktop; public DesktopFrameDemo() { super( "Using a JDesktopPane" ); JMenuBar bar = new JMenuBar(); // create menu bar JMenu addMenu = new JMenu( "Add" ); // create Add menu JMenuItem newFrameItem = new JMenuItem( "Internal Frame" ); addMenu.add( newFrameItem ); // add new frame item to Add menu bar.add( addMenu ); // add Add menu to menu bar setJMenuBar( bar ); // set menu bar for this application ActionListener newFrameMenuItemlistener = new NewFrameMenuItemListner(); newFrameItem.addActionListener(newFrameMenuItemlistener); theDesktop = new JDesktopPane(); // create desktop pane add( theDesktop ); // add desktop pane to frame } class NewFrameMenuItemListner implements ActionListener { public void actionPerformed(ActionEvent event){ JInternalFrame frame = new JInternalFrame( "Internal Frame", true, true, true, true ); frame.setSize(200,200); theDesktop.add( frame ); // attach internal frame frame.setVisible( true ); // show internal frame frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); } public static void main( String[] args ){ DesktopFrameDemo desktopFrame = new DesktopFrameDemo(); desktopFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); desktopFrame.setSize( 600, 480 ); // set frame size desktopFrame.setVisible( true ); // display frame } Page 78

79 Programming Question 1. Modify CheckBoxFrame.java so that it extends JInternalFrame (instead of JFrame). Save this file as CheckBoxInternalFrame.java.  Change constructor to accept: String title, boolean resizable, boolean closable, boolean maximizable, boolean iconifiable 2. Create a class DesktopFrame that extends JFrame with a menu “File” that has a menu item “Acess Internal Frame”.  Clicking on menu item should result in displaying a internal frame (CheckBoxInternalFrame)  Clicking on close button of internal frame should close the internal frame. Page 79 Find program Template next slide

80 public class DesktopFrame extends JFrame { private JDesktopPane theDesktop; public DesktopFrame() { super( "Using a JDesktopPane" ); //TODO: create menu bar //TODO: create Add menu //TODO: create menu item : newFrameItem //TODO: add newFrameItem to Add menu //TODO: add Add menu to menu bar //TODO: set menu bar for this application //TODO: create desktop pane //TODO: add desktop pane to frame //TODO: set up listener for newFrameItem } class NewFrameMenuItemListner implements ActionListener { public void actionPerformed(ActionEvent event) { //TODO: create internal frame //TODO: set internal frame to size of contents //TODO: add internal frame to desktop pane //TODO: show internal frame frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); //set default close operation of internal frame } public static void main( String[] args ) { DesktopFrame desktopFrame = new DesktopFrame(); desktopFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); desktopFrame.setSize( 600, 480 ); // set frame size desktopFrame.setVisible( true ); // display frame } Page 80

81 Answer import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JInternalFrame; import javax.swing.JTextField; import javax.swing.JCheckBox; public class CheckBoxInternalFrame extends JInternalFrame { private JTextField textField; // displays text in changing fonts private JCheckBox boldJCheckBox; // to select/deselect bold private JCheckBox italicJCheckBox; // to select/deselect italic private ActionListener listener; public CheckBoxInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable, boolean iconifiable) { super( title, resizable, closable, maximizable, iconifiable); setLayout( new FlowLayout() ); // set frame layout // set up JTextField and set its font textField = new JTextField( "Watch the font style change", 20 ); textField.setFont( new Font( "Serif", Font.PLAIN, 14 ) ); add( textField ); // add textField to JFrame boldJCheckBox = new JCheckBox( "Bold" ); // create bold checkbox italicJCheckBox = new JCheckBox( "Italic" ); // create italic add( boldJCheckBox ); // add bold checkbox to JFrame add( italicJCheckBox ); // add italic checkbox to JFrame // register listeners for JCheckBoxes listener = new CheckBoxListner(); boldJCheckBox.addActionListener( listener ); italicJCheckBox.addActionListener( listener ); } Page 81 CheckBoxInternalFrame.java

82 class CheckBoxListner implements ActionListener { public void actionPerformed(ActionEvent event) { Font font = null; // stores the new Font // determine which CheckBoxes are checked and create Font if ( boldJCheckBox.isSelected() && italicJCheckBox.isSelected() ) font = new Font( "Serif", Font.BOLD + Font.ITALIC, 14 ); else if ( boldJCheckBox.isSelected() ) font = new Font( "Serif", Font.BOLD, 14 ); else if ( italicJCheckBox.isSelected() ) font = new Font( "Serif", Font.ITALIC, 14 ); else font = new Font( "Serif", Font.PLAIN, 14 ); textField.setFont( font ); // set textField's font } Page 82

83 import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.Random; import javax.swing.JFrame; import javax.swing.JDesktopPane; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JInternalFrame; public class DesktopFrame extends JFrame { private JDesktopPane theDesktop; public DesktopFrame() { super( "Using a JDesktopPane" ); JMenuBar bar = new JMenuBar(); // create menu bar JMenu addMenu = new JMenu( "Add" ); // create Add menu JMenuItem newFrameItem = new JMenuItem( "Internal Frame" ); addMenu.add( newFrameItem ); // add new frame item to Add menu bar.add( addMenu ); // add Add menu to menu bar setJMenuBar( bar ); // set menu bar for this application theDesktop = new JDesktopPane(); // create desktop pane add( theDesktop ); // add desktop pane to frame // set up listener for newFrame menu item ActionListener newFrameMenuItemlistener = new NewFrameMenuItemListner(); newFrameItem.addActionListener(newFrameMenuItemlistener); } Page 83 DesktopFrame.java

84 class NewFrameMenuItemListner implements ActionListener { public void actionPerformed(ActionEvent event) { JInternalFrame frame = new CheckBoxInternalFrame( "Internal Frame", true, true, true, true ); frame.pack(); // set internal frame to size of contents theDesktop.add( frame ); // attach internal frame frame.setVisible( true ); // show internal frame frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); } public static void main( String[] args ) { DesktopFrame desktopFrame = new DesktopFrame(); desktopFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); desktopFrame.setSize( 600, 480 ); // set frame size desktopFrame.setVisible( true ); // display frame } Page 84

85 Creating Password Text  Create variable of type JPasswordField field: JPasswordField passwordField;  Create JPasswordField object: passwordField = new JPasswordField( "Hidden text" );  Add ActionListner: passwordField.addActionListener( listener);  listener should check user name and password typed in by user matches entry in a password database or file.  Get typed in password: char[] password = passwordField.getPassword(); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 85

86 Programming Question  Modify DesktopFrame.java to add one more menu item (Login).  Clicking on the login button should display a Internal frame for login (LoginInternalFrame.java should be implemented by student)  Clicking on the Login button should validate user against a logins.txt and display message “successful login” or “unsuccessful login”logins.txt http://www.users.csbsju.edu/~rdissanayaka/courses/f14/csci160/handouts/ch19/logins.txt  Hint : to compare two char arrays use Arrays class: Arrays.equals (charArray1, charArray2); Page 86 Find program Template next slide

87 public class LoginInternalFrame extends JInternalFrame { private JLabel userLabel; //user label private JTextField userTextField; // user text filed private JLabel passwordLabel; //user label private JPasswordField passwordField; // password field with text private JButton loginButton; //login button private JButton cancelButton; //cancel button String userName; char[] password; public LoginInternalFrame() { super("Login", true, true, true, true ); //TODO: set layout //TODO: create and add labels, text boxes and buttons //TODO: register action listener for login button and cancel button } private class LoginHandler implements ActionListener { public void actionPerformed( ActionEvent event ) { if ( event.getSource() == loginButton ) { //TODO: get username and passowrd entered by user //TODO: open logins.txt file and look for a matching username and passord //TODO: if found match, display message”successful login” and clear text fields. } else if( event.getSource() == cancelButton ) { setVisible(false); } Page 87

88 Answer import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.Random; import javax.swing.JFrame; import javax.swing.JDesktopPane; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JInternalFrame; public class DesktopFrame2 extends JFrame { private JDesktopPane theDesktop; public DesktopFrame2() { super( "Using a JDesktopPane" ); JMenuBar bar = new JMenuBar(); // create menu bar JMenu addMenu = new JMenu( "Add" ); // create Add menu JMenuItem newFrameItem = new JMenuItem( "Internal Frame" ); JMenuItem loginFrameItem = new JMenuItem( "Login" ); addMenu.add( newFrameItem ); // add new frame item to Add menu addMenu.add( loginFrameItem ); // add new frame item to Add menu bar.add( addMenu ); // add Add menu to menu bar setJMenuBar( bar ); // set menu bar for this application theDesktop = new JDesktopPane(); // create desktop pane add( theDesktop ); // add desktop pane to frame // set up listener for newFrame menu item ActionListener newFrameMenuItemlistener = new NewFrameMenuItemListner(); newFrameItem.addActionListener(newFrameMenuItemlistener); ActionListener loginMenuItemlistener = new LoginMenuItemListner(); loginFrameItem.addActionListener(loginMenuItemlistener); } Page 88 DesktopFrame2.java

89 Answer class NewFrameMenuItemListner implements ActionListener { public void actionPerformed(ActionEvent event) { JInternalFrame frame = new CheckBoxInternalFrame( "Internal Frame", true, true, true, true ); frame.pack(); // set internal frame to size of contents theDesktop.add( frame ); // attach internal frame frame.setVisible( true ); // show internal frame frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); } class LoginMenuItemListner implements ActionListener { public void actionPerformed(ActionEvent event) { JInternalFrame loginFrame = new LoginInternalFrame(); loginFrame.pack(); // set internal frame to size of contents theDesktop.add( loginFrame ); // attach internal frame loginFrame.setVisible( true ); // show internal frame loginFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); } public static void main( String[] args ) { DesktopFrame2 desktopFrame = new DesktopFrame2(); desktopFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); desktopFrame.setSize( 600, 480 ); // set frame size desktopFrame.setVisible( true ); // display frame } Page 89

90 Answer import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JButton; import javax.swing.JTextField; import javax.swing.JPasswordField; import javax.swing.JOptionPane; import javax.swing.JInternalFrame; import java.util.Scanner; import java.awt.GridLayout; import java.io.File; import java.util.Arrays; public class LoginInternalFrame extends JInternalFrame { private JLabel userLabel; //user label private JTextField userTextField; // user text filed private JLabel passwordLabel; //user label private JPasswordField passwordField; // password field with text private JButton loginButton; //login button private JButton cancelButton; //cancel button String userName; char[] password; Page 90 LoginInternalFrame.java

91 Answer public LoginInternalFrame() { super("Login", true, true, true, true ); setLayout( new GridLayout(3,2) ); userLabel = new JLabel("User Name: "); passwordLabel = new JLabel("Password: "); userTextField = new JTextField( 10 ); passwordField = new JPasswordField( 10 ); loginButton = new JButton("Login"); cancelButton = new JButton("Cancel"); getContentPane().add(userLabel); getContentPane().add(userTextField); getContentPane().add(passwordLabel); getContentPane().add(passwordField); getContentPane().add(loginButton); getContentPane().add(cancelButton); LoginHandler handler = new LoginHandler(); loginButton.addActionListener( handler ); cancelButton.addActionListener( handler ); } Page 91 LoginInternalFrame.java

92 private class LoginHandler implements ActionListener { public void actionPerformed( ActionEvent event ){ if ( event.getSource() == loginButton ){ userName = userTextField.getText(); password = passwordField.getPassword(); boolean foundMatch = false; try { Scanner sc = new Scanner(new File("logins.txt")); while(sc.hasNext() && !foundMatch){ String[] entry = sc.next().split(","); System.out.println("user: "+userName+ " entry[0]: "+entry[0]); System.out.println("password: "+password+ " entry[1]: "+entry[1]); if( Arrays.equals (entry[0].toCharArray(), userName.toCharArray()) && Arrays.equals (entry[1].toCharArray(), password)){ foundMatch = true; break; } if(!foundMatch){ JOptionPane.showMessageDialog( null, "Unsuccessful Login","Failed Login", JOptionPane.ERROR_MESSAGE ); userTextField.setText(""); passwordField.setText(""); } else{ JOptionPane.showMessageDialog( null, "Successful Login","Successful Login", JOptionPane.INFORMATION_MESSAGE ); setClosed( true ); } catch(Exception e){ e.printStackTrace(); } else if( event.getSource() == cancelButton ){ setVisible(false); } Page 92

93  Project: 1.Your project should have a main menu window that display all functions available for user as menus/menu items Initially should have only login menu item should be enabled. A User first select login menu item and login. Upon successful login, other menu items (register for course, enter grades etc.) should be enabled. Log off button can save changes to files and reset main menu frame to only enable login menu item. 2.I need to see multiple scenarios handled per function E.g. GUI for registering a student a course (successful registration, prerequisites not satisfied, enrolled in similar etc.) 3.I need to see content of files before and after changes made by user Page 93

94 Sample GUI for project Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 94 File Student Professor Login Logoff Close Display/Find StudentDisplay/Find Professor Display Teaching Assignments Display Course Schedule Add section Drop section View Transcript Display Student Roster Agree to teach a course x

95 Student  Find Student Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 95 File Student Professor x x Find Student Enter Student Name Name: SSN: Major: Degree: FindAddEdit

96 JTable  display tables of data, optionally allowing the user to edit the data.  does not contain or cache data; it is simply a view of your data.  View demo: http://docs.oracle.com/javase/tutorialJWS/samples/uiswing/SimpleTableDem oProject/SimpleTableDemo.jnlp http://docs.oracle.com/javase/tutorialJWS/samples/uiswing/SimpleTableDem oProject/SimpleTableDemo.jnlp Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 96

97 Example import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingUtilities; public class TableExample extends JFrame{ public TableExample() { String[] columns = new String[] { "Id", "Name", "Hourly Rate", "Part Time" }; //table headers //actual data for the table in a 2d array Object[][] data = new Object[][] { {1, "John", 40.0, false }, {2, "Rambo", 70.0, false }, {3, "Zorro", 60.0, true }, }; JTable table = new JTable(data, columns); //create table with data this.add(new JScrollPane(table)); //add the table to the frame this.setTitle("Table Example"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.pack(); } public static void main(String[] args{ new TableExample().setVisible(true); } Page 97

98 JLists  A list displays a series of items from which the user may select one or more items  created with class JList  supports :  Single-selection lists allow only one item to be selected at a time  Multiple-selection lists allow any number of items to be selected Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 98

99 Example import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.*; public class JListDemo extends JFrame { JList list; String[] listColorNames = { "black", "blue", "green", "yellow", "white" }; Color[] listColorValues = { Color.BLACK, Color.BLUE, Color.GREEN, Color.YELLOW, Color.WHITE }; public JListDemo() { super("List Source Demo"); getContentPane().setLayout(new FlowLayout()); list = new JList(listColorNames); list.setSelectedIndex(0); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); getContentPane().add(new JScrollPane(list)); list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { getContentPane().setBackground(listColorValues[list.getSelectedIndex()]); } }); setSize(200, 200); setVisible(true); } public static void main(String[] args) { JListDemo test = new JListDemo(); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }

100 JTree  display hierarchical data.  has a 'root node' which is the top-most parent for all nodes in the tree.  A node is an item in a tree.  A node can have many children nodes. These children nodes themselves can have further children nodes.  If a node doesn't have any children node, it is called a leaf node.  Expanding a node displays the children and collapsing hides them. Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 100

101 Example import javax.swing.JFrame; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.tree.DefaultMutableTreeNode; public class TreeExample extends JFrame { private JTree tree; public TreeExample() { //create the root node DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root"); //create the child nodes DefaultMutableTreeNode vegetableNode = new DefaultMutableTreeNode("Vegetables"); DefaultMutableTreeNode fruitNode = new DefaultMutableTreeNode("Fruits"); //add the child nodes to the root node root.add(vegetableNode); root.add(fruitNode); //create the tree by passing in the root node tree = new JTree(root); add(tree); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("JTree Example"); this.pack(); this.setVisible(true); } Page 101

102 public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new TreeExample(); } }); } Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 102

103 JTabbedPane  Arranges GUI components into layers, of which only one is visible at a time.  Users access each layer via a tab  When the user clicks a tab, the appropriate layer is displayed.  The tabs appear at the top by default  Any component can be placed on a tab. Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 103

104 Example import java.awt.BorderLayout; import java.awt.Color; import javax.swing.JFrame; import javax.swing.JTabbedPane; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.SwingConstants; public class JTabbedPaneFrame extends JFrame { // set up GUI public JTabbedPaneFrame() { super( "JTabbedPane Demo " ); JTabbedPane tabbedPane = new JTabbedPane(); // create JTabbedPane // set up pane11 and add it to JTabbedPane JLabel label1 = new JLabel( "panel one", SwingConstants.CENTER ); JPanel panel1 = new JPanel(); // create first panel panel1.add( label1 ); // add label to panel tabbedPane.addTab( "Tab One", null, panel1, "First Panel" ); // set up panel2 and add it to JTabbedPane JLabel label2 = new JLabel( "panel two", SwingConstants.CENTER ); JPanel panel2 = new JPanel(); // create second panel panel2.add( label2 ); // add label to panel tabbedPane.addTab( "Tab Two", null, panel2, "Second Panel" ); Page 104 JTabbedPaneFrame.java Continued 

105 // set up panel3 and add it to JTabbedPane JLabel label3 = new JLabel( "panel three" ); JPanel panel3 = new JPanel(); // create third panel panel3.setLayout( new BorderLayout() ); // use borderlayout panel3.add( new JButton( "North" ), BorderLayout.NORTH ); panel3.add( new JButton( "West" ), BorderLayout.WEST ); panel3.add( new JButton( "East" ), BorderLayout.EAST ); panel3.add( new JButton( "South" ), BorderLayout.SOUTH ); panel3.add( label3, BorderLayout.CENTER ); tabbedPane.addTab( "Tab Three", null, panel3, "Third Panel" ); add( tabbedPane ); // add JTabbedPane to frame } // end JTabbedPaneFrame constructor } Page 105

106 Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 106 import javax.swing.JFrame; public class JTabbedPaneDemo { public static void main( String[] args ) { JTabbedPaneFrame tabbedPaneFrame = new JTabbedPaneFrame(); tabbedPaneFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); tabbedPaneFrame.setSize( 300, 300 ); // set frame size tabbedPaneFrame.setVisible( true ); // display frame } // end main } // end class JTabbedPaneDemo JTabbedPaneDemo.java

107  Find out more:  BoxLayout  GridBagLayout  Jpopup menus Page 107

108 References:  http://www.codejava.net/java-se/swing/jtree- basic-tutorial-and-examples http://www.codejava.net/java-se/swing/jtree- basic-tutorial-and-examples Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 108

109 Swing vs AWT  AWT is Java’s original set of classes for building GUIs  Uses peer components of the OS; heavyweight  Not truly portable: looks different and lays out inconsistently on different OSs Due to OS’s underlying display management system  Swing is designed to solve AWT’s problems  99% java; lightweight components Drawing of components is done in java Uses 4 of AWTs components –Window, frame, dialog, ?  Lays out consistently on all OSs  Uses AWT event handling

110 Common GUI Event Types and Listener Interfaces  Many different types of events can occur when the user interacts with a GUI.  The event information is stored in an object of a class that extends AWTEvent (from package java.awt)  These event types are used with both AWT and Swing components.  Additional event types that are specific to Swing GUI components are declared in package javax.swing.event. Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 110

111 Some event classes in package java.awt.event Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 111

112 Some common event listener interfaces in java.awt.event Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 112 Handle ActionEvents Handle MouseEvents Handle KeyEvents

113 Which listener(s) a GUI component supports?  You can tell what kinds of events a component can fire by looking at the kinds of event listeners you can register on it.  E.g. the JComboBox class defines these listener registration methods:  addActionListener  addItemListener  addPopupMenuListener  Thus, a combo box supports action, item, and popup menu listeners in addition to the listener methods it inherits from JComponent. Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 113

114 From: https://docs.oracle.com/javase/tutorial/uiswing/events/eventsandcomponents.html Page 114

115  Implementing Listeners for Commonly Handled Events  https://docs.oracle.com/javase/tutorial/uiswing/ev ents/handling.html https://docs.oracle.com/javase/tutorial/uiswing/ev ents/handling.html Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 115

116 ActionEventListnener  How to Write an Action Listener  Action listeners are probably the easiest and most common event handlers to implement.  You implement an action listener to define what should be done when an user performs certain operation.  An action event occurs, whenever an action is performed by the user.  Examples: When the user clicks a button,button chooses a menu item,menu item presses Enter in a text field.text field  The result is that an actionPerformed message is sent to all action listeners that are registered on the relevant component. Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 116

117 Example ActionListener Implementation import java.awt.*; import java.awt.event.*; public class AL extends Frame implements WindowListener,ActionListener { TextField text = new TextField(20); Button b; private int numClicks = 0; public static void main(String[] args) { AL myWindow = new AL("My first window"); myWindow.setSize(350,100); myWindow.setVisible(true); } public AL(String title) { super(title); setLayout(new FlowLayout()); addWindowListener(this); //ladd windowlistener to this frame: windowsClosing(WindowsEvent e) b = new Button("Click me"); add(b); add(text); b.addActionListener(this); //add action listener to button, actionPerformed(ActionEvent e) } public void actionPerformed(ActionEvent e) { numClicks++; text.setText("Button Clicked " + numClicks + " times"); } public void windowClosing(WindowEvent e) { dispose(); System.exit(0); } public void windowOpened(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowClosed(WindowEvent e) {} } Page 117

118 ItemListener  How to Write an Item Listener  Item events are fired by components that implement the ItemSelectable interface.ItemSelectable  Generally, ItemSelectable components maintain on/off state for one or more items.  The Swing components that fire item events include buttons like: check boxes, check boxes check menu items,check menu items toggle buttons combo boxes.combo boxes Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 118

119 Example import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ItemEventDemo extends JPanel implements ItemListener { static JFrame frame; JLabel label; String newline = "\n"; public ItemEventDemo() { super(new BorderLayout()); JPanel panel = new JPanel(new BorderLayout()); label = new JLabel("This is a label", JLabel.CENTER); panel.add(label, BorderLayout.CENTER); JCheckBox checkbox = new JCheckBox("Label visible", true); checkbox.addItemListener(this); panel.add(checkbox, BorderLayout.PAGE_END); add(panel, BorderLayout.PAGE_END); } public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { label.setVisible(true); label.revalidate(); //Need to revalidate and repaint, or else the label will probably be drawn in the wrong place. label.repaint(); } else { label.setVisible(false); } private static void createAndShowGUI() { frame = new JFrame("ItemEventDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JComponent newContentPane = new ItemEventDemo(); newContentPane.setOpaque(true); //content panes must be opaque frame.setContentPane(newContentPane); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } Page 119


Download ppt "Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar with common."

Similar presentations


Ads by Google