Presentation is loading. Please wait.

Presentation is loading. Please wait.

Graphical User Interfaces

Similar presentations


Presentation on theme: "Graphical User Interfaces"— 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.

3 Introduction Graphical User Interface (GUI): GUI Component:
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. Javax vs java: originally javax was intended to be for extensions, and sometimes things would be promoted out of javax into java. One issue was Netscape (and probably IE) limiting classes that could be in the java package. When Swing was set to "graduate" to java from javax there was sort of a mini-blow up because people realized that they would have to modify all of their imports. Given that backwards compatibility is one of the primary goals of Java they changed their mind. At that point in time, at least for the community (maybe not for Sun) the whole point of javax was lost. So now we have some things in javax that probably should be in java... but aside from the people that chose the package names I don't know if anyone can figure out what the rationale is on a case-by-case basis. The javax namespace is usually (that's a loaded word) used for standard extensions, currently known as optional packages. The standard extensions are a subset of the non-core APIs; the other segment of the non-core APIs obviously called the non-standard extensions, occupying the namespaces like com.sun.* or com.ibm.. The core APIs take up the java. namespace. Not everything in the Java API world starts off in core, which is why extensions are usually born out of JSR requests. They are eventually promoted to core based on 'wise counsel'. The interest in this nomenclature, came out of a faux pas on Sun's part - extensions could have been promoted to core, i.e. moved from javax.* to java.* breaking the backward compatibility promise. Programmers cried hoarse, and better sense prevailed. This is why, the Swing API although part of the core, continues to remain in the javax.* namespace. And that is also how packages get promoted from extensions to core - they are simply made available for download as part of the JDK and JRE. Backward binary compatibility (or downward compatibility) - an ability of clients built with an old version of library API to run on a new one (wiki). Upward binary compatibility (or forward compatibility) - an ability of clients built with a new version of library API to run on old one (wiki). Historically, the idea was that java.* packages would be the ones that shipped with the JDK, and the javax.* packages would be the ones that have to be downloaded separately. It still does work this way, to an extent; all java.* packages come with the JDK, and there are many javax.* packages, like for servlets, that have to be downloaded separately. A monkey wrench was thrown into this scheme when Sun decided to move some javax.* packages, like Swing, into the main JDK. They were actually going to change the package name from javax.swing to java.swing, but when it became clear that this would break backwards compatibility for a huge amount of code, they decided instead to move the packages in, but keep the javax.swing name. So the name is no longer indicative, but is there for historical reasons. It wouldn't surprise me if the same thing happened to the org.omg and org.w3c packages (they were third-party libraries that got moved into the core JDK and the names couldn't be changed). Regardless, if it's in the JDK API docs, you can use it without downloading anything apart from the main JDK, and the class loader will find it just fine

4 Sample GUI The menus, buttons and combo box are
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.

5 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.

6 Simple GUI-Based Input/Output with JOptionPane
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.

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

8 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 ); }

9 Get user input: If user click OK button: Return user input as string
If user click CANCEL button: Returns null

10 Display output: parentComponent=null : center message in screen

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

12 Windows 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 import javax.swing.*; JPanel p = new JPanel(); JLabel l1 = new JLabel("Panel label"); p.add(l1); p.setVisible(true); 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.

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

14 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);

15 Output: Copyright © 2014 by John Wiley & Sons. All rights reserved.

16 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);

17 Output: Copyright © 2014 by John Wiley & Sons. All rights reserved.

18 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);

19 Output: Copyright © 2014 by John Wiley & Sons. All rights reserved.

20 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.

21 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 ( ) Copyright © 2014 by John Wiley & Sons. All rights reserved.

22 Example: 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);

23 Output: Copyright © 2014 by John Wiley & Sons. All rights reserved.

24 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.

25 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") Find program template in next slide Copyright © 2014 by John Wiley & Sons. All rights reserved.

26 Template 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); //TODO: Create Border layout and add buttons } public static void main(String[] args) BorderLayoutFrame f = new BorderLayoutFrame("BorderLayout Demo"); f.setVisible(true);

