OO Case Study - Swing

0.0(0)
studied byStudied by 0 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/28

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

29 Terms

1
New cards

GUIs in Java - Swing

  • the standard java package for GUIs

    • still platform independent, like the rest of Java

  • the package is very large and extremely flexible 

    • includes textboxes, sliders, buttons, images

  • heavily object oriented 

2
New cards

GUI Components

  • built from a standard set of components

    • Traditional ones can be broken down into clear parts 

    • Windows, Buttons, text input areas, menus, etc

    • These are often referred to as components 

3
New cards

GUI Components in Java

  • graphical components are implemented as Java classes 

  • each type of component is a different class 

  • implementation is therefore encapsulated 

  • the complexity of the task is hidden

<ul><li><p>graphical components are implemented as Java classes&nbsp;</p></li><li><p>each type of component is a different class&nbsp;</p></li><li><p>implementation is therefore encapsulated&nbsp;</p></li><li><p>the complexity of the task is hidden</p></li></ul><p></p>
4
New cards

Packages

just a named collection of classes grouped together

act much like C++ namespaces…

Classes from inside packages can be used via full name (e.g. javax.swing.JFrame) 

import javax.swing.*;
public class ...

5
New cards

Import Keyword

tells the java compiler of any additional classes packages you want to import into your program’s namespace

always found on the first lines of any class file

6
New cards

JFrame

represents a window in the host OS

  • Style (Window Decoration) matches local OS

  • Includes title bar, icons to minimize, resize, close, etc

constructor has 2 commonly used forms:

JFrame();
JFrame(String title);

contains useful (private) attributes and associated accessor/mutator mathods:

boolean getVisible();
void setVisible(boolean b);
String getTitle();
void setTitle(String s);
void setSize(int x, int y);

7
New cards

Instantiation in JFrame

  • One instance for every window you need 

  • Make an instance in the usual way: use new to call its constructor

  • Windows are created in an invisible state so that all the components can be built before it is displayed to the user… 

  • Invoke methods on the instance to control its behaviour

JFrame a = new JFrame(); //create blank window
a.setVisible(true); //make it visible
a.setTitle("Hello World"); //change window title
a.setSize(300,300); //change window size

8
New cards

Closing in JFrame

  • Defining what happens when the window is closed 

    • setDefaultCloseOperation(int operation); 

    • JFrame.EXIT_ON_CLOSE (terminate application)

    •  JFrame.DISPOSE_ON_CLOSE (close window, keep app running) 

    • JFrame.DO_NOTHING_ON_CLOSE (ignore)

JFrame a = new JFrame(); //create blank window
a.setVisible(true); //make it visible
a.setTitle("Hello World"); //change window title
a.setSize(300,300); //change window size
a.setDefaultCloseOperation(JFrame,EXIT_ON_CLOSE);

9
New cards

Static Variable/Method

Called on a class, not an instance

  • Use sparingly: Useful only when a more procedural programming style is preferred to OO

  • The variable is also shared between all instances of that class

  • Don’t use static when defining methods in a typical class

10
New cards

Final Variable

Can’t have its value changed after it has been initialized

  • Commonly used technique for defining constants 

  • More humanly readable than trying to remember values 

  • Make code more readable

11
New cards

Adding Components - JPanel

  • holds a list of components, and provides add() and remove() methods for Swing components, so: 

    • create an instance

    • set it as the default panel for your new frame 

import javax.swing.*;
public class HelloWorld
{
	JFrame a = new JFrame();
	JPanel panel = new JPanel();
	a.setContentPane(panel);
}

12
New cards

Adding a Component to a Window

Instantiate the component 

Add it to the relevant JPanel

13
New cards

Common Components of JPanel

  • JButton

  • JLabel 

  • JTextField

14
New cards

JLable

read only text field

  • text can’t be changed by the user on the GUI

  • very useful for prompts, status messages, instructions to the user, etc

commonly used constructors:

JLabel(String s); //plain text
JLabel(Icon i); //image

accessor and mutator methods provided to inspect and change the text displayed:

String getText();
void setText(String s);

15
New cards

JButton

a clickable component

  • useful for performing user-initiated actions

several simple constructors:

JButton(String s); //clickable text button
JButton(ImageIcon i); //clickable image button

16
New cards

JTextField

user editable block of text useful for collecting user input

simple constructors:

JTextField{}; //initially empty
JTextField(String s); //created with given text

accessor and mutator methods provided to inspect and change the text displayed:

String getText(); //retrieve typed text
void setText(String s); // set text box to given value
void setEditable(boolean); //enables/disables user input

17
New cards

Creating Non-Trivial User Interfaces

  • Swing provides a set of Layout Managers class that dynamically layout GUIs for you

  • These help to keep your application flexible and platform independent

  • Layout Managers are part of a package called AWT, so…

import java.awt.*;

18
New cards

FlowLayout

The simplest layout manager 

  • Arrange components best to fit the size of the JPanel 

  • Purely in a left to right, top to bottom order 

  • Useful for simple GUIs, lists etc

  • Implemented in the FlowLayout class, instantiate one if you need one…. 

  • The setLayout() method provided by JPanel allows you to define the layout manager you want to use in that JPanel

FlowLayout layout = new FlowLayout(); //create layout manager
panel.setLayout(layout); //assign to panel

19
New cards

Benefits and Drawbacks of FlowLayout

  • Highly reactive: layout reacts dynamically to changes in size of the panel 

  • Very simple to use 

  • Lack of control over where components are placed 

