Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS-0401 INTERMEDIATE PROGRAMMING USING JAVA

Similar presentations


Presentation on theme: "CS-0401 INTERMEDIATE PROGRAMMING USING JAVA"— Presentation transcript:

1 CS-0401 INTERMEDIATE PROGRAMMING USING JAVA Prof. Dr. Paulo Brasko Ferreira Spring 2015

2 Chapter 12 Java Graphical User Interface

3 Pop Quiz !!! What is the difference between these three types of classes? Regular classe Abstract Classe Interface

4 You will learn how to do this GUI in this chapter

5 Creating our First Window

6 Steps to create a window
Steps to create a window (“Frame” in Java terms) Create a new frame object with “new Frame( )” JFrame frame = new JFrame(); Set its title frame.setTitle("A Simple Window"); Set its size frame.setSize(200, 300); Set its default close operation frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Set it visible frame.setVisible(true); See SimpleWindow

7 Creating and Adding Components into a Frame

8 Process of adding components
GUI components panel frame

9 How to create GUI components
ObjectType objectName = new ObjectType(args); Examples: JButton submitRequestButton = new JButton(“Submit”); JLabel label1 = new JLabel(“File Name: ”); JTextField textField = new JTextField(20);

10 Creating the JPanel and adding components
JPanel panel = new JPanel ( ); panel.add(submitRequestButton); panel.add(textField); panel.add(label1);

11 Adding the panel into the frame
frame.add(panel); frame.visible(true); See KiloConverterWindowPhase_1

12 Handling Events with Action Listeners

13 Events and Action Listeners
An event is a user interaction with your GUI Examples of events: A click of a mouse button Window being resized Typing words in a text area Selecting an option in a drop-down list An Action Listener is an object that responds to these events I was clicked! Button Event Assigned Action Listener

14 Action Listener An Action Listener is an object that responds to the events We need to create a new class just to be a listener of a given event! Object of what Class???

15 Creating an Event Listener Class

16 Creating an Event Listener
Action Listener needs to be an object of a new class The class will be placed inside your class (inner class) public class YourRegularClass { private void yourRegularMethods() // doing some cool stuff here } private class Inner // doing some other cool stuff here

17 Let’s create a JButton action listener class
Adding an inner class Let’s create a JButton action listener class Create this class at the end of your class, but before the last curly bracket: private class MyButtonListener implements ActionListener { // do your calculations here } Implements???

18 Interface??? Wow, it is getting more and more complicated!
Time-out!!! “Implements” means that we are going to provide a code (an implementation) for a given interface Interface??? Wow, it is getting more and more complicated!

19 Interface An Interface is a java file containing only method definitions, but no implementation: Example:

20 Interfaces Interface just define the methods signature:
Public type Returning type Method name Input arguments Interface does not implement the method

21 A specific method in your program
Interfaces Interfaces are like contracts! Both parties must agree and obey the rules defined in the contract I’ll call a method of your program I’ll handle that! A specific method in your program Java Virtual Machine I have been pressed Button Pressed

22 Java Development Team at Sun Systems
But What Method? Java Development Team at Sun Systems Is it the same as Jared’s? What is Mara’s method name? It would be nice it they use the same method name

23 Action Listener Interface
public interface ActionListener extends EventListener { public void actionPerformed(ActionEvent e); }

24 Action Listener Interface
You: “I promise to have such a method in my code” Java Team: “We will call your actionPerformed”

25 Action Listener Interface
private class CalcButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) // your code here to handle the action // like converting kilometers to miles }

26 How Events are Handled Action Listener Object
JButton Component actionPerformed(ActionEvent e) #1: The Mouse Clicks the Button #2: JButton Generates an Event #3: JVM receives the event and calls the action listener object’s actionPerformed method #4: actionPerformed method does whatever you have programmed

27 What you must do Create a JButton and register a listener to it
button1.addActionListener(new MyButtonListener()) Create an inner class inside your class and add the keywords “implements ActionListener” private class ButtonListener implements ActionListener Add the method defined in that interface (ActionListener) public void actionPerformed(ActionEvent e) Code inside this method whatever functionality is wanted See KiloConverterWindow_Phase_2

28 How do we retrieve the text from the JTextField?
JTextField kiloTextField = new JTextField(); input = kiloTextField.getText(); miles = Double.parseDouble(input) * ; JOptionPane.showMessageDialog(null, input + " kilometers is " + miles + " miles.");

29 GUI with multiple buttons

30 GUI with multiple buttons
How would you implement action listeners for all three buttons? Two ways: Creating three inner classes, one for each action listener See code ColorWindow.java Creating one inner class and figure out which button has generated the event by using ActionEvent e See code ColorWindow2.java

31 Layout Managers

32 Layout Managers Run program ColorWindow.java
Resize the window in many different ways What happen? Who is responsible for organizing the GUI components all the time?

33 Meet the Layout Manager!

34 Layout Managers Layout manager is an object that governs components’
Position Sizes The programmer does not normally specify the exact location of a component He/she just add the component into the panel panel.add(button1); panel.add(button2); panel.add(button3); panel.add(button4);

35 Layout Managers How to use a layout manager:
You designate a layout for a given panel: JPanel panel = new JPanel(); BorderLayout layout = new BorderLayout(); panel.setLayout(layout); panel.setLayout(new BorderLayout());

36 Types of Layout Managers

37 Flow Layout Manager

38 Sample: ColorWindow.java
Flow Layout Manager FlowLayout layout = new FlowLayout(); myPanel.setLayout(layout); After Resizing Arranges components of different sizes in rows Flow layout is the default layout manager for JPanels What does it mean? You can add as many components into the container as you want (no limit) You can include other panels inside a panel as well What happen if you resize the window during run-time? Sample: ColorWindow.java

39 FlowLayout Constructors
Constructs a new FlowLayout with a centered alignment and a default 5-unit horizontal and vertical gap FlowLayout layout = new FlowLayout( ); Sample: ColorWindow.java

40 FlowLayout Constructors
FlowLayout(int align): Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical gap. Align options: FlowLayout.LEADING (left alignment) FlowLayout.CENTER (default) FlowLayout.TRAILING (rigtht alignment) FlowLayout layout = new FlowLayout(FlowLayout.LEADING); Sample: ColorWindow.java

41 FlowLayout Constructors
FlowLayout(int align, int hgap, int vgap): Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps. FlowLayout layout = new FlowLayout(FlowLayout. LEADING, 20, 50); Sample: ColorWindow.java

42 Border Layout Manager

43 Border Layout Manager Panel is separated by regions
North, South, West, East, Center Jframe’s default layout manager You can add only 5 components

44 Sample: BorderWindow.java
Border Layout Manager Example: JPanel panel = new JPanel( ); panel.setLayout(new BorderLayout( )); JButton button1 = new JButton(“Click me”); panel.add(button1, BorderLayout.NORTH); JButton button2 = new JButton(“Submit”); panel.add(button2); JButton button3 = new JButton(“Cancel”); panel.add(button3); In what regions will button2 and button3 be added? Sample: BorderWindow.java

45 Can I create this window with lots of components using Border Layout?
Nesting components Can I create this window with lots of components using Border Layout?

46

47 Rules governing Border Layout
North and South regions: Component will be resized horizontally to fills up the entire region West, Center, East regions: Component will be resized vertically to fills up the entire region

48 Rules governing Border Layout
No need to place a component in all the regions Regions will shrink and expand as necessary You can adjust vertical and Horizontal gaps BorderLayout (int horizontalGap, int verticalGap); panel.setLayout(new BorderLayout(5,10)); BorderWindow.java

49 How can we avoid the buttons to get stretched?
BorderPanelWindow.java How can we avoid the buttons to get stretched?

50 Grid Layout Manager

51 Grid Layout Manager Divides the container into cells (like in Excel spreadsheets) GridLayout(int rows, int columns) new GridLayout(2 , 3); No need to place a component in all the cells One component per cell The cells are filled up in the order that you add components There is no way of specifying cell location

52 How to create this GUI?

53 More about GUI components
STOP

54 Radio Buttons

55 Radion Buttons How radio buttons work?
If I click on “Regular coffee” should it remove my Bagel selection?

56 Grouping Radio Buttons
Creating the radio buttons JRadioButton radio1 = new JRadioButton(“None”); JRadioButton radio2 = new JRadioButton(“Decaf”); JRadioButton radio3 = new JRadioButton(“Regular”); Group them together ButtonGroup group = new ButtonGroup( ); group.add(radio1); group.add(radio2); group.add(radio3); You still need to add the buttons into a JPanel panel.add(radio1); panel.add(radio2); panel.add(radio3); See CoffeePanel.java

57 Check Radio Button Programmatically
During the definition of the button: regularCoffee = new JRadioButton("Regular coffee", true); During run-time: cappuccino.setSelected(true); cappuccino.doClick( );

58 Taking action as a radio button is clicked
Depending on your application, you might want to add listeners to each of your radio buttons As soon as the radio button is selected you can take some action Like disabling some other components in your GUI Veteran? Some discounts might be available See MetricConverterWindow.java

59 Adding listener for a radion button
milesButton.addActionListener(new RadioButtonListener()); private class RadioButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) if (e.getSource() == milesButton) // do stuff here }