27 Example Comment line where you add JButton to SOUTH and run
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

28 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.

29 Programming Question Write class GridLayoutDemo.java to generate following output Find program template in next slide Copyright © 2014 by John Wiley & Sons. All rights reserved.

30 Template 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); //TODO: create button panel } public static void main(String[] args) GrdLayoutFrame f = new GrdLayoutFrame("GrdLayout Demo"); f.setVisible(true);

31 Example 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);

32 Output: Copyright © 2014 by John Wiley & Sons. All rights reserved.

33 Question Which layout manager would be suitable for each component?
frame Get Transcript X Enter Student ID : panel1 Student Transcript: panel2 PRINT CANCEL CLEAR panel3

34 Answer X Enter Student ID : Student Transcript: PRINT CANCEL CLEAR
Frame (BorderLayout) Get Transcript X Enter Student ID : Panel1 (FlowLayout ) In Frame.NORTH Student Transcript: Panel2 (GridLayout) In Frame.CENTER PRINT CANCEL CLEAR Panel3 (FlowLayout) In Frame.SOUTH

35 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.

36 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.

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

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

39 Answer 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); Answer

40 Output: Copyright © 2014 by John Wiley & Sons. All rights reserved.

41 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); Copyright © 2014 by John Wiley & Sons. All rights reserved.

42 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());

43 Example Continued next page  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 

44 Example Continued next page  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 

45 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);

46 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); textArea.setText(“Account Balance”); Copyright © 2014 by John Wiley & Sons. All rights reserved.

47 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 textArea.append(account.getBalance() + "\n"); textArea.setEditable(false); Copyright © 2014 by John Wiley & Sons. All rights reserved.

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

49 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.

50 Answer Continued next page 
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; Continued next page 

51 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 

52 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);

53 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.

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

55 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.

56 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")); Copyright © 2014 by John Wiley & Sons. All rights reserved.

57 Example : no button group, no border
Copyright © 2014 by John Wiley & Sons. All rights reserved.

58 Example: With Button Group
Copyright © 2014 by John Wiley & Sons. All rights reserved.

59 Example: with border Copyright © 2014 by John Wiley & Sons. All rights reserved.

60 Complete code import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.ButtonGroup; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; public class RadioButtonDemoFrame extends JFrame { public RadioButtonDemoFrame(String title) super(title); 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); JCheckBox italicCheckBox = new JCheckBox("Italic"); JComboBox facenameCombo = new JComboBox(); facenameCombo.addItem("Serif"); facenameCombo.addItem("SansSerif"); JPanel panel = new JPanel(); panel.add(smallButton); panel.add(mediumButton); panel.add(largeButton); panel.setBorder(new TitledBorder(new EtchedBorder(),"Size")); panel.add(italicCheckBox); panel.add(facenameCombo); add(panel); setSize(300,300); } public static void main(String args[]) RadioButtonDemoFrame frame = new RadioButtonDemoFrame("Radio Buttons"); frame.setVisible(true); Copyright © 2014 by John Wiley & Sons. All rights reserved.

61 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); if (largeButton.isSelected()) { size = LARGE_SIZE; } Copyright © 2014 by John Wiley & Sons. All rights reserved.

62 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 } Copyright © 2014 by John Wiley & Sons. All rights reserved.

63 Combo Boxes 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"); . . . String selectedString = (String) facenameCombo.getSelectedItem(); Copyright © 2014 by John Wiley & Sons. All rights reserved. Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 63

64 Example Copyright © 2014 by John Wiley & Sons. All rights reserved.

65 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)

66 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 ) ); Find Class template In next slide

67 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

