CS-0401 INTERMEDIATE PROGRAMMING USING JAVA Prof. Dr. Paulo Brasko Ferreira Spring 2015
Chapter 12 Java Graphical User Interface
Pop Quiz !!! What is the difference between these three types of classes? Regular classe Abstract Classe Interface
You will learn how to do this GUI in this chapter
Creating our First Window
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
Creating and Adding Components into a Frame
Process of adding components GUI components panel frame
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);
Creating the JPanel and adding components JPanel panel = new JPanel ( ); panel.add(submitRequestButton); panel.add(textField); panel.add(label1);
Adding the panel into the frame frame.add(panel); frame.visible(true); See KiloConverterWindowPhase_1
Handling Events with Action Listeners
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
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???
Creating an Event Listener Class
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
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???
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!
Interface An Interface is a java file containing only method definitions, but no implementation: Example:
Interfaces Interface just define the methods signature: Public type Returning type Method name Input arguments Interface does not implement the method
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
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
Action Listener Interface public interface ActionListener extends EventListener { public void actionPerformed(ActionEvent e); }
Action Listener Interface You: “I promise to have such a method in my code” Java Team: “We will call your actionPerformed”
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 }
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
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
How do we retrieve the text from the JTextField? JTextField kiloTextField = new JTextField(); input = kiloTextField.getText(); miles = Double.parseDouble(input) * 0.6214; JOptionPane.showMessageDialog(null, input + " kilometers is " + miles + " miles.");
GUI with multiple buttons
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
Layout Managers
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?
Meet the Layout Manager!
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);
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());
Types of Layout Managers
Flow Layout Manager
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
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
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
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
Border Layout Manager
Border Layout Manager Panel is separated by regions North, South, West, East, Center Jframe’s default layout manager You can add only 5 components
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
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?
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
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
How can we avoid the buttons to get stretched? BorderPanelWindow.java How can we avoid the buttons to get stretched?
Grid Layout Manager
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
How to create this GUI?
More about GUI components STOP
Radio Buttons
Radion Buttons How radio buttons work? If I click on “Regular coffee” should it remove my Bagel selection?
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
Check Radio Button Programmatically During the definition of the button: regularCoffee = new JRadioButton("Regular coffee", true); During run-time: cappuccino.setSelected(true); cappuccino.doClick( );
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
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 }
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; }
Check Boxes
Check Boxes JCheckBox myCB = new JCheckBox(“Butter”); JCheckBox myCB = new JCheckBox(“Cream”, true);
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
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
Borders
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???
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
Border Factory
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);
The Brandi’s Bagel House See CoffeePanel.java