PART 22. Java GUI Library SWT GUI Library SWING GUI Library Swing First Program

Similar documents
Part I: Learn Common Graphics Components

Graphical User Interfaces. Swing. Jose Jesus García Rueda

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

Example: Building a Java GUI

Introduction to the JAVA UI classes Advanced HCI IAT351

Example: Building a Java GUI

Graphical User Interfaces. Comp 152

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

Starting Out with Java: From Control Structures Through Objects Sixth Edition

PART 23. Java GUI Advanced JList Component. more items.

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

Graphical User Interface (GUI)

AP CS Unit 11: Graphics and Events

Window Interfaces Using Swing Objects

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Chapter 9 Designing Graphical User Interfaces (GUIs)

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Window Interfaces Using Swing Objects

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

PIC 20A GUI with swing

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Introduction to Graphical Interface Programming in Java. Introduction to AWT and Swing

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions.

Systems Programming Graphical User Interfaces

Packages: Putting Classes Together

Java: Graphical User Interfaces (GUI)

Chapter 8. Java continued. CS Hugh Anderson s notes. Page number: 264 ALERT. MCQ test next week. This time. This place.

Java continued. Chapter 8 ALERT ALERT. Last week. MCQ test next week. This time. This place. Closed book. Assignment #2 is for groups of 3

Chapter 12 GUI Basics

Widgets. Widgets Widget Toolkits. 2.3 Widgets 1

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

encompass a group of features for building Graphical User Interfaces (GUI).

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

BASICS OF GRAPHICAL APPS

KF5008 Program Design & Development. Lecture 1 Usability GUI Design and Implementation

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

To gain experience using GUI components and listeners.

Graphical User Interfaces in Java - SWING

CSCI 201L Midterm Written Summer % of course grade

Lecture 9. Lecture

Swing. By Iqtidar Ali

2110: GUIS: Graphical User Interfaces

Widgets. Overview. Widget. Widgets Widget toolkits Lightweight vs. heavyweight widgets Swing Widget Demo

Lecture 5: Java Graphics

Swing from A to Z Some Simple Components. Preface

Programmierpraktikum

Java IDE Programming-I

Part 3: Graphical User Interface (GUI) & Java Applets

EVENTS, EVENT SOURCES AND LISTENERS

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

Systems Programming. Bachelor in Telecommunication Technology Engineering Bachelor in Communication System Engineering Carlos III University of Madrid

COURSE DESCRIPTION. John Lewis and William Loftus; Java: Software Solutions; Addison Wesley

Widgets. Widgets Widget Toolkits. User Interface Widget

Graphical User Interface (GUI)

1.00 Lecture 14. Lecture Preview

Agenda. Container and Component

I.1 Introduction Matisse GUI designer I.2 GroupLayout Basics Sequential and Parallel Arrangements sequential horizontal orientation

Chapter 7: A First Look at GUI Applications

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

Class 14: Introduction to the Swing Toolkit

EPITA Première Année Cycle Ingénieur. Atelier Java - J5

Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI

Chapter 6: Graphical User Interfaces

Graphical User Interfaces (GUIs)

FirstSwingFrame.java Page 1 of 1

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

Swing I CHAPTER EVENT-DRIVEN PROGRAMMING 921 Events and Listeners 921

Calculator Class. /** * Create a new calculator and show it. */ public Calculator() { engine = new CalcEngine(); gui = new UserInterface(engine); }

Class 16: The Swing Event Model

Graphical Applications

Programming Languages and Techniques (CIS120)

Swing Programming Example Number 2

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

Java Programming Lecture 6

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

Swing I Event-Driven Programming Buttons, Events, and Other Swing Basics Containers and Layout Managers 946

Lecture 3: Java Graphics & Events

Chapter 12 Advanced GUIs and Graphics

Graphical User Interface (GUI)

INTRODUCTION TO (GUIS)

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

Jonathan Aldrich Charlie Garrod

JLayeredPane. Depth Constants in JLayeredPane

(Incomplete) History of GUIs

GUI and its COmponent Textfield, Button & Label. By Iqtidar Ali

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Graphical interfaces & event-driven programming

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Introduction to GUIs. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2014

COMP16121 Sample Code Lecture 1

Transcription:

PART 22 Java GUI Library 22.1 SWT GUI Library There is also another GUI library for the Java programming language. It is called SWT (The Standard widget toolkit). The SWT library was initially developed by the IBM corporation. Now it is an open source project, supported by IBM. The SWT is an example of a heavyweight toolkit. It lets the underlying OS to create GUI. SWT uses the java native interface to do the job. The main advantages of the SWT are speed and native look and feel. It is less powerful then Swing. It is also OS dependent library. 22.2 SWING GUI Library Swing library is an official Java GUI toolkit released by Sun Microsystems. Swing is written in 100% java. Swing is a part of JFC, Java Foundation Classes. It is a collection of packages for creating full featured desktop applications. JFC consists of AWT, Swing, Accessibility, Java 2D, and Drag and Drop. Swing was released in 1997 with JDK 1.2. 22.3 Swing First Program In this chapter, we will program our first programs in Swing toolkit. The examples are going to be very simple. We will cover some basic functionality. In our first example, we will show a basic window on the screen.

Alternative 1: Extending JFrame public class Example extends JFrame { public Example() { settitle("simple example"); setsize(300, 200); setdefaultcloseoperation(exit_on_close); Example ex = new Example(); ex.setvisible(true); Alternative 2: Using JFrame Class public class Example { public static void creategui() { JFrame frame = new JFrame("Hello World"); frame.setsize(300, 200); frame.setvisible(true); creategui(); 22.3 JFrame A Frame object in Swing is called a JFrame, which abides by the naming conventions of Swing where default widgets have a J at the start (i.e JButton, JLabel etc). The JFrame is described as a 'Top-Level' container, as the JFrame does not need to attach itself to another object to be displayed.

The Content Pane is where you put all the text, buttons and funky graphics (widgets) that you wish to put on your program. We work with the Content Pane for most of the tutorials in this site. As you can see from this example though, the JFrame consists of several different components. To add and display widgets, we need to specify that it's the content pane we add to. The Content Pane is at the top of a containment hierarchy. A containment hierarchy is a tree of components that has a top-level container (in this case the JFrame) as its root. As you start to work down the tree, we use other non-top-level containers such as a JPanel to hold widgets. 22.4 EventQueue.invokeLater() The invokelater() method places the application on the Swing Event Queue. It is used to prevent GUI from hanging in certain situations. This topic is an advanced concept and we should not worry right now about it. EventQueue.invokeLater(new Runnable() { public void run() { // gui codes should be placed here. ); Example:

import javax.swing.eventqueue; public class Example extends JFrame { public Example() { settitle("simple example"); setsize(300, 200); setlocationrelativeto(null); setdefaultcloseoperation(exit_on_close); EventQueue.invokeLater(new Runnable() { public void run() { ); Example ex = new Example(); ex.setvisible(true); While this code is very small, the application window can do quite a lot. It can be resized, maximized, minimized. All the complexity that comes with it has been hidden from the application programmer. import javax.swing.eventqueue; Here we import Swing classes, that will be used in the code example. public class Example extends JFrame { The Example class inherits from the JFrame widget. JFrame is a toplevel container, which is used for placing other widgets. settitle("simple example"); Here we set the title of the window using the settitle() method. setsize(300, 200); This code will resize the window to be 300px wide and 200px tall. setlocationrelativeto(null); This line will center the window on the screen.

setdefaultcloseoperation(exit_on_close); This method will close the window, if we click on the close button of the titlebar. By default nothing happens. EventQueue.invokeLater(new Runnable() { public void run() { Example ex = new Example(); ex.setvisible(true); ); We create an instance of our code example and make it visible on the screen. 22.5 JButton In our next example, we will have a button. When we click on the button, the application terminates. import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.jbutton; import javax.swing.jpanel; import javax.swing.eventqueue; public class Example extends JFrame { // constructor public Example() { initui(); // initialize GUI components public final void initui() {

JPanel panel = new JPanel(); getcontentpane().add(panel); panel.setlayout(null); JButton quitbutton = new JButton("Quit"); quitbutton.setbounds(50, 60, 80, 30); //Button Event quitbutton.addactionlistener(new ActionListener() { public void actionperformed(actionevent event) { ); System.exit(0); panel.add(quitbutton); settitle("quit button"); setsize(300, 200); setlocationrelativeto(null); setdefaultcloseoperation(exit_on_close); // main method EventQueue.invokeLater(new Runnable() { public void run() { Example ex = new Example(); ex.setvisible(true); ); We position a JButton on the window. We will add an action listener to this button. public Example() { initui(); It is a good programming practice to put the code that creates the GUI inside a specific method. JPanel panel = new JPanel(); getcontentpane().add(panel); We create a JPanel component. It is a generic lightweight container. We add the JPanel to the JFrame. panel.setlayout(null);

By default, the JPanel has a FlowLayout manager. The layout manager is used to place widgets onto the containers. If we call setlayout(null) we can position our components absolutely. For this, we use the setbounds() method. JButton quitbutton = new JButton("Quit"); quitbutton.setbounds(50, 60, 80, 30); quitbutton.addactionlistener(new ActionListener() { public void actionperformed(actionevent event) { System.exit(0); ); Here we create a button. We position it by calling the setbounds() method. Then we add an action listener. The action listener will be called, when we perform an action on the button. In our case, if we click on the button. The click will terminate the application. panel.add(quitbutton); In order to show the quit button, we must add it to the panel. 22.6 Tooltip Tooltips are part of the internal application's help system. The Swing shows a small rectangular window, if we hover a mouse pointer over an object. import javax.swing.jbutton; import javax.swing.jpanel; import javax.swing.eventqueue; public class Example extends JFrame {

public Example() { initui(); public final void initui() { JPanel panel = new JPanel(); getcontentpane().add(panel); panel.setlayout(null); panel.settooltiptext("a Panel container"); JButton button = new JButton("Button"); button.setbounds(100, 60, 100, 30); button.settooltiptext("a button component"); panel.add(button); settitle("tooltip"); setsize(300, 200); setlocationrelativeto(null); setdefaultcloseoperation(exit_on_close); EventQueue.invokeLater(new Runnable() { public void run() { Example ex = new Example(); ex.setvisible(true); ); In the example, we set the tooltip for the frame and the button. panel.settooltiptext("a Panel container"); To enable a tooltip, we call the settooltiptext() method.

22.7 JLabel Component JLabel is a simple component for displaying text, images or both. It does not react to input events. import java.awt.borderlayout; import java.awt.color; import java.awt.font; import javax.swing.jlabel; import javax.swing.jpanel; public class MyLabel extends JFrame { public MyLabel() { settitle("no Sleep"); String lyrics = "<html>it's way too late to think of<br>" + "Someone I would call now<br>" + "And neon signs got tired<br>" + "Red eye flights help the stars out<br>" + "I'm safe in a corner<br>" + "Just hours before me<br></html>"; JPanel panel = new JPanel(); panel.setlayout(new BorderLayout(10, 10)); JLabel label = new JLabel(lyrics); label.setfont(new Font("Georgia", Font.PLAIN, 14)); label.setforeground(new Color(50, 50, 25)); label.setbounds(105, 129, 46, 14); panel.add(label, BorderLayout.CENTER); add(panel); pack(); setdefaultcloseoperation(exit_on_close); MyLabel mylabel = new MyLabel(); mylabel.setvisible(true); In our example, we show lyrics of no sleep song from cardigans. We can use html tags in JLabelcomponent. We use the <br> tag to separate lines. JPanel panel = new JPanel(); panel.setlayout(new BorderLayout(10, 10)); We create a panel and set a BorderLayout manager. JLabel label = new JLabel(lyrics); label.setfont(new Font("Georgia", Font.PLAIN, 14)); label.setforeground(new Color(50, 50, 25));

Here we create the label component. We set it's font to plain georgia, 14 px tall. We also change the foreground color. panel.add(label, BorderLayout.CENTER); We put the label into the center of the panel. add(panel); pack(); The panel is added to the frame component. We call the pack() method, which will resize the window, so that all components are visible. 22.8 JCheckBox Component JCheckBox is a component that has two states. On and Off. It is a box with a label. If the check box is checked, it is represented by a tick in a box. A check box can be used to show/hide splashscreen at startup, toggle visibility of a toolbar etc. import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.jcheckbox; import javax.swing.eventqueue; public class CheckBoxExample extends JFrame { public CheckBoxExample() { initui(); public final void initui() { final JCheckBox checkbox = new JCheckBox("Show Title", true); checkbox.setbounds(37, 23, 127, 23); getcontentpane().setlayout(null); getcontentpane().add(checkbox); checkbox.addactionlistener(new ActionListener() { public void actionperformed(actionevent e) { boolean state = checkbox.isselected();

); if (state) { settitle("jcheckbox example"); else { settitle(""); setsize(280, 200); settitle("jcheckbox example"); setlocationrelativeto(null); setresizable(false); setdefaultcloseoperation(jframe.exit_on_close); EventQueue.invokeLater(new Runnable() { public void run() { CheckBoxExample ex = new CheckBoxExample(); ex.setvisible(true); ); Our code example shows or hides the title of the window depending on its state. JCheckBox checkbox = new JCheckBox("Show Title", true); Here we have a constructor for the checkbox. We provide text and state. boolean state = checkbox.isselected(); if (state) { settitle("jcheckbox example"); else { settitle(""); We find out the selection state of the check box. Depending on the state of the check box, we show or hide the title of the window.

22.9 JSlider JSlider is a component that lets the user graphically select a value by sliding a knob within a bounded interval. Our example will show a volume control. import java.awt.borderlayout; import java.awt.dimension; import javax.swing.borderfactory; import javax.swing.box; import javax.swing.boxlayout; import javax.swing.jlabel; import javax.swing.jpanel; import javax.swing.jslider; import javax.swing.eventqueue; import javax.swing.event.changeevent; import javax.swing.event.changelistener; public class SliderExample extends JFrame { private JSlider slider; private JLabel label; public SliderExample() { initui(); public final void initui() { JPanel panel = new JPanel(); panel.setlayout(new BoxLayout(panel, BoxLayout.X_AXIS)); panel.setborder(borderfactory.createemptyborder(40, 40, 40, 40)); setlayout(new BorderLayout()); panel.add(box.createhorizontalglue()); slider = new JSlider(0, 150, 0); slider.setpreferredsize(new Dimension(150, 30)); slider.addchangelistener(new ChangeListener() { public void statechanged(changeevent event) { int value = slider.getvalue(); if (value == 0) { label.settext("< "); else if (value > 0 && value <= 30) { label.settext("< )"); else if (value > 30 && value < 80) { label.settext("< ))"); else { label.settext("< )))"); ); panel.add(slider); label = new JLabel("< ",JLabel.CENTER); panel.add(label); panel.add(box.createhorizontalglue()); add(panel, BorderLayout.CENTER); pack();

settitle("jslider"); setdefaultcloseoperation(exit_on_close); setlocationrelativeto(null); EventQueue.invokeLater(new Runnable() { ); public void run() { SliderExample ex = new SliderExample(); ex.setvisible(true); In the code example, we show a JSlider and a JLabel. By dragging the slider, we change the text on the label component. panel.setlayout(new BoxLayout(panel, BoxLayout.X_AXIS)); panel.setborder(borderfactory.createemptyborder(40, 40, 40, 40)); We creare a 40px border around the panel. panel.add(box.createhorizontalglue()); We put resizable space to bo both sides, left and right. It is to prevent JSlider from growing to unnatural sizes. slider = new JSlider(0, 150, 0); This is a JSlider constructor. The parameters are minimum value, maximum value and current value. slider.addchangelistener(new ChangeListener() {... ); We add a ChangeListener to the slider. Inside the listener, we determine the current slider value and update the label accordingly.

22.10 JComboBox Combobox is a component that combines a button or editable field and a drop-down list. The user can select a value from the drop-down list, which appears at the user's request. If you make the combo box editable, then the combo box includes an editable field into which the user can type a value. import javax.swing.imageicon; import javax.swing.jcombobox; import javax.swing.jlabel; import javax.swing.jpanel; import javax.swing.eventqueue; import javax.swing.border.emptyborder; import java.awt.event.itemlistener; import java.awt.event.itemevent; import javax.swing.border.lineborder; import java.awt.color; public class ComboBoxExample extends JFrame { private JPanel contentpane; private JLabel display = null; private JComboBox combobox = null; final String[] authors = {"Leo Tolstoy","John Galsworthy","Honore de Balzac"; final String[] images = { "tolstoy.jpg","galsworthy.jpg","balzac.jpg",; public ComboBoxExample() { settitle("jcombobox"); setdefaultcloseoperation(jframe.exit_on_close); setbounds(100, 100, 315, 300); contentpane = new JPanel(); contentpane.setborder(new EmptyBorder(5, 5, 5, 5)); setcontentpane(contentpane); contentpane.setlayout(null); display = new JLabel(); display.setborder(new LineBorder(new Color(0, 0, 0))); display.setbounds(50, 26, 148, 162); contentpane.add(display); combobox = new JComboBox(authors); //Combobox Event declared here: itemstatechanged combobox.additemlistener(new ItemListener() { public void itemstatechanged(itemevent e) { if (e.getstatechange() == ItemEvent.SELECTED) { int index = combobox.getselectedindex(); display.seticon(new ImageIcon( ClassLoader.getSystemResource(images[index] ))); ); combobox.setselectedindex(-1); combobox.setbounds(50, 199, 148, 20);

contentpane.add(combobox); EventQueue.invokeLater(new Runnable() { public void run() { ComboBoxExample frame = new ComboBoxExample(); frame.setvisible(true); ); In our example, we have two components. A label and a combobox. We have three names of famous novelists in our combobox. If we select a name, an image is displayed in the label. display = new JLabel(); The display area is a simple JLabel. combobox = new JComboBox(authors); combobox.setselectedindex(-1); The constructor of the JComboBox takes a string array of novelists. If we provide -1 as an argument in the setselectedindex() method, no item to be selected. combobox.additemlistener( ); We add an ItemListener to our combobox. In the event handler, we get the selected index of the combobox and set an appropriate icon for the label. The selected item is an index to the array of images. 22.11 JToggleButton

JToggleButton is a button that has two states. Pressed and not pressed. You toggle between these two states by clicking on it. There are situations where this functionality fits well. import javax.swing.jpanel; import javax.swing.eventqueue; import javax.swing.border.emptyborder; import javax.swing.border.lineborder; import javax.swing.jtogglebutton; import java.awt.color; import java.awt.event.actionevent; import java.awt.event.actionlistener; public class ToggleButtonSample extends JFrame { private JPanel contentpane; private JToggleButton redbutton; private JToggleButton greenbutton; private JToggleButton bluebutton; private JPanel display; public ToggleButtonSample() { setdefaultcloseoperation(jframe.exit_on_close); setbounds(100, 100, 302, 245); contentpane = new JPanel(); contentpane.setborder(new EmptyBorder(5, 5, 5, 5)); setcontentpane(contentpane); contentpane.setlayout(null); display = new JPanel(); display.setbounds(155, 27, 121, 113); display.setborder(lineborder.creategraylineborder()); display.setbackground(color.black); contentpane.add(display); redbutton = new JToggleButton("red"); redbutton.addactionlistener(new ActionListener() { public void actionperformed(actionevent e) { Color color = display.getbackground(); int red = color.getred(); int green = color.getgreen(); int blue = color.getblue(); if (e.getactioncommand().equals("red")) { if (red == 0) { red = 255; else { red = 0; Color setcol = new Color(red, green, blue); display.setbackground(setcol); ); redbutton.setbounds(10, 27, 121, 23); contentpane.add(redbutton); greenbutton = new JToggleButton("green"); greenbutton.addactionlistener(new ActionListener() {

public void actionperformed(actionevent e) { Color color = display.getbackground(); int red = color.getred(); int green = color.getgreen(); int blue = color.getblue(); if (e.getactioncommand().equals("green")) { if (green == 0) { green = 255; else { green = 0; Color setcol = new Color(red, green, blue); display.setbackground(setcol); ); greenbutton.setbounds(10, 65, 121, 23); contentpane.add(greenbutton); bluebutton = new JToggleButton("blue"); bluebutton.addactionlistener(new ActionListener() { public void actionperformed(actionevent e) { Color color = display.getbackground(); int red = color.getred(); int green = color.getgreen(); int blue = color.getblue(); if (e.getactioncommand().equals("blue")) { if (blue == 0) { blue = 255; else { blue = 0; Color setcol = new Color(red, green, blue); display.setbackground(setcol); ); bluebutton.setbounds(10, 100, 121, 23); contentpane.add(bluebutton); EventQueue.invokeLater(new Runnable() { public void run() { ToggleButtonSample frame = new ToggleButtonSample(); frame.setvisible(true); ); The example has one panel and three toggle buttons. We set the background color of the display panel to black. The toggle buttons will toggle the red, green and blue parts of the color value. The background color will depend on which togglebuttons we have pressed.

Color color = display.getbackground(); int red = color.getred(); int green = color.getgreen(); int blue = color.getblue(); In the actionperformed method, we determine the current red, green, blue parts of the display background color. if (e.getactioncommand().equals("red")) { if (red == 0) { red = 255; else { red = 0; We determine, which button was toggled, and update the color part of the RGB value accordingly. Color setcol = new Color(red, green, blue); display.setbackground(setcol); Here a new color is created and the display panel is updated to a new color.