68 Answer CheckBoxFrame.java
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 ); } What is the difference between adding an element to a JFrame as opposed to a Container?  The code is: jframe.getContentPane().add(button); // the same result occurs for JButton button = new JButton("no difference"); JFrame jframe = new JFrame("no difference"); jframe.add(button); getContentPane returns a Container object. What is the point of adding button to the Container if it works equally well with the JFrame? Why bother coding jframe.getContentPane().add(button); if we can do jframe.add(button); frame.add(button) did not used to be equivalent, for what reason I never did know. But the JFrame has several associated containers, and the ContentPane is the one where one would (normally) want a button to go. So you need to put it in the content pane, you used to have to do it explicitly, and now they've made it more convenient with the add method on JFrame itself. ContentPane (or Content Pain?) Content pane border. There are several ways to handle the content pane, but most of them fail to provide one basic requirement -- ability to set a border. If you look at design guidelines (eg, Sun's Java Look and Feel Design Guidelines, Second Edition) and actual practice for attractive windows (both JFrames and JDialogs), you will generally observe the following: JFrames have a content pane, which holds the components. These components are sized and positioned by the layout manager when JFrame's pack() is called. The problem is that the Container class doesn't have a way to set borders. Borders appear on most windows that are filled with controls. For example, the typical dialog box or secondary window has a relatively wide (eg, 12 pixel) border, and similarly for primary windows that have a fixed size. No, or thin, borders. Windows with a large editing or display area often have no or very thin borders. Users want to have as big a working area as possible. To better understand the situation, it's good to have the inheritance of some of these containers in mind. Inheritance hierarchy JPanel->JComponentsetBorder(...)->Containeradd(...)  setLayout(...)->Component->ObjectDifferent approaches to using the content pane Create a JPanel. Set the content pane - My favorite.class GUI extends JFrame { GUI() { JPanel content = new JPanel(); content.setLayout(...); content.setBorder(BorderFactory.createEmptyBorder(11,11,11,11)); content.add(...); content.add(...); setContentPane(content);Get content pane, work with it. Problem: Unable to set border.class GUI extends JFrame { GUI() { Container content = getContentPane(); content.setBorder(BorderFactory.createEmptyBorder(11,11,11,11)); content.setLayout(...); content.add(...); content.add(...); . . .Use getContentPane for every reference. Problem: Unable to set border.class GUI extends JFrame { GUI() { getContentPane().setLayout(...); getContentPane().setBorder(BorderFactory.createEmptyBorder(11,11,11,11)); getContentPane().add(...); getContentPane().add(...); . . .Use Java 5 JFrame pass-through methods. See Blast from the past discussion below.class GUI extends JFrame { GUI() { setLayout(...); setBorder(BorderFactory.createEmptyBorder(11,11,11,11)); add(...); add(...); . . .Why I prefer to create a new content pane You will see all of these approaches used by different programmers. They are all reasonable. Choose the one which makes you most comfortable. They all assume that the code occurs inside of a JFrame subclass constructor or method (ie, this refers to the JFrame). Irony. getContentPane() returns a Container object. This isn't really a plain Container object, but is actually aJPanel! This is a Container as a consequence of the hierarchy. So if we get the predefined content pane, it turns out it's actually a JPanel, but we really can't take advantage of the functionality that was added by JComponent. If we downcast it to JPanel, we create fragile code that might break because the contract with getContentPane() is to return a Container, and there is no guarantee that future versions will actually continue to return a JPanel. Reason: Restrictions on Container. If you try to use the returned Container from getContentPane(), you can't use setBorder(...). Every JFrame comes with a pre-created content pane. What a waste. Reason: What is the default layout? And just what is the default layout for a JFrame's content pane? Is it the same as for an Applet or a newly created JPanel? Surprisingly they aren't the same. And the default was changed in different versions (admittedly you have to go way back to find this change). So I recommend not relying on the default layout. Always explicitly set for the content pane, even if you use the predefined one. Reason: Generality of one programming style. The overall layout of a window is often created by nesting panels. If you're going to be creating panels and working with them, it's easier to treat them all the same rather than making the top-level content pane a special case. And just in case you thought the default layout was BorderLayout, as the documentation says, you might be surprised that it is really an anonymous inner subclass of BorderLayout. I haven't bothered to look at the source code to figure out why they just didn't use a normal BorderLayout, but it makes me nervous. I hate these FUD(Fear, Uncertainty, Doubt) arguments, but it's what I feel when thinking about the default layouts. And the final layout issue is that you should be using a better layout than BorderLayout anyway. Long ago, before the Swing GUI library, there was no content pane and components were added directly to the window (the old AWT Frame class). Blast from the past - Adding directly to a JFrame in Java 5 Reason to use predefined content pane: efficiency? Creating a JPanel can't be very expensive, but it does cost some execution time. This small one-time cost is worth it. Java 5? For some reason, Java 5 added the ability to use the content pane by creating add() and setLayout() inJFrame which pass-through calls to the underlying content pane so it looks like the old AWT code. Maybe they did this because are request has been on the request queue for a really long time, and it was trivial to implement. Maybe it was just someone's pet project. Swing. When the superior Swing GUI library came along, it was easy, but annoying, to rewrite code to use Swing's content pane. That was long ago, and for most of Java's history programmers have been using the content pane explicitly. They defined add() methods in JFrame which simply call the corresponding add() methods for the content pane. It seems strange to add this feature now, especially since many layouts use multiple nested panels so you still have to be comfortable with adding directly to a JPanel. And not everything you want to do with the content pane can be done through calls to the JFrame. Raising cognitive complexity with useless options increases every programmer's burden a little bit because they always have to be prepared to deal with this alternative when reading code. Worse than useless. There are lots of ways to make Swing more usable; adding this "feature" seems like a waste of manpower and adds yet more unneeded alternatives. They regularly reject useful additional features because they are concerned about the growing size of the Java API. So... I suggest giving the content pane JPanel a name that lets the reader know it is the content pane. The namecontent, which is probably used by more programmers than any other name. Suggested practice: Name the content pane "content" It's your time, waste it if you want to. There is no problem if you want to use this feature, but why get in the habit of using this minimally useful alternative when you have to know how to explicitly deal with a JPanel for many layouts anyway? 2007

