41
Graphical User Interfaces with Swing Kakarontzas George

Graphical User Interfaces with Swing

  • Upload
    others

  • View
    13

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Graphical User Interfaces with Swing

Graphical User Interfaces with Swing Kakarontzas George

Page 2: Graphical User Interfaces with Swing

What is swing? Swing is a set of GUI components that are 100% pure Java code

and not dependent on specific any specific operating system (e.g. MS Windows)

This allows programs written with swing to have a pluggable look and feel. By default swing programs have a custom java look and feel. Nevertheless we can specify that we wish their appearance to be that of a specific windows framework (e.g. Ms Windows or CDE), regardless of the operating system in which the program is running.

Because swing components are 100% java code, they don’t have to limit to the common factor of the different operating systems.

Page 3: Graphical User Interfaces with Swing

Our first swing application (1) import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SwingApplication extends JFrame { private static String labelPrefix = “Number of clicks: "; private int numClicks = 0; private JLabel label; private JButton button; private JPanel pane; public SwingApplication() { ... } public static void main(String[] args) { SwingApplication app = new SwingApplication(); } }

Page 4: Graphical User Interfaces with Swing

public SwingApplication() { super("Swing Application");

label = new JLabel(labelPrefix + "0 ");

button = new JButton(“I’m a button!");

button.setMnemonic(KeyEvent.VK_I);

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

numClicks++;

label.setText(labelPrefix + numClicks);

}

});

... }

Our first swing application(2)

Page 5: Graphical User Interfaces with Swing

public SwingApplication() { ...

pane = new JPanel();

pane.setBorder(BorderFactory.createEmptyBorder(

30, //top

30, //left

10, //bottom

30) //right

);

pane.setLayout(new GridLayout(0, 1));

pane.add(button);

pane.add(label);

... }

Our first swing application(3)

Page 6: Graphical User Interfaces with Swing

public SwingApplication() { ...

getContentPane().add(pane, BorderLayout.CENTER);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

pack();

setVisible(true);

}

Our first swing application(4)

Page 7: Graphical User Interfaces with Swing

Running the program

Each time we press the button the label displays the updated number of clicks.

Page 8: Graphical User Interfaces with Swing

The JFrame class JFrame is a top-level container class which can contain other swing

components. Components are added in the content area of the JFrame using the

method: frame.getConentPane().add(component); The content pane of a JFrame usually contains all components

except menus. Layout managers of a JFrame are also associated with the content

pane of the frame, and are responsible for the placement of the components.

In a JFrame we can define what happens if a user presses the close button on the frame using the method: setDefaultCloseOperation(int), e.g., setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

Page 9: Graphical User Interfaces with Swing

Look and Feel

We can set the look and feel of a swing application (or applet), to a different look and feel than the default.

The following program displays the look-and-feel class names for: The system look and feel The available look and feels of the executing JVM

and The java look and feel

Page 10: Graphical User Interfaces with Swing

LookAndFeels import javax.swing.*; public class LookAndFeels { public static void main(String args[]) { System.out.println("System look and feel..."); String slaf = UIManager.getSystemLookAndFeelClassName(); System.out.println(slaf); System.out.println("\nAll available looks and feels..."); UIManager.LookAndFeelInfo[] lafs = UIManager.getInstalledLookAndFeels(); for (int i=0; i<lafs.length; i++) { String className = lafs[i].getClassName(); System.out.println(className); } System.out.println("\nThe Java look and feel..."); String jlf = UIManager.getCrossPlatformLookAndFeelClassName(); System.out.println(jlf); } }

Page 11: Graphical User Interfaces with Swing

Running the program

Page 12: Graphical User Interfaces with Swing

Setting the look and feel

We can set the look and feel of a java application by using code similar to the following code segment:

String laf = UIManager.getSystemLookAndFeelClassName();

try { UIManager.setLookAndFeel(laf); } catch (UnsupportedLookAndFeelException exc) {System.err.println("Unsupported: " + laf);} catch (Exception exc) {System.err.println("Error loading " + laf); }