Some very limited control over alignment possible

  • By default, it will centre your components in panel 

  • But you can specify left, right or centre alignment in the constructor 

  • Note the American spelling of CENTER

FlowLayout layout = new FLowLayout(FlowLayout.LEFT);
FlowLayout layout = new FLowLayout(FlowLayout.CENTER);
FlowLayout layout = new FLowLayout(FlowLayout.RIGHT);

20
New cards

GridLayout

Fixed size components in a matrix 

  • fits components into a n x m grid structure

  • Still arranged left to right, top to bottom, but on grid boundaries, and you can specify the shape of the grid…

GridLayout layout = new GridLayout(int rows, int columns);
panel.setLayout(layout);

<p>Fixed size components in a matrix&nbsp;</p><ul><li><p>fits components into a n x m grid structure</p></li><li><p>Still arranged left to right, top to bottom, but on grid boundaries, and you can specify the shape of the grid…</p></li></ul><pre><code class="language-Java">GridLayout layout = new GridLayout(int rows, int columns);
panel.setLayout(layout);</code></pre><p></p>
21
New cards

Benefits and Drawbacks of GridLayout

managers are excellent for repeating sets of components

  • Which is remarkably common… 

  • e.g. a mixing desk, numerical keyboard, powerpoint…

 Far too clinical to layout everything this way though… 

  • We still don’t really have any control over which component goes where…

22
New cards

BorderLayout

Provides relative positioning of up to five components 

  • BorderLayout divides the JPanel into five areas 

  • North, South, East, West and Center 

  • Compass points take priority over space 

Specify which area to put component inside the add method 

  • Only one component permitted per location

BorderLayout layout = new BorderLayout();
panel.setLatyout(layout);
panel.add("North", buttonPanic);

<p>Provides relative positioning of up to five components&nbsp;</p><ul><li><p>BorderLayout divides the JPanel into five areas&nbsp;</p></li><li><p>North, South, East, West and Center&nbsp;</p></li><li><p>Compass points take priority over space&nbsp;</p></li></ul><p>Specify which area to put component inside the add method&nbsp;</p><ul><li><p>Only one component permitted per location</p></li></ul><pre><code class="language-Java">BorderLayout layout = new BorderLayout();
panel.setLatyout(layout);
panel.add("North", buttonPanic);</code></pre><p></p>
23
New cards

Setting your own Layout

can specify positions manually if you wish

  • specify a null Layout manager

  • use setLocation(int x, int y) and setSize(int x, int y) to manually place components

  • all swing components respond to these methods

panel.setLayout(null); //disable layout manager
public void setLocation(int x, int y);
public void setSize(int x, int y);

we can also use ratios

JButton button = new JButton("Press");
int width = (int)(frame.getWidth() * 0.5);
int height = (int)(frame.getHeight() * 0.2);
button.setSize(width, height);

24
New cards

Using Multiple Panels

Panels can be placed inside other panels… 

  • Each JPanel has its own LayoutManager 

  • This can give us much more flexibility with the layout, while maintaining the ability to handle window resizes 

  • For example, a panel with a GridLayout inside a panel with a BorderLayout:

<p>Panels can be placed inside other panels…&nbsp;</p><ul><li><p><span>Each JPanel has its own LayoutManager&nbsp;</span></p></li><li><p><span>This can give us much more flexibility with the layout, while maintaining the ability to handle window resizes&nbsp;</span></p></li><li><p><span>For example, a panel with a GridLayout inside a panel with a BorderLayout:</span></p></li></ul><p></p>
25
New cards

Event-Based/Asynchronous Programming

when used your code does NOT have a simple start to end flow of execution… Instead: 

  • You application registers interest in certain events (e.g. button presses) 

  • The environment (in this case Java) informs the application when they occur

<p>when used your code does NOT have a simple start to end flow of execution… Instead:&nbsp;</p><ul><li><p>You application registers interest in certain events (e.g. button presses)&nbsp;</p></li><li><p>The environment (in this case Java) informs the application when they occur</p></li></ul><p></p>
26
New cards

Listener Interfaces

Swing lets you register “Listeners” on GUI components: 

  • You register an interest in the events you wish to receive 

  • You provide an object with a well-known method 

  • That method is then invoked when that event occurs 

27
New cards

Types of Listener Interfaces

  • ActionListener: when buttons are clicked 

  • ChangeListener: when sliders are moved 

  • KeyListener: when a button is pressed on the keyboard 

  • MouseListener: when a mouse button is pressed/moved 

  • WindowListener: when windows are resized/closed/minimized

28
New cards

Implementing an ActionListener

All Listeners follow the same steps:  

  • Import the java.awt.event package 

  • Declare you want to receive an event by adding implements ActionListener to your class definition 

  • Use the addActionListener() method to register your interest in the relevant buttons  

  • Write a method called actionPerformed() in your class, with the parameters shown below…

public void actionPerformed(ActionEvent e) {
//code you want to execute when the button is clicked
}

29
New cards

Supporting Multiple Buttons

One ActionListener can be register with multiple buttons 

  • The ActionEvent object can differentiate the source for us 

  • Responds to the getSource() method 

  • Returns the object that generated the event (the JButton) 

Combined with a conditional this can be used to trap all your events in one place: 

public void actionPerformed(ActionEvent e) {
	if (e.getSource() == okButton)
		//...
	if (e.getSource() == cancelButton)
		//...
}