69 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

70 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.

71 Answer RadioButtonFrame.java
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

72 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 ); }

73 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

74 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 . . . }

75 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); JMenuItem exitItem = new JMenuItem("Exit"); filemenu.add(exitItem);

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

77 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

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

79 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 );

80 Answer MenuFrame.java 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;

81 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 ); }

82 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 );

83 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: JDesktopPane 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

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

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

86 Programming Question 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 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

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

88 Answer CheckBoxInternalFrame.java
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 ); }

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 }

90 DesktopFrame.java 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); }

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

92 Project: Your project should have a main menu window that display all functions available for user as menus/menu items File Student Professor Login Logoff Close Display/Find Student Display/Find Professor Display Teaching Assignments Display Course Schedule Add section Drop section View Transcript Display Student Roster Agree to teach a course

93 Project: 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 When user enter student id, and section details and press enroll button, enrolls and/or print error/success messages and update files Drop Section When user enter student id, and section details and click drop button, drops and/or print error/success messages and update files

94 Project: I need you to demonstrate multiple scenarios handled per function Add Section/enroll successful registration, prerequisites not satisfied enrolled in similar etc. I need to see content of files before and after changes made by user

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

96 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.

97 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” Hint : to compare two char arrays use Arrays class: Arrays.equals (charArray1, charArray2); Find program Template next slide

98 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);

99 Answer DesktopFrame2.java
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); }

100 Answer { public void actionPerformed(ActionEvent event)
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 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

101 Answer LoginInternalFrame.java
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;

102 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 ); }

103 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);

104 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: Copyright © 2014 by John Wiley & Sons. All rights reserved.

105 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);

106 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.

107 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);

108 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.

109 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); }

110 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.

111 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.

112 Example JTabbedPaneFrame.java Continued 
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" ); Continued 

113 // 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 }

114 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.

115 Find out more: BoxLayout GridBagLayout Jpopup menus

116 References: Copyright © 2014 by John Wiley & Sons. All rights reserved.