Page 13: Graphical User Interfaces with Swing

Exercise

Set the look and feel of the SwingApplication we did earlier to the different possible look and feels available and run the application to observe visually the difference.

You can set the look and feel of an application to the constructor before adding any objects to the frame

Use the class names of the look and feel classes that we obtained by running the LookAndFeel application earlier.

Page 14: Graphical User Interfaces with Swing

Exercise results

Windows Look And Feel

Motif/CDE Look And Feel

Java Look And Feel

Page 15: Graphical User Interfaces with Swing

Buttons

The JButton class can be used for the buttons of a GUI application

The JToggleButton class can be used in an application in which we need buttons that are pressed or not pressed (they can have two different states, e.g. a switch).

The JRadioButton and JCheckBox classes can be used to implement radio buttons and check boxes respectively.

Page 16: Graphical User Interfaces with Swing

ToolBars

We can use the JToolBar class to implement toolbars. A toolbar can be moved to any of the four edges of a

JFrame unless we set the floatable attribute to false (this assumes a BorderLayout layout manager)

It is usual to use with this class buttons that contain icons instead of text. Since it is sometimes difficult for the user to understand what the button does by looking at the icon, we usually associate icon buttons with tooltips that explain what the button does. These tooltips are displayed when the mouse pointer is placed on the button.

Page 17: Graphical User Interfaces with Swing

The “Buttons” example As an example we will implement a swing application in

which we are going to place several different Buttons, JToggleButtons, JCheckBoxes, JRadioButtons, as well as a JToolBar.

For now these buttons will not be active (they won’t do anything when we press them). We will later add events for them.

The application will look like this:

Page 18: Graphical User Interfaces with Swing

Η εφαρμογή Buttons

