50
1 A Quick Java A Quick Java Swing Tutorial Swing Tutorial

1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

Embed Size (px)

Citation preview

Page 1: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

1

A Quick Java A Quick Java Swing TutorialSwing Tutorial

Page 2: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

2

IntroductionIntroduction

• Swing – A set of GUI classes– Part of the Java's standard library

– Much better than the previous library: AWT• Abstract Window Toolkit

• Highlights– A rich set of widgets

• Widget: Any GUI element (also called: components)

– Contents and shape are separated (MVC support)

– Fine-grained control over the behavior and look and feel

– Platform independent• Isolates the programmer from the operating system's GUI

Page 3: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

3

Swing ComponentsSwing Components

• Containers– Contain and manage other components.– Top Level/Internal – Examples: JFrame (Top Level), JScrollPane, JPanel.

• Basic controls

– Atomic components

– Used for showing ouput and/or getting some input

– Inherits JComponent– Examples: JButton, JLabel, JTextArea, JTable, Jlist

• Usually every Swing class extends the corresponding AWT class

– For backward-compatibility reasons

Page 4: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

4

My First Swing ProgramMy First Swing Programimport javax.swing.*;import java.awt.BorderLayout;

public class First { public static void main(String[] args) { JFrame frame = new JFrame("My First Frame");

// operation to do when the window is closed. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(new JLabel("I Love Swing"), BorderLayout.CENTER); frame.pack(); frame.setVisible(true); }}

Page 5: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

5

Top Level Containers: JFrameTop Level Containers: JFrame• javax.swing.JFrame:

– Top-level window with a title and a border.– Usually used as a program's main window

Page 6: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

6

More on JFrameMore on JFrame

• Made of several layers

• Widgets are added to the Content Pane layer.– Use getContentPane() to obtain it

• Other layers are used for customizing the window's appearence

Page 7: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

7

Top Level Containers: JDialogTop Level Containers: JDialog• javax.swing.JDialog:

– More simple and limited than frames– Typically used for showing a short message on the screen– Also has a border and a title bar– May have an owner

• If the owner is invisible the dialog will also be invisible

– Use the static method of JoptionPane to show standard dialog boxes:JOptionPane.showMessageDialog(null, "4+2=6");

Page 8: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

8

Top Level Containers: JFileChooserTop Level Containers: JFileChooser

• javax.swing.JFileChooser:– Allows the the user to choose a file– Supports “open” and “save”: showOpenDialog(),showSaveDialog()

JFileChooser fc = new JFileChooser();int returnVal = fc.showOpenDialog(null);if(returnVal == JFileChooser.APPROVE_OPTION) System.out.println("File: " + fc.getSelectedFile());

Page 9: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

Example Program

• Using JFileChooser

Page 10: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

import javax.swing.*;import java.awt.BorderLayout;

public class Second { public static void main(String[] args) { JFrame frame = new JFrame("My First Frame");

// operation to do when the window is closed. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(new JLabel("I Love Swing"), BorderLayout.CENTER); frame.pack(); frame.setVisible(true);

Page 11: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

JFileChooser fc = new JFileChooser();int returnVal = fc.showOpenDialog(null);if(returnVal ==

JFileChooser.APPROVE_OPTION) System.out.println("File: " +

fc.getSelectedFile()); }}

Page 12: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

Amending this to choose a file for input

import javax.swing.*;import java.awt.BorderLayout;import java.io.*;public class Third { public static void main(String[] args) {JFileChooser fc = new JFileChooser();int returnVal = fc.showOpenDialog(null);if(returnVal == JFileChooser.APPROVE_OPTION) System.out.println("File: " + fc.getSelectedFile());

Page 13: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

Next

try{

// Open the file that is the first // command line parameter FileInputStream fstream = new

FileInputStream(fc.getSelectedFile());

// Convert our input stream to a // DataInputStream

DataInputStream in = new DataInputStream(fstream);

Page 14: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

finally // Continue to read lines while // there are still some left to read while (in.available() !=0)

{ // Print file line to screen

System.out.println (in.readLine());}

in.close();}

catch (Exception e){

System.err.println("File input error");}

}}

Page 15: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

And Using this to save a file for Output

Page 16: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

import javax.swing.*;import java.awt.BorderLayout;import java.io.*;public class Fourth { public static void main(String[] args) {JFileChooser fc = new JFileChooser();int returnVal = fc.showSaveDialog(null);if(returnVal == JFileChooser.APPROVE_OPTION) System.out.println("File: " + fc.getSelectedFile());

FileOutputStream out; // declare a file output object PrintStream p; // declare a print stream object

Page 17: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

try { // Create a new file output stream // connected to "myfile.txt" out = new FileOutputStream(fc.getSelectedFile());

// Connect print stream to the output stream p = new PrintStream( out );

p.println ("This is written to a file");

p.close(); }

Page 18: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

catch (Exception e) { System.err.println ("Error

writing to file"); }

}}

Page 19: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

19

Internal ContainersInternal Containers

• Not Top level containers• Can contain other non-top level components• Examples:

– JScrollPane: Provides a scrollable view of its components

– JSplitPane: Separates two components

– JTabbedPane: User chooses whichcomponent to see

Page 20: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

20

Containers - LayoutContainers - Layout

• Each container has a layout manager – Determines the size, location of contained widgets.

• Setting the current layout of a container:void setLayout(LayoutManager lm)

• LayoutManager implementing classes:– BorderLayout– BoxLayout– FlowLayout– GridLayout

Page 21: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

21

Containers - LayoutContainers - Layout

Page 22: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

22

Swing ComponentsSwing Components

Page 23: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

23

Swing ComponentsSwing Components

Page 24: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

24

First Swing Program RevisitedFirst Swing Program Revisited

import javax.swing.*;import java.awt.BorderLayout;

public class First { public static void main(String[] args) { JFrame frame = new JFrame("My First Frame");

// operation to do when the window is closed. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(new JLabel("I Love Swing"), BorderLayout.CENTER); frame.pack(); frame.setVisible(true); }}

Create a frame

Create a text label

Add the label to the content pane

Choose the border layout

Specify CENTER as the layout position

Page 25: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

25

InputInput

• So we now know how to present widgets on the screen

• A program also needs to react to the user's actions

• Examples:– When the user presses a button we want to save a file

– When the user closes the program we want to ask “are you sure?”

– ...

• Swing mechanism: Events and Listeners

Page 26: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

26

Events, ListenersEvents, Listeners• Swing defines all sorts of Listener interfaces

– E.g.: ActionListener, MouseMotionListener, WindowListener, ...

public interface ActionListener extends EventListener {

public void actionPerformed(ActionEvent e);

}

public interface MouseMotionListener extends EventListener {

public void mouseDragged(MouseEvent e);

public void mouseMoved(MouseEvent e);

}

• There are default (empty) implementations for many of the listeners– E.g.: MouseMotionAdapter, WindowAdapter

Page 27: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

27

Events, Listeners (cont.)Events, Listeners (cont.)

• A listener is an object that implements a listener interface

• If we need to react to an event (on a certain widget) we register a listener object with that widget

• E.g.: addActionListener() registers an action listener with its receiver:

JButton button = new JButton(); ActionListener listener = ...; button.addActionListener(listener);

• When an event occurs, all registered listeners are notified– The appropriate listener method (e.g: actionPerformed()) is

invoked

– An object describing the event is passed as a parameter

Page 28: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

28

Event Handling Demo: GUIEvent Handling Demo: GUI

Page 29: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

29

Event Handling Demo: CodeEvent Handling Demo: Codeimport javax.swing.*;import java.awt.*;import java.awt.event.*;

public class Events implements ActionListener { public Events() { JFrame frame = new JFrame("Events"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().setLayout(new FlowLayout()); JButton b = new JButton("Click me!"); b.addActionListener(this); frame.getContentPane().add(b); frame.pack(); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Thank you"); } public static void main(String[] args) { new Events(); } }

Page 30: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

30

Inner ClassesInner Classes

• Nested within another classes

• Instance specific: – Has access to methods & fields of the object that

created it– => An inner class has TWO this variables

• Can be static – Can access only static members and methods only– A static method cannot create a non-static inner class

Page 31: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

31

Local ClassesLocal Classes

• Same as inner classes but defined inside a method

• Has access to local variables of the enclosing method – Only if the variable is defined as final

• Can be anonymous– Doesn’t have a name.

Page 32: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

32

Event Handling Demo: Local ClassEvent Handling Demo: Local Classimport javax.swing.*;import java.awt.*;import java.awt.event.*;

public class Events { public Events() { JFrame frame = new JFrame("Events"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().setLayout(new FlowLayout()); JButton b = new JButton("Click me!"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Thank you"); } }); frame.getContentPane().add(b); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { new Events(); } }

Page 33: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

Example of using RadioButtons

Page 34: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

• import javax.swing.*;• import java.awt.*;• import java.awt.event.*;

• public class SelectRadioButton{• JLabel label;

• public SelectRadioButton(){• JFrame frame = new JFrame("Radio button selection");• JRadioButton first = new JRadioButton("First");• JRadioButton second = new JRadioButton("Second");• JRadioButton third = new JRadioButton("Third");• JRadioButton fourth = new JRadioButton("Fourth");• JRadioButton fifth = new JRadioButton("Fifth");•

Page 35: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

• JPanel panel = new JPanel();• panel.add(first);• panel.add(second);• panel.add(third);• panel.add(fourth);• panel.add(fifth);• ButtonGroup bg = new ButtonGroup();• bg.add(first);• bg.add(second);• bg.add(third);• bg.add(fourth);• bg.add(fifth);

Page 36: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

• first.addActionListener(new MyAction());• second.addActionListener(new MyAction());• third.addActionListener(new MyAction());• fourth.addActionListener(new MyAction());• fifth.addActionListener(new MyAction());• label = new JLabel("Roseindia.net");• frame.add(panel, BorderLayout.NORTH);• frame.add(label, BorderLayout.CENTER);• frame.setSize(400, 400);• frame.setVisible(true);• frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);• }

Page 37: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

• public class MyAction implements ActionListener{• public void actionPerformed(ActionEvent e){• label.setText(e.getActionCommand());• JOptionPane.showMessageDialog(null,"This is the "

+ e.getActionCommand() + • " radio button.");• }• }• public static void main(String[] args){• SelectRadioButton sr = new SelectRadioButton();• }• }

Page 38: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

CheckBox example

• Compliments of Java Docs

Page 39: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

Structure of Exams

• 4 questions• Do 1 and any 2 others

Page 40: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

Declare Checkboxes

import java.awt.*;import java.awt.event.*;import javax.swing.*;//Note: Help for getting the below source code is taken from Java Sun Website

public class JCheckBoxDemo extends JPanel {

//Four accessory choices provide for 16 different combinationsJCheckBox jcbChin;

JCheckBox jcbGlasses; JCheckBox jcbHair; JCheckBox jcbTeeth;

Page 41: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

Add an Item listener for each of the checkboxes

/* The image for each combination is contained in a separate image file whose name indicates the accessories. The filenames are "geek-XXXX.gif" where XXXX can be one * of the following 16 choices. */

StringBuffer choices; JLabel jlbPicture; CheckBoxListener myListener = null; public JCheckBoxDemo() {

// Add an item listener for each of the check boxes. // This is the listener class which contains business logic myListener = new CheckBoxListener();

Page 42: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

Add item listeners and Key Stroke access

// Create check boxes with default selection true jcbChin = new JCheckBox("Chin"); jcbChin.setMnemonic(KeyEvent.VK_C); //Alt+C Checks/Unchecks the

check Box jcbChin.setSelected(true); jcbChin.addItemListener(myListener); jcbGlasses = new JCheckBox("Glasses"); jcbGlasses.setMnemonic(KeyEvent.VK_G); //Alt+G Checks/Unchecks the

check Box jcbGlasses.setSelected(true); jcbGlasses.addItemListener(myListener);

Page 43: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

And Again

jcbHair = new JCheckBox("Hair"); jcbHair.setMnemonic(KeyEvent.VK_H); //Alt+H

Checks/Unchecks the check Box jcbHair.setSelected(true); jcbHair.addItemListener(myListener);

jcbTeeth = new JCheckBox("Teeth"); jcbTeeth.setMnemonic(KeyEvent.VK_T); //Alt+T

Checks/Unchecks the check Box jcbTeeth.setSelected(true); jcbTeeth.addItemListener(myListener);

Page 44: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

Default Image

// Indicates what's on the geek. choices = new StringBuffer("cght");//Default Image has

all the parts.

// Set up the picture label jlbPicture = new JLabel(new ImageIcon("geek-" +

choices.toString().trim() + ".gif")); jlbPicture.setToolTipText(choices.toString().trim());

Page 45: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

Add Checkboxes

// Put the check boxes in a column in a panel JPanel jplCheckBox = new JPanel(); jplCheckBox.setLayout(new GridLayout(0,

1)); //0 rows, 1 Column jplCheckBox.add(jcbChin); jplCheckBox.add(jcbGlasses); jplCheckBox.add(jcbHair); jplCheckBox.add(jcbTeeth);

Page 46: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

Impose Layout

setLayout(new BorderLayout()); add(jplCheckBox, BorderLayout.WEST); add(jlbPicture, BorderLayout.CENTER);

setBorder(BorderFactory.createEmptyBorder(20,20,20,20));

}

Page 47: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

Listen for Checkbox event and get source

//Listens to the check boxes events class CheckBoxListener implements

ItemListener { public void itemStateChanged(ItemEvent e) { int index = 0; char c = '-'; Object source = e.getSource(); if (source == jcbChin) { index = 0; c = 'c'; }

Page 48: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

else if (source == jcbGlasses) { index = 1; c = 'g'; } else if (source == jcbHair) { index = 2; c = 'h'; } else if (source == jcbTeeth) { index = 3; c = 't'; }

Page 49: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

Depending on whats clicked display appropriate GIF

if (e.getStateChange() == ItemEvent.DESELECTED) c = '-';

choices.setCharAt(index, c); jlbPicture.setIcon(new ImageIcon("geek-"

+ choices.toString().trim() + ".gif")); jlbPicture.setToolTipText(choices.toString()); } }

}

Page 50: 1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:

Display Title and Border

public static void main(String s[]) { JFrame frame = new JFrame("JCheckBox Usage Demo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setContentPane(new JCheckBoxDemo()); frame.pack(); frame.setVisible(true); }