Graphical User Interfaces 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 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 Sample GUI From: Java How To Program – Dietel & Dietel The menus, buttons and combo box are part of the application’s GUI. They enable you to interact with the application. Page 4 Simple GUI-Based Input/Output with JOptionPane To interact with the user, applications use: dialog boxes • Classes: JOptionPane Windows OR • classes: JFrame, JPanel Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 5 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 6 Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 7 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. 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 ); } } Page 8 Get user input: If user click OK button: Return user input as string If user click CANCEL button: Returns null Display output: parentComponent=null : center message in screen Page 10 Sample output from program: Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 11 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 My First Frame X Enter Student ID : panel1 panel2 Student Transcript: PRINT Copyright © 2014 by John Wiley & Sons. All rights reserved. frame CANCEL CLEAR panel3 Page 13 JFrame Class Example empty JFrame window (with no GUI components inside): 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); } } Page 14 Output: Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 15 Example JFrame with a GUI object(JLabel) added: import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.Container; public class MyFrame2 extends JFrame { public MyFrame2(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) { MyFrame2 f = new MyFrame2("My Second Frame"); f.setVisible(true); } } Page 16 Output: Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 17 JPanel Class Example JFrame with a JPanel objects containing other JLabel objects: import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JLabel; public class MyFrame3 extends JFrame { public MyFrame3(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) { MyFrame3 f = new MyFrame3("My Third Frame"); f.setSize(200,200); f.setVisible(true); } } Page 18 Output: Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 19 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 Components are added to a container which uses a layout manager to place them Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 20 Flow Layout Components are added from left to right panel = new JPanel(); panel.add(rateLabel); panel.add(rateField); panel.add(button); panel.add(resultLabel); A JPanel uses flow layout by default Try reducing width of Jframe in previous window (100.200) Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 21 Example: import import import import javax.swing.JFrame; javax.swing.JPanel; javax.swing.JLabel; 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 panel.add(new panel.add(new panel.add(new panel.add(new panel.add(new JLabel("One")); JLabel("Two")); JLabel("Three")); JLabel("Four")); JLabel("Five")); JLabel("Six")); getContentPane().add(panel); } public static void main(String[] args) { FlowLayoutFrame f = new FlowLayoutFrame("FlowLayoutDemo"); f.setSize(300,300); f.setVisible(true); } } Page 22 Output: Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 23 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); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 24 Programming Question Write class BorderLayoutFrame.java that generate following output with 5 buttons in a border layout: Hint: to create a button: new JButton(“North") Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 25 Example import import import import javax.swing.JFrame; javax.swing.JPanel; javax.swing.JButton; java.awt.BorderLayout; public class BorderLayoutFrame extends Jframe { Comment line where you add JButton to SOUTH and run 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); } } Page 26 Grid Layout Components are placed in boxes in a simple table arrangement Specify the size (rows then columns) of the grid JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4, 3)); 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); . . . Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 27 Programming Question Write class GridLayoutDemo.java to generate following output Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 28 Example import import import import javax.swing.JFrame; javax.swing.JPanel; javax.swing.JButton; 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 getContentPane().add(new getContentPane().add(new getContentPane().add(new getContentPane().add(new getContentPane().add(new getContentPane().add(new getContentPane().add(new getContentPane().add(new getContentPane().add(new getContentPane().add(new getContentPane().add(new JButton("7")); JButton("8")); JButton("9")); JButton("4")); JButton("5")); JButton("6")); JButton("1")); JButton("2")); JButton("3")); JButton("0")); JButton(".")); JButton("CE")); } public static void main(String[] args) { GrdLayoutFrame f = new GrdLayoutFrame("GrdLayout Demo"); f.setVisible(true); } } Page 29 Output: Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 30 Question Which layout manager would be suitable for each component? Get Transcript X Enter Student ID : frame panel1 Student Transcript: panel2 PRINT CANCEL CLEAR panel3 Page 31 Answer Get Transcript X Enter Student ID : Frame (BorderLayout) Panel1 (FlowLayout ) In Frame.NORTH Student Transcript: Panel2 (GridLayout) In Frame.CENTER PRINT CANCEL CLEAR Panel3 (FlowLayout) In Frame.SOUTH Page 32 Programming Question Write a program CalculatorFrame that generates following GUI: Hint: Creating a text field: Find program template in next slide JTextField display = new JTextField(); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 33 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 Which layout manager will work best? Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 35 calculatorPanel JPanel(BorderLayout) display JTextField = CalculatorPanel.NORTH keyPanel Jpanel = CalculatorPanel.CENTER (GridLayout) Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 36 Answer import import import import import import javax.swing.JFrame; javax.swing.JPanel; javax.swing.JButton; javax.swing.JTextField; java.awt.BorderLayout; 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); } } Page 37 Output: Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 38 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 final int FIELD_WIDTH = 10; final JTextField rateField = new JTextField(FIELD_WIDTH); A Label helps the user know what you want Normally to the left of a textbox Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 39 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 rateLabel JLable rateField JTextField button JButton resultLabel JLable InvestmentFrame JFrame Code to execute when button is clicked: double rate = Double.parseDouble(rateField.getText()); double interest = account.getBalance() * rate / 100; account.deposit(interest); resultLabel.setText("balance: " + account.getBalance()); Page 40 Example import import import import import import import java.awt.event.ActionEvent; java.awt.event.ActionListener; javax.swing.JButton; javax.swing.JFrame; javax.swing.JLabel; javax.swing.JPanel; 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 private private private private JLabel rateLabel; JTextField rateField; JButton button; JLabel resultLabel; double balance; Continued next page Page 41 Example 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 Page 42 Example /** INNER CLASS 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); } } Page 43 Text Areas Create multi-line text areas with a JTextArea object Set the size in rows and columns final int ROWS = 10; final int COLUMNS = 30; JTextArea textArea = new JTextArea(ROWS, COLUMNS); Use the setText method to set the text of a text field or text area textArea.setText(“Account Balance”); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 44 Text Areas The append method adds text to the end of a text area • Use newline characters to separate lines textArea.append(account.getBalance() + "\n"); Use the setEditable method to control user input textArea.setEditable(false); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 45 JTextField and JTextArea To add scroll bars, use JScrollPane: JScrollPane scrollPane = new JScrollPane(textArea); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 46 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 Answer import import import import import import import import import java.awt.event.ActionEvent; java.awt.event.ActionListener; javax.swing.JButton; javax.swing.JFrame; javax.swing.JLabel; javax.swing.JPanel; javax.swing.JScrollPane; javax.swing.JTextArea; 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 private private private private JLabel rateLabel; JTextField rateField; JButton button; JTextArea resultArea; double balance; Continued next page Page 48 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); Continued next page } Page 49 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 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 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 Grouping Radio Buttons Add Radio Buttons into a ButtonGroup so that only one button in the group is selected at a time Create the JRadioButtons 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); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 53 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: JPanel panel = new JPanel(); panel.add(smallButton); panel.add(mediumButton); panel.add(largeButton); panel.setBorder(new TitledBorder(new EtchedBorder(),"Size")); There are a large number of border styles available • See the Swing documentation for more details Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 54 Example : no button group, no border Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 55 Example: With Button Group Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 56 Example: with border Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 57 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 JRadioButton largeButton = new JRadioButton("Large"); largeButton.setSelected(true); Call the isSelected method of each button to find out which one it is currently selected if (largeButton.isSelected()) { size = LARGE_SIZE; } Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 58 Selecting Check Boxes To setup a Check Box, use Swing JCheckBox JCheckBox italicCheckBox = new JCheckBox("Italic"); Call the isSelected method of a checkbox to find out whether it is currently selected or not if (italicCheckBox.isSelected()) { style = style + Font.ITALIC } Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 59 Combo Boxes Add text ‘items’ to a combo box that will show in the list: JComboBox facenameCombo = new JComboBox(); facenameCombo.addItem("Serif"); facenameCombo.addItem("SansSerif"); . . . 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: String selectedString = (String) facenameCombo.getSelectedItem(); Copyright © 2014 by John Wiley & Sons. All rights reserved. Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 60 Page 60 Example Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 61 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) faceNamePanel(JPanel) controlPanel(JPanel: fontFrame.SOUTH) styleGroupPanel(JPanel) sizeGroupPanel(JPanel) 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: Find Class template In next slide textField.setFont( new Font( "Serif", Font.PLAIN, 14 ) ); textField.setFont( new Font( "Serif", Font.PLAIN+Font.ITALIC, 14 ) ); Page 63 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 64 Answer import import import import import import import CheckBoxFrame.java java.awt.FlowLayout; java.awt.Font; java.awt.event.ActionEvent; java.awt.event.ActionListener; javax.swing.JFrame; javax.swing.JTextField; javax.swing.JCheckBox; public class CheckBoxFrame extends JFrame { private private private private JTextField textField; // displays text in changing fonts JCheckBox boldJCheckBox; // to select/deselect bold JCheckBox italicJCheckBox; // to select/deselect italic 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 65 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 66 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 67 Answer import import import import import import import import RadioButtonFrame.java java.awt.FlowLayout; java.awt.Font; java.awt.event.ActionEvent; java.awt.event.ActionListener; javax.swing.JFrame; javax.swing.JTextField; javax.swing.JRadioButton; 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 68 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 69 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 70 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 . . . } } Page 71 MenuBar and Menu Items The MenuBar contains Menus • Add JMenu objects to the MenuBar ( E.g. a file menu, a Edit menue etc. ) JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenu fontMenu = new JMenu("Font"); menuBar.add(fileMenu); menuBar.add(fontMenu); A Menu contains SubMenus and Menu items • A Menu item has no further SubMenus JMenuItem exitItem = new JMenuItem("Exit"); filemenu.add(exitItem); Page 72 Menu Item Events Add action listeners to each Menu item JMenuItem item = new JMenuItem(name); ActionListener listener = new FaceItemListener(); item.addActionListener(listener); The listener is customized for each Menu item Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 73 FaceEvent ActionListener (2) Listener Inner Class version 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 Page 74 Programming Question Write class MenuFrame java that generates the following font viewer Find Class template In next slide Selecting a menu item should change font in text field appropriately Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 75 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 76 Answer import import import import import import import import import import MenuFrame.java java.awt.FlowLayout; java.awt.Font; java.awt.event.ActionEvent; java.awt.event.ActionListener; javax.swing.JFrame; javax.swing.JTextField; javax.swing.JCheckBox; javax.swing.JMenuBar; javax.swing.JMenu; 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 77 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 78 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 79 Project: 1. Your project should have a main menu window that display all functions available for user as menus/menu items File Student Professor Login Display/Find Student Logoff Display Course Schedule Display Teaching Assignments Close Add section Drop section Display/Find Professor Display Student Roster Agree to teach a course View Transcript Page 80 Project: 1. You are required to implement following: • Desktop pane with (at least) student menu • Implement following menu items: – Find student » Show FindStudent Internal Frame » When user enter student id, display name, major, transcript etc. – Display course schedule » Show AddDropSection Internal Frame » When user enter student id, and click on display, display course schedule. – Add Section » Show AddDropSection Internal Frame » When user enter student id, and section details and press enroll button, enrolls and/or print error/success messages and update files – Drop Section » Show AddDropSection Internal Frame » When user enter student id, and section details and click drop button, drops and/or print error/success messages and update files Page 81 Project: 2. I need you to demonstrate multiple scenarios handled per function • Add Section/enroll – 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 82 Student Find Student File Student x Professor Find Student x Enter Student ID Name: SSN: Major: Degree: Find Copyright © 2014 by John Wiley & Sons. All rights reserved. Add Edit Page 83 JDesktopPane and JInternalFrame Allow you to display child windows inside main/parent windows Create Desktop pane inside JFrame: JDesktopPane theDesktop = new JDesktopPane(); add( theDesktop ); // add desktop pane to JFrame Create an internal frame: JInternalFrame internalFrame = new JInternalFrame("Internal Frame", true, true, true, true ); or define a class that extend JInternalFrame and then: JInternalFrame internalFrame = new LoginInternalFrame(); Add internal frame to Desktop pane: theDesktop.add( internalFrame ); // attach internal frame Page 84 Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 85 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 86 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. Find program Template next slide Page 87 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 88 Answer import import import import import import import CheckBoxInternalFrame.java java.awt.FlowLayout; java.awt.Font; java.awt.event.ActionEvent; java.awt.event.ActionListener; javax.swing.JInternalFrame; javax.swing.JTextField; 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 89 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 90 DesktopFrame.java import import import import import import import import import import import import java.awt.BorderLayout; java.awt.Dimension; java.awt.Graphics; java.awt.event.ActionListener; java.awt.event.ActionEvent; java.util.Random; javax.swing.JFrame; javax.swing.JDesktopPane; javax.swing.JMenuBar; javax.swing.JMenu; javax.swing.JMenuItem; 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 91 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 92 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 93 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” • http://www.users.csbsju.edu/~rdissanayaka/courses/f14/csci160/handouts/ch19/logins.txt Find program Template next slide Hint : to compare two char arrays use Arrays class: Arrays.equals (charArray1, charArray2); Page 94 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 95 Answer import import import import import import import import import import import import DesktopFrame2.java java.awt.BorderLayout; java.awt.Dimension; java.awt.Graphics; java.awt.event.ActionListener; java.awt.event.ActionEvent; java.util.Random; javax.swing.JFrame; javax.swing.JDesktopPane; javax.swing.JMenuBar; javax.swing.JMenu; javax.swing.JMenuItem; 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 96 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 97 Answer import import import import import import import import import import import import import LoginInternalFrame.java java.awt.event.ActionListener; java.awt.event.ActionEvent; javax.swing.JFrame; javax.swing.JLabel; javax.swing.JButton; javax.swing.JTextField; javax.swing.JPasswordField; javax.swing.JOptionPane; javax.swing.JInternalFrame; java.util.Scanner; java.awt.GridLayout; java.io.File; 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 98 Answer LoginInternalFrame.java 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 99 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 100 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 Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 101 Example import import import import javax.swing.JFrame; javax.swing.JScrollPane; javax.swing.JTable; 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 102 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 103 Example import import import import import javax.swing.*; javax.swing.event.ListSelectionEvent; javax.swing.event.ListSelectionListener; java.awt.*; 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); } } 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 105 Example import import import import javax.swing.JFrame; javax.swing.JTree; javax.swing.SwingUtilities; 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 106 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 107 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 108 Example import import import import import import import import JTabbedPaneFrame.java java.awt.BorderLayout; java.awt.Color; javax.swing.JFrame; javax.swing.JTabbedPane; javax.swing.JLabel; javax.swing.JPanel; javax.swing.JButton; 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" ); Continued Page 109 // 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 110 JTabbedPaneDemo.java 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 Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 111 Find out more: BoxLayout GridBagLayout Jpopup menus Page 112 References: http://www.codejava.net/java-se/swing/jtreebasic-tutorial-and-examples Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 113 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 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 115 Some event classes in package java.awt.event Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 116 Some common event listener interfaces in java.awt.event Handle ActionEvents Handle KeyEvents Handle MouseEvents Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 117 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 118 From: https://docs.oracle.com/javase/tutorial/uiswing/events/eventsandcomponents.html Page 119 Implementing Listeners for Commonly Handled Events https://docs.oracle.com/javase/tutorial/uiswing/ev ents/handling.html Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 120 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, • chooses a menu item, • presses Enter in a 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 121 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 122 ItemListener How to Write an Item Listener Item events are fired by components that implement the ItemSelectable interface. 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 menu items, toggle buttons combo boxes. Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 123 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 124