117 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 AWT vs Swing When developing a Java program it is important to select the appropriate Java Graphical User Interface (GUI) components. There are two basic sets of components that you will most likely build your Java programs with. These two groups of components are called the Abstract Window Toolkit (AWT) and Swing. Both of these groups of components are part of the Java Foundation Classes (JFC). An Overview of the AWT AWT stands for Abstract Window ToolKit. The Abstract Window Toolkit supports GUI Java programming. It is a portable GUI library for stand-alone applications and/or applets. The Abstract Window Toolkit provides the connection between your application and the native GUI. The AWT provides a high level of abstraction for your Java program since it hides you from the underlying details of the GUI your program will be running on. AWT features include: A rich set of user interface components. A robust event-handling model. Graphics and imaging tools, including shape, color, and font classes. Layout managers, for flexible window layouts that don't depend on a particular window size or screen resolution. Data transfer classes, for cut-and-paste through the native platform clipboard. The AWT components depend on native code counterparts (called peers) to handle their functionality. Thus, these components are often called "heavyweight" components. An Overview of Swing Swing implements a set of GUI components that build on AWT technology and provide a pluggable look and feel. Swing is implemented entirely in the Java programming language, and is based on the JDK 1.1 Lightweight UI Framework. Swing features include: All the features of AWT. 100% Pure Java certified versions of the existing AWT component set (Button, Scrollbar, Label, etc.). A rich set of higher-level components (such as tree view, list box, and tabbed panes). Pure Java design, no reliance on peers. Pluggable Look and Feel. Swing components do not depend on peers to handle their functionality. Thus, these components are often called "lightweight" components. AWT vs. Swing There are, of course, both pros and cons to using either set of components from the JFC in your Java applications. Here is a summary: AWT: Pros Speed: use of native peers speeds component performance. Applet Portability: most Web browsers support AWT classes so AWT applets can run without the Java plugin. Look and Feel: AWT components more closely reflect the look and feel of the OS they run on. ConsPortability: use of native peers creates platform specific limitations. Some components may not function at all on some platforms. Third Party Development: the majority of component makers, including Borland and Sun, base new component development on Swing components. There is a much smaller set of AWT components available, thus placing the burden on the programmer to create his or her own AWT-based components. Features: AWT components do not support features like icons and tool-tips. Swing: Pros Portability: Pure Java design provides for fewer platform specific limitations. Behavior: Pure Java design allows for a greater range of behavior for Swing components since they are not limited by the native peers that AWT uses. Features: Swing supports a wider range of features like icons and pop-up tool-tips for components. Vendor Support: Swing development is more active. Sun puts much more energy into making Swing robust. Look and Feel: The pluggable look and feel lets you design a single set of GUI components that can automatically have the look and feel of any OS platform (Microsoft Windows, Solaris, Macintosh, etc.). It also makes it easier to make global changes to your Java programs that provide greater accessibility (like picking a hi-contrast color scheme or changing all the fonts in all dialogs, etc.). ConsApplet Portability: Most Web browsers do not include the Swing classes, so the Java plugin must be used. Performance: Swing components are generally slower and buggier than AWT, due to both the fact that they are pure Java and to video issues on various platforms. Since Swing components handle their own painting (rather than using native API's like DirectX on Windows) you may run into graphical glitches. Look and Feel: Even when Swing components are set to use the look and feel of the OS they are run on, they may not look like their native counterparts. In general, AWT components are appropriate for simple applet development or development that targets a specific platform (i.e. the Java program will run on only one platform). For most any other Java GUI development you will want to use Swing components. Also note that the Borland value-added components included with JBuilder, like dbSwing and JBCL, are based on Swing components so if you wish to use these components you will want to base your development on Swing.

118 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.

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

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

121 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.

122 From: https://docs. oracle

123 Implementing Listeners for Commonly Handled Events
Copyright © 2014 by John Wiley & Sons. All rights reserved.

124 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.

125 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) {}

126 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.

127 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(); });


Download ppt "Graphical User Interfaces"

Similar presentations


Ads by Google