1/28
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
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
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
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
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 ...
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
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);
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
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);
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
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
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);
}
Adding a Component to a Window
Instantiate the component
Add it to the relevant JPanel
Common Components of JPanel
JButton
JLabel
JTextField
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);
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
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
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.*;
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
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);
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);
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…
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);
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);
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:
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
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
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
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
}
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)
//...
}