import java.awt.*; import javax.swing.*; import javax.swing.border.*; public class Buttons extends JFrame { //member variables JToolBar toolbar; //A JToolBar JCheckBox Coffee, Tea, Wine; //Three JCheckBoxes JRadioButton Male, Female; //Two JRadioButtons JButton Clear, Quit; //Two Jbuttons JToggleButton a, b, c; //Three JToggleButtons public Buttons() { . . . } //constructor private void setBar() { . . .} //helper method //main creates the JFrame so that it is displayed static public void main(String argv[]) { new Buttons(); } }

Page 19: Graphical User Interfaces with Swing

Construction of the JFrame

The following code segment makes the frame closeable, creates a JPanel (jp) and adds it to the JFrame (we will later on add objects on jp). It also sets the layout of jb to the BorderLayout. Notice also calling the constructor of the super class to set the title of the frame with the command: super(“Buttons and Checks”);

public Buttons() {

super("Buttons and Checks"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel jp = new JPanel(); getContentPane().add(jp); jp.setLayout(new BorderLayout());

...

}

Page 20: Graphical User Interfaces with Swing

JToolBar and application Panels The following code segment creates the JToolBar and adds it to the

north area of jp. It also does the toolbar non-floatable. It creates an additional panel (center) and adds it to the jp’s center. Then it creates two more panels (left and right) and adds them to the center panel. These two panels will be sharing the center area of the frame.

public Buttons() { ... toolbar = new JToolBar(); toolbar.setFloatable(false); jp.add("North", toolbar); JPanel center = new JPanel(); jp.add("Center", center); center.setLayout(new GridLayout(1,2)); JPanel left = new JPanel(); JPanel right = new JPanel(); center.add(left); center.add(right); ... }

Page 21: Graphical User Interfaces with Swing

Application panels

left

right

center

jp toolbar

Page 22: Graphical User Interfaces with Swing

Layouts and borders of the central panels The following code segment separates the two

central panels (left and right) so that they have three lines and one column each, and places around them a titled border using the setBorder method of the JPanel class:

public Buttons() { ... left.setLayout(new GridLayout(3,1));

right.setLayout(new GridLayout(3,1));

left.setBorder(new TitledBorder(“Preferences"));

right.setBorder(new TitledBorder(“Gender")) ... }

Page 23: Graphical User Interfaces with Swing

How it looks so far:

The look of our application so far is this:

Page 24: Graphical User Interfaces with Swing

Adding the Check Boxes

The following code segment creates three JCheckBox objects and adds them to the left panel (the “Preferences” panel). Because it is possible that someone might prefer all three kinds of drinks (coffe, tea and wine) these are check boxes and not radio buttons.

public Buttons() { ... left.add(Coffee = new JCheckBox(“Coffe"));

left.add(Tea = new JCheckBox(“Tea"));

left.add(Wine = new JCheckBox(“Wine")); ... }

Page 25: Graphical User Interfaces with Swing

Adding the Radio Buttons The following code segment creates to JRadioButton objects and

adds them to the right panel (the “Gender” panel). To enable the selection of one gender at a time we create a ButtonGroup object and add two JRadioButtons in this button group: since the two JRadioButtons belong to the same ButtonGrpoup only one of them can be selected at a time:

public Buttons() { ... right.add(Male = new JRadioButton(“Male"));

right.add(Female = new JRadioButton(“Female"));

ButtonGroup bgroup = new ButtonGroup();

bgroup.add(Male);

bgroup.add(Female); ... }

Page 26: Graphical User Interfaces with Swing

How it looks so far:

The look of our application so far is this:

Page 27: Graphical User Interfaces with Swing

The rest of the constructor The rest of the constructor’s code

calls the setBar() method which will create the toolbar that we already added to the jp panel

calls pack() to ensure that the frame has the appropriate dimensions so that all it’s objects can be displayed properly and

displays the frame by calling the setVisible(true) method.

public Buttons() { ... setBar();

pack();

setVisible(true);

}

private void setBar() { ... }

Page 28: Graphical User Interfaces with Swing

The setBar method (1)

setBar() initially creates two JButton objects with icons and places them on the JToolBar. It sets the size of the JButtons using the setSize() method. It also sets the tooltips for the JButtons using the setToolTipText() method. private void setBar() { Clear = new JButton(new ImageIcon("erase.gif")); setSize(25, 25); Quit = new JButton(new ImageIcon("stop.gif")); setSize(25, 25); toolbar.add(Clear); Clear.setToolTipText("Cleans all borders"); Quit.setToolTipText("Exits the program"); toolbar.add(Quit);

... }

Page 29: Graphical User Interfaces with Swing

The setBar method (2)

Next we add a separator to the toolbar with the addSeparator() method, we create three JToggleButtons and add them on the toolbar. private void setBar() { ...

toolbar.addSeparator(); a = new JToggleButton(“a"); b = new JToggleButton(“b"); c = new JToggleButton(“c"); toolbar.add(a); toolbar.add(b); toolbar.add(c);

... }

Page 30: Graphical User Interfaces with Swing

The setBar method (3)

Finally we add the three JToggleButtons to a ButtonGroup so that only one of them can be turned on (selected) at a time.

private void setBar() { ...

ButtonGroup tgroup = new ButtonGroup(); tgroup.add(a); tgroup.add(b); tgroup.add(c);

}

Page 31: Graphical User Interfaces with Swing

The result of the application The result of the application is displayed in the

following figure: Notice that check boxes, radio buttons and toggle buttons,

behave as expected in regard to their selection Also notice the appearance of tooltip text messages. JButtons are not active yet, because we haven’t added event

handling code to them, something that we will do next.

Page 32: Graphical User Interfaces with Swing

Event Listeners – Required steps

1. First we have to decide on the events that we want to capture and their sources.

2. Next we have to decide what is the appropriate interface of the java.awt.event package that we have to implement in the event handling class.

3. Then we need to decide what will be the event handling class that will implement this interface and implement the interface for this class by providing the code for the event handling method.

4. Finally we have to create an object of the class we implemented in the third step and add this object to the event source object as an event listener using the appropriate addXXXListener method. This association will be realized using a method call such as this: event-source-object.addXXXListener(event-listener-object)

Page 33: Graphical User Interfaces with Swing

Events

The more significant event classes are the following: ActionEvent: This class is used for events such as pressing a

button or pressing the enter inside a text box. AdjustmentEvent: This class is used for adjustment events that

are caused by the user to objects that are adjustable (e.g. scrollbars).

ItemEvent: This class is used for events that are caused by the user to selectable objects (e.g. a check box). They are either the selection or the de-selection of the selectable object.

KeyEvent: This class is used for events caused by the user using the keyboard

MouseEvent: This class is used for events caused by the user using the mouse

Page 34: Graphical User Interfaces with Swing

Event handling classes

Classes that handle or listen for events (event listeners) must implement the appropriate interfaces, depending on the event type that they want to handle.

If, for example, we implement a class that listens for events caused by pressing a button, then we need to implement the ActionListener interface for this class. The implementation of this interface entails the definition of the following method: void actionPerformed(ActionEvent e). This method will be called automatically when the event is caused on the object(s) for which this class is associated as their event listener.

Page 35: Graphical User Interfaces with Swing

Event handling interfaces of the java.awt.event package The most important interfaces that we usually have to implement for

the event handling classes are the following: ActionListener: Is implemented by classes that listen for

ActionEvents such as pressing a button. The method that we have to implement is void actionPerformed( ActionEvent e ) which will handle the event when it is caused.

AdjustmentListener: Is implemented by classes that listen for adjustment events such as changing the position of a scroll bar. The method that we have to implement is the void adjustmentValueChanged( AdjustmentEvent e ) method.

ItemListener: Is implemented by classes that listen for Item Events such as changing the state of a check box. The method that have to implement is the void itemStateChanged( ItemEvent e ) method.

Page 36: Graphical User Interfaces with Swing

Associating event sources to event listeners When a class implements the xxxListener

interface it can be associated with an object that can be the source for these events. The association is achieved by calling addXXXListener methods

For example in a JCheckBox there is an addItemListener(ItemListener l). This method adds an object that implements the ItemListener interface to the JCheckBox as the listener of item events originating from this check box.

Page 37: Graphical User Interfaces with Swing

Example: Adding event listening to the Buttons application JFrame will implement the ActionListener

interface. We will implement the actionPerformed(Event e)

for the JFrame (this is the method that an ActionListener has to provide)

We will associate the JFrame with the two JButtons of the toolbar so that the JFrame will be their listener for action events originating from them. When we press these buttons the JFrame.actionPerformed method will be executed.

Page 38: Graphical User Interfaces with Swing

Updates to the Buttons application

import java.awt.event.*;

...

public class Button extends JFrame implements ActionListener

{ ...

private void setBar() {... Clear.addActionListener(this);

Quit.addActionListener(this); ...}

public void actionPerformed(ActionEvent e) { ...

} }

Page 39: Graphical User Interfaces with Swing

The actionPerformed method

public void actionPerformed(ActionEvent e)

{

Object obj = e.getSource();

if(obj == Quit)

System.exit(0);

if(obj == Clear)

{

Coffee.setSelected(false);

Tea.setSelected(false);

Wine.setSelected(false);

}

}

Page 40: Graphical User Interfaces with Swing

Exercise 1

The JRadioButtons of the application cannot be cleared using the setSelected(false) method because if a radio button is selected from a group then one must be selected at all times. To give the illusion of clearance of the radio buttons group add a third invisible radio button and select this when the user presses the clear button.

Page 41: Graphical User Interfaces with Swing

Exercise 2

Create an application that displays two buttons, one with the Greek flag and another with the English flag. The frame will have above the two buttons a label (JLabel) that will contain either the phrase ‘English text’ or the phrase ‘Ελληνικό κείμενο’. When the user presses the Greek flag button the Greek text will be displayed. When the user presses the English flag button the English text will be displayed. Initially the label contains the Greek text message.