60 Just checking if the button is selected
public double getCoffeeCost() { double coffeeCost = 0.0; if (noCoffee.isSelected()) coffeeCost = NO_COFFEE; else if (regularCoffee.isSelected()) coffeeCost = REGULAR_COFFEE; else if (decafCoffee.isSelected()) coffeeCost = DECAF_COFFEE; else if (cappuccino.isSelected()) coffeeCost = CAPPUCCINO; return coffeeCost; }

61 Check Boxes

62 Check Boxes JCheckBox myCB = new JCheckBox(“Butter”);
JCheckBox myCB = new JCheckBox(“Cream”, true);

63 Responding to CheckBox Event
You must implement the ItemListener interface private Class MyInnerClass implements ItemListener You must implement the method itemStateChanged ( ) public void itemStateChanged(ItemEvent e) See ColorCheckBoxWindow.java

64 Checking programmatically if a checkbox is checked
To check if a checkbox has been selected during run-time: public boolean checkBox.isSelected() Example: if (myCheckBox.isSelected()) { // do some stuff here } See ToppingPanel.java

65 Borders

66 What is a Border Factory???
The Border Class A component can appear with several different styles of borders around it A Border object specifies the details of a border You use the BorderFactory class to create a border object panel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); What is a Border Factory???

67 Border Factory A factory class is a class that provides different types of objects based on the specifications you give to it as input argument

68 Border Factory

69 Examples Border blackline, raisedetched, loweredetched, raisedbevel, loweredbevel, empty; blackline = BorderFactory.createLineBorder(Color.black); raisedetched = BorderFactory.createEtchedBorder(EtchedBorder.RAISED); loweredetched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED); raisedbevel = BorderFactory.createRaisedBevelBorder(); loweredbevel = BorderFactory.createLoweredBevelBorder(); empty = BorderFactory.createEmptyBorder(); jComp1.setBorder(blackline); jComp2.setBorder(raisedbevel); jComp3.setBorder(loweredbevel); jComp4.setBorder(empty);

70 The Brandi’s Bagel House
See CoffeePanel.java


Download ppt "CS-0401 INTERMEDIATE PROGRAMMING USING JAVA"

Similar presentations


Ads by Google