Post on 02-Apr-2015
Page w16.1 – Spring 2010 Steffen Vissing Andersen
SDJ I1 subjects, Spring 2010
Agenda – Week 16, 2010
• GUI
Page w16.2 – Spring 2010 Steffen Vissing Andersen
GUI - elements
• Which GUI elements can you recognize here?
Page w16.3 – Spring 2010 Steffen Vissing Andersen
Components used
JFrame
JLabelJTextField
JButton
TitleBorder
JCheckBox JRadioButton ButtonGroup
Page w16.4 – Spring 2010 Steffen Vissing Andersen
What is a GUI?
• Has at least one window• A Frame
• The window has at least one container• The content pane
• All visible components are added to a container
• A container is an invisible component that holds other components and containers
Page w16.5 – Spring 2010 Steffen Vissing Andersen
Top Level Containers
• Top-level containers• To appear on a screen, every GUI component must be
part of a containment hierarchy. A containment hierarchy is a tree of components that has a top-level container as its root
• Can hold a menu bar
• Types of Top Level Contaniers• JFrame
• Normal window with Caption bar• JDialog• JApplet
Caption barCaption bar
Content pane
Page w16.6 – Spring 2010 Steffen Vissing Andersen
JFrame – the Window
• The topmost GUI component• A standalone application with a Swing-based GUI has at
least one containment hierarchy with a JFrame as its root
• Components are added to the Frames content pane• getContentPane() returns the default content pane of
the Frame• setContentPane(contentPane) adds another kind of
Content Pane
Page w16.7 – Spring 2010 Steffen Vissing Andersen
An Example: A simple window (compostition)
import javax.swing.JFrame;
public class ASimpleWindow1 { private JFrame win;
public ASimpleWindow1() { win = new JFrame("A Simple window");
win.setSize(400, 300); win.setVisible(true);
// Specify what happens when the window are closed // Exit the application win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
Page w16.8 – Spring 2010 Steffen Vissing Andersen
An Example: A simple window (inheritance)
import javax.swing.JFrame;
public class ASimpleWindow2 extends JFrame {
public ASimpleWindow2() { super("A Simple window 2");
setSize(300, 200); setVisible(true);
// Specify what happens when the window are closed setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
Page w16.9 – Spring 2010 Steffen Vissing Andersen
Content Pane
• Content pane typical a JPanel• Here the visual components are placed• Can have its own layout• Can be added as a component to other containers
(JPanel’s etc.)
JPanel mainPanel = new JPanel();JPanel subPanel1 = new JPanel();JPanel subPanel2 = new JPanel();mainPanel.add(subPanel1);mainPanel.add(subPanel2);add(mainPanel);
mainPanel
subPanel1
subPanel2
Page w16.10 – Spring 2010 Steffen Vissing Andersen
Panels used
JPanel w. BoarderLayout
JPanel w. BoxLayout
JPanel w. GridLayout
JPanel w. GridLayout
JPanel’s w. FlowLayout
JPanel w. FlowLayout
Page w16.11 – Spring 2010 Steffen Vissing Andersen
User event
• How does the program reacts on user event?
Page w16.12 – Spring 2010 Steffen Vissing Andersen
How to react on user action
• A user can manipulate with all the GUI components every time the GUI is visible!
• How to implement a program that can handle this?
• We need to look at the way a program is executed
Page w16.13 – Spring 2010 Steffen Vissing Andersen
Normal program flow
method 2
method 1
method 3
Page w16.14 – Spring 2010 Steffen Vissing Andersen
Event driven programming
• Your applications have until now been executed by following the program structure you have implemented
• A GUI is an event driven program• User event are the trigger for executing small
parts of your application• Event and Action listeners
• These listeners are added to the individual GUI components
Page w16.15 – Spring 2010 Steffen Vissing Andersen
Event driven program flow
Page w16.16 – Spring 2010 Steffen Vissing Andersen
Components ready to use
• Take a look at this link:
• http://java.sun.com/docs/books/tutorial/ui/features/components.html
Page w16.17 – Spring 2010 Steffen Vissing Andersen
Layout Managers
• Used to help us with the layout of components in a container
• We will take a look at a few of them here
Page w16.18 – Spring 2010 Steffen Vissing Andersen
FlowLayout
• The components are put in a row until the right border and then continue on the next row
• This is the default layout of JPanel
Page w16.19 – Spring 2010 Steffen Vissing Andersen
GridLayout
• The components are put in rows and columns• You decide the number of rows and columns
Page w16.20 – Spring 2010 Steffen Vissing Andersen
BorderLayoyt
• Components are put in five different areas
North
East
SouthCenter
West
Page w16.21 – Spring 2010 Steffen Vissing Andersen
Layout’s used
BoarderLayout
Page w16.22 – Spring 2010 Steffen Vissing Andersen
Layout’s used
JPanel w. FlowLayoutJPanel w. BorderLayout
Page w16.23 – Spring 2010 Steffen Vissing Andersen
Layout’s used
JPanel w. FlowLayout
Page w16.24 – Spring 2010 Steffen Vissing Andersen
Layout’s used
JPanel w. BoxLayout
Page w16.25 – Spring 2010 Steffen Vissing Andersen
Layout’s used
JPanel w. GridLayout
Page w16.26 – Spring 2010 Steffen Vissing Andersen
Layout’s used
JPanel w. FlowLayout
Page w16.27 – Spring 2010 Steffen Vissing Andersen
Layout’s used
A Frame (or panel) with Borderlayout- A label in north- A Flowlayout panel in center (with 3 panels)
- A Boxlayout panel (with labels and checkboxes)- A Gridlayout panel (with radiobuttons) - A Gridlayout panel (with 3 panels)
- 3 Flowlayout panels (each with a label and a text field)- A Borderlayout panel in south (with a panel in east)
- A Flowlayout panel (with 2 buttons)
Page w16.28 – Spring 2010 Steffen Vissing Andersen
Compress your window – pack()
Before pack()
After pack()
Page w16.29 – Spring 2010 Steffen Vissing Andersen
Temperature conversion – GUI example (1/7)
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class FrameTemperature extends JFrame{ private JLabel labelTemp; private JTextField textFieldTemp; private JButton buttonToCelcius; private JButton buttonToFahrenheit;
public FrameTemperature() { super("Temperature conversion"); createComponents(); initializeComponents(); registerEventHandlers(); addComponentsToFrame(); }
Page w16.30 – Spring 2010 Steffen Vissing Andersen
Temperature conversion – GUI example (2/7)
private void createComponents() { textFieldTemp = new JTextField(6); labelTemp = new JLabel("Temperature:"); buttonToCelcius = new JButton("To Celcius"); buttonToFahrenheit = new JButton("To Fahrenheit"); }
private void initializeComponents() { setSize(300, 120); // set frame size setVisible(true); setLocationRelativeTo(null); // center of the screen setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); textFieldTemp.setText("");}
Page w16.31 – Spring 2010 Steffen Vissing Andersen
Temperature conversion – GUI example (3/7)
private void registerEventHandlers() { ButtonHandler handler = new ButtonHandler(); buttonToCelcius.addActionListener(handler); buttonToFahrenheit.addActionListener(handler); }
Note: Event Handler class ButtonHandler is a private inner class
Page w16.32 – Spring 2010 Steffen Vissing Andersen
Temperature conversion – GUI example (4/7)
private void addComponentsToFrame() { JPanel panelDegree = new JPanel(new BorderLayout()); panelDegree.add(labelTemperature, BorderLayout.NORTH); panelDegree.add(textFieldTempe, BorderLayout.SOUTH);
JPanel panelButtons = new JPanel(new BorderLayout(0, 5)); panelButtons.add(buttonToCelcius, BorderLayout.NORTH); panelButtons.add(buttonToFahrenheit, BorderLayout.SOUTH);
JPanel contentPane = new JPanel(new FlowLayout()); contentPane.add(panelDegree); contentPane.add(panelButtons);
setLayout(new FlowLayout()); setContentPane(contentPane); }
Page w16.33 – Spring 2010 Steffen Vissing Andersen
Temperature conversion – GUI example (5/7)
private class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent event) { String msg = textFieldTemp.getText(); double temperature = Double.parseDouble(msg); Temperature temp = new Temperature(); if (event.getSource() == buttonToCelcius) { double t = temp.fahrenheitToCelcius(temperature); msg = String.format("%s Fah = %.2f Celcius", msg, t); } else if (event.getSource() == buttonToFahrenheit) { double t = temp.celciusToFahrenheit(temperature); msg = String.format("%s Celcius = %.2f Fah", msg, t); } JOptionPane.showMessageDialog(null, msg); } }
We need a class Temperature
Page w16.34 – Spring 2010 Steffen Vissing Andersen
Temperature conversion – GUI example (6/7)
public static void main(String[] args) { FrameTemperature frame = new FrameTemperature(); }
} // End of class FrameTemperature
Page w16.35 – Spring 2010 Steffen Vissing Andersen
Temperature conversion – GUI example (7/7)
// The model class
public class Temperature{ public double fahrenheitToCelcius(double fahrenheit) { return 5.0/12.0 * (fahrenheit - 32); } public double celciusToFahrenheit(double celcius) { return celcius * 9.0/5.0 + 32; }}
Page w16.36 – Spring 2010 Steffen Vissing Andersen
Programming Exercises
• Create the following GUI – without functionality
http://it-engineering.dk/Course/A09/SDJI1A/Exercises/ExercisesSession29.pdf
Page w16.37 – Spring 2010 Steffen Vissing Andersen
GUI step by step
1. Sketch your GUI on paper2. Divide the GUI into small separate functionalities3. Implement it part by part in separate classes that
inherits (extends) JPanel• With own layout (LayoutManager)• With own getters for data
4. Implement the Window by inheriting from JFrame• With own layout (LayoutManager)
5. Add the panels to the window6. Add buttons to the window7. Implement action listeners in inner classes that
implements the ActionListener interface
Page w16.38 – Spring 2010 Steffen Vissing Andersen
Sketch your GUI
Page w16.39 – Spring 2010 Steffen Vissing Andersen
Setup Event Handling for a GUI Component
• Several coding steps are required for an application to respond to events• Create a class for the event handler• Implement an appropriate event-listener interface• Register the event handler
• Event handler Class• Public class declared in a separate file • Class declared in the GUI class file (default/no access
modifier) • Private inner class – declared inside the GUI Class
declaration• Anonymous inner class – declared inside the argument
list in calling the addActionListener method
Page w16.40 – Spring 2010 Steffen Vissing Andersen
Event handler Class
• The Event handler class implements ActionListener• i.e. implements a method with the signature:
public void actionPerformed(ActionEvent event)
• Event handler class can be formed in several ways:1. Class declared outside the GUI class declaration
• Public class declared in a separate file • Class declared in the GUI class file (default/no access
modifier)
2. Private inner class – declared inside the GUI class declaration
3. Anonymous inner class – declared inside the argument list in calling the addActionListener method for a component
4. The GUI class itself if this class implements ActionListener and implements the method actionPerformed
Page w16.41 – Spring 2010 Steffen Vissing Andersen
Event handler class declared outside the GUI class
class ButtonHandler implements ActionListener{ private GUIClass frame; public ButtonHandler(GUIClass frame) { this.frame = frame; } public void actionPerformed(ActionEvent event) { if (buttonText.toLowerCase().equals("clear")) { frame.initializeComponents(); } }}
Class should be public, if declared in a separate file
Page w16.42 – Spring 2010 Steffen Vissing Andersen
Event handler class as a private inner class
public class GUIClass extends JFrame{ // ... private class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent event) { if (event.getSource() == buttonClear) { initializeComponents(); } } } // end inner class
} // end of GUI class
Page w16.43 – Spring 2010 Steffen Vissing Andersen
Event handler class as the GUI class itself
public class GUIClass extends JFrame implements ActionListener{ // ... public void actionPerformed(ActionEvent event) { if (event.getSource() == buttonClear) { initializeComponents(); } }
} // end of GUI class
Page w16.44 – Spring 2010 Steffen Vissing Andersen
addActionListener – using Event handler class
• Class declared outside the GUI class declaration ButtonHandler handler = new ButtonHandler(this); // or other
arguments button1.addActionListener(handler);
• Private inner class ButtonHandler handler = new ButtonHandler(); button2.addActionListener(handler);
• Anonymous inner class button3.addActionListener( new ActionListener(){public void actionPerformed( ActionEvent event){initializeComponents();}});
• The GUI class itself button4.addActionListener(this);
Page w16.45 – Spring 2010 Steffen Vissing Andersen
Some Swing Components
Page w16.46 – Spring 2010 Steffen Vissing Andersen
Images – an Example
Page w16.47 – Spring 2010 Steffen Vissing Andersen
Images – an Example
ImagePanel
ButtonPanel
Page w16.48 – Spring 2010 Steffen Vissing Andersen
ButtonPanel (1/4)
import java.awt.*;import java.awt.event.ActionListener;import javax.swing.*;
public class ButtonPanel extends JPanel{ private JButton[] button;
public ButtonPanel(String[] buttonText) { button = new JButton[buttonText.length]; for (int i = 0; i < button.length; i++) button[i] = new JButton(buttonText[i]);
addComponentsToPanel(); }
Page w16.49 – Spring 2010 Steffen Vissing Andersen
ButtonPanel (2/4)
private void addComponentsToPanel() { if (button.length == 3) { setLayout(new BorderLayout(0, 5)); add(button[0], BorderLayout.NORTH); add(button[1], BorderLayout.CENTER); add(button[2], BorderLayout.SOUTH); } else { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); for (int i = 0; i < button.length; i++) { add(button[i]); if (i < button.length - 1) add(Box.createRigidArea(new Dimension(0, 5))); } } }
Page w16.50 – Spring 2010 Steffen Vissing Andersen
ButtonPanel (3/4)
public JButton getButton(String text) { for (int i = 0; i < button.length; i++) if (button[i].getText().equals(text)) return button[i]; return new JButton("No such button"); }
Page w16.51 – Spring 2010 Steffen Vissing Andersen
ButtonPanel (4/4)
public void addActionListenerToOneButton(String buttonText, ActionListener listener) { JButton oneButton = getButton(buttonText); oneButton.addActionListener(listener); }
public void addActionListenerToAllButtons( ActionListener listener) { if (listener == null) return; for (int i = 0; i < button.length; i++) if (button[i] != null) button[i].addActionListener(listener); }
} // End of class ButtonPanel
Page w16.52 – Spring 2010 Steffen Vissing Andersen
ImagePanel (1/2)
import java.awt.event.MouseListener;import javax.swing.*;
public class ImagePanel extends JPanel{ private ImageIcon imageIcon;
public ImagePanel(String imagePath) { imageIcon = new ImageIcon(imagePath); addComponentsToPanel(); } public ImagePanel(String imagePath, MouseListener listener) { this(imagePath); registerListener(listener); }
Page w16.53 – Spring 2010 Steffen Vissing Andersen
ImagePanel (2/2)
private void addComponentsToPanel() { JLabel imageLabel = new JLabel(imageIcon); add(imageLabel); }
private void registerListener(MouseListener listener) { if (listener == null) return; addMouseListener(listener); }
} // End of class ImagePanel
Page w16.54 – Spring 2010 Steffen Vissing Andersen
Class ImageGUI (1/6)
import java.awt.event.*; import javax.swing.*;
public class ImageGUI extends JFrame{ private JPanel contentPane; private ImagePanel imagePanel1; private ImagePanel imagePanel2; private ButtonPanel buttonPanel;
public ImageGUI() { super("Images");
createComponents(); registerEventHandlers(); addComponentsToFrame(); initialize();}
Page w16.55 – Spring 2010 Steffen Vissing Andersen
Class ImageGUI (2/6)
private void createComponents() { imagePanel1 = new ImagePanel(".\\bob.jpg"); imagePanel2 = new ImagePanel(".\\wendy.jpg"); String buttonStrings[] = {"OK", "Cancel", "Help"}; buttonPanel = new ButtonPanel(buttonStrings); contentPane = new JPanel(); }
private void registerEventHandlers() { imagePanel1.addMouseListener(new MouseHandler(“Bob”)); imagePanel2.addMouseListener(new MouseHandler(“Wendy”)); ButtonHandler handler = new ButtonHandler(); buttonPanel.addActionListenerToAllButtons(handler);}
Page w16.56 – Spring 2010 Steffen Vissing Andersen
Class ImageGUI (3/6)
private void addComponentsToFrame() { contentPane.add(imagePanel1); contentPane.add(imagePanel2); contentPane.add(buttonPanel);
setContentPane(contentPane); } private void initialize() { setLocation(100, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); pack(); }
Page w16.57 – Spring 2010 Steffen Vissing Andersen
Class ImageGUI (4/6)
private class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent event) { if (event.getSource() == buttonPanel.getButton(0)) { int q = JOptionPane.showConfirmDialog(null, "Quit?"); if (q == 0) System.exit(0); } else if (event.getSource() == buttonPanel.getButton(1)) { System.exit(0); } else if (event.getSource() == buttonPanel.getButton(2)) { JOptionPane.showMessageDialog(null, "Click on image"); } } }
Page w16.58 – Spring 2010 Steffen Vissing Andersen
Class ImageGUI (5/6)
private class MouseHandler extends MouseAdapter { private String title;
public MouseHandler(String title) { this.title = title; } public void mouseClicked(MouseEvent e) { JOptionPane.showMessageDialog(null, title); } }
Page w16.59 – Spring 2010 Steffen Vissing Andersen
Class ImageGUI (6/6)
public static void main(String[] args) { ImageGUI frame = new ImageGUI(); }
} // end of class ImageGUI
Page w16.60 – Spring 2010 Steffen Vissing Andersen
Class MenuFrame – a menu Example (1/7)
import java.awt.*; import java.awt.event.*;import java.util.ArrayList;import javax.swing.*;
public class MenuFrame extends JFrame{ private JLabel label1; private JPanel mainPanel; private JMenuBar menuBar; private JMenu[] menu; private ArrayList<JMenuItem[]> menuItem; private Dimension size;
Page w16.61 – Spring 2010 Steffen Vissing Andersen
Class MenuFrame – a menu Example (2/7)
public MenuFrame() { createComponents(); createMenu(); initializeComponents(); registerEventHandlers(); addComponentsToFrame(); }
private void createComponents() { label1 = new JLabel("This is a test"); mainPanel = new JPanel(); }
Page w16.62 – Spring 2010 Steffen Vissing Andersen
Class MenuFrame – a menu Example (3/7)
private void createMenu() { menuBar = new JMenuBar(); menu = new JMenu[3]; menu[0] = new JMenu("File"); menu[1] = new JMenu("Edit"); menu[2] = new JMenu("View");
menuItem = new ArrayList<JMenuItem[]>(); JMenuItem[] items = new JMenuItem[3]; items[0] = new JMenuItem("Open"); items[1] = new JMenuItem("Save"); items[2] = new JMenuItem("Exit"); menuItem.add(items);
items = new JMenuItem[2]; items[0] = new JMenuItem("Copy"); items[1] = new JMenuItem("Paste");
Page w16.63 – Spring 2010 Steffen Vissing Andersen
Class MenuFrame – a menu Example (4/7)
menuItem.add(items);
items = new JMenuItem[1]; items[0] = new JMenuItem("Full Screen"); menuItem.add(items);
for (int i = 0; i < menu.length; i++) { JMenuItem[] theItem = menuItem.get(i); for (int j = 0; j < theItem.length; j++) { menu[i].add(theItem[j]); } menuBar.add(menu[i]); } } // End of createMenu
Page w16.64 – Spring 2010 Steffen Vissing Andersen
Class MenuFrame – a menu Example (5/7)
public void initializeComponents() { setJMenuBar(menuBar); add(mainPanel);
setSize(300, 300); setVisible(true); size = getSize(); }
private void addComponentsToFrame() { mainPanel.add(label1);
setContentPane(mainPanel); }
Page w16.65 – Spring 2010 Steffen Vissing Andersen
Class MenuFrame – a menu Example (6/7)
private void registerEventHandlers() { for (int i = 0; i < menu.length; i++) { MenuListener menuListener = new MenuListener(this); JMenuItem[] theItem = menuItem.get(i); for (int j = 0; j < theItem.length; j++) { theItem[j].addActionListener(menuListener); } } }
Page w16.66 – Spring 2010 Steffen Vissing Andersen
Class MenuFrame – a menu Example (7/7)
public JLabel getLabel() { return label1; } public Dimension getFrameSize() { return size; }
public static void main(String[] args) { new MenuFrame(); }} // end of class MenuFrame
Page w16.67 – Spring 2010 Steffen Vissing Andersen
Class MenuListener for class MenuFrame (1/3)
public class MenuListener implements ActionListener{ public MenuFrame frame;
MenuListener(MenuFrame frame) { this.frame = frame; }
public void actionPerformed(ActionEvent e) { String text = ((JMenuItem) e.getSource()).getText(); frame.getLabel().setText(text); text = text.toLowerCase();
if (text.equals("exit")) System.exit(0);
Page w16.68 – Spring 2010 Steffen Vissing Andersen
Class MenuListener for class MenuFrame (2/3)
else if (text.equals("full screen")) { frame.setSize(frame.getToolkit().getScreenSize()); ((JMenuItem) e.getSource()).setText("Restore down"); } else if (menuItemText.equals("restore down")) { frame.setSize(frame.getFrameSize()); ((JMenuItem) e.getSource()).setText("Full Screen"); }
Page w16.69 – Spring 2010 Steffen Vissing Andersen
Class MenuListener for class MenuFrame (3/3)
else if (menuItemText.equals("open")) { String path = "C:\\_SVA\\Workspace\\Java"; JFileChooser chooser = new JFileChooser(path); FileNameExtensionFilter filter = new FileNameExtensionFilter( "Text files *.txt, *.java", "txt", "java"); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(frame); if(returnVal == JFileChooser.APPROVE_OPTION) { String msg = "You chose to open this file: " + chooser.getSelectedFile().getName(); frame.getLabel().setText(msg); } } // end of method actionPerformed} // end of class MenuListener
Page w16.70 – Spring 2010 Steffen Vissing Andersen
Class MenuFrame - Output