Introduction to JAVA GUI Programming

CSC 308 2.0 System Development with Java Introduction to JAVA GUI Programming Budditha Hettige Department of Statistics and Computer Science Graph...
14 downloads 0 Views 1MB Size
CSC 308 2.0

System Development with Java

Introduction to JAVA GUI Programming Budditha Hettige Department of Statistics and Computer Science

Graphical User Interface • Many Java application use a graphical user interface or GUI • A GUI is a graphical window or windows that provide interaction with the user. • GUI‟s accept input from: – the keyboard – a mouse.

• A window in a GUI consists of components that: – present data to the user – allow interaction with the application. Budditha Hettige

2

Introduction • Some common GUI components are: – buttons, labels, text fields, check boxes, radio buttons, combo boxes, and sliders.

Budditha Hettige

3

GUI Programming • GUI programs are event-driven • Basic types of GUI Programs – Stand-alone applications – Applets

• Stranded GUI library – AWT – SWINIG

Budditha Hettige

4

Abstract Windowing Toolkit(AWT) • IS a Original Java GUI API • Very limited in capability – Few components – API not well structured, particularly event handling for user actions – Not entirely portable (used native widgets)

Budditha Hettige

5

JFC/Swing • Java Foundation Classes (or “Swing”) – Replacement for AWT (although does share some classes) – Also provide basis for developing new GUI features (which are being continually added)

• What does Swing include? – – – – – –

100% Java Swing components (more, and more sophisticated) Pluggable Look and Feel Support Accessibility API Better graphics support (Java 2D) Drag and Drop Budditha Hettige

6

JFC/Swing cont… • Disadvantages – Can be slow (resource hungry) – Large complex API (big learning curve) – Many features best suited for GUI builders, IDEs

• Important to use Swing and not AWT – Swing is the recommended way to build Java GUIs

Budditha Hettige

7

Design Stages of the GUI 1. Design the user interface – Organising pre-built GUI components to build windows, dialogs – E.g buttons, tables, menus, etc

2. Writing the application logic – What does the application do?

3. Writing event-handling code to tie the GUI components to the application logic

Budditha Hettige

8

User interface • A GUI is built in layers. • Bottom most layer is the window (Container) – Contains all other components – Can provide basic features like maximise/minimise buttons, title bar, menu bar, etc

• On top of this are layered (Component) – Components, e.g. buttons, text fields – or intermediate containers, e.g. panels

• Arrangement of components in a contained is handled by a layout manager – Its job is to instruct components on how to arrange themselves so the GUI is drawn correctly. Budditha Hettige

9

The containment hierarchy • This layered GUI can be viewed as a hierarchy of components – NOT an inheritance hierarchy, – It just describes how components are nested one within another

Budditha Hettige

10

GUI Application Jframe

Budditha Hettige

11

The containment hierarchy JFrame

JButton

JButton

JLabel

Budditha Hettige

JPanel

JTextField

12

Swing Top level containers • JWindow – Basic no frills window, just a square on the screen

• JFrame – The basic Swing window. Offers basic window controls, resizable

• JDialog – For building dialog boxes, e.g. File open/save

• JApplet – For building applets, embedded into a web page

Budditha Hettige

13

New containers (Netbeans)

Budditha Hettige

14

SWING containers • Panel • Scroll Pane • Tool Bar etc

Budditha Hettige

15

Working with JFrames • Many different possibilities, but the basics include: – Setting window title – Setting location on screen – Setting size of window – Restricting resizes – Set close operation (exit the program), as by default it does nothing. Budditha Hettige

16

Example public class NewJFrame extends javax.swing.JFrame { public NewJFrame() { initComponents(); } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); } }

Budditha Hettige

17

Example close operation

private void initComponents() {

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Test Window"); setAlwaysOnTop(true);

Set title of the window

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 251, Short.MAX_VALUE)

);

Set size of the window

layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 189, Short.MAX_VALUE) ); } Budditha Hettige

18

Adding Components to a Frame • A JFrame has several areas – Window decorations – (Optional) Menu bar – Content pane

• Content pane is where components are added. – Content pane is a Container object – Obtain reference to the content pane, and then add another component to it JFrame frame = new JFrame(“Example”); JButton button = new JButton(“Click me!”); frame.getContentPane().add( button );

Budditha Hettige

19

Adding Components • Very common to extend the Swing components, particularly JFrame – Create your own specialised versions – May include a fixed set of components – Provide extra methods for working with those components, etc. – Encapsulates how the GUI is constructed

• Slightly different to Visual Basic where one tends to just use the basic components

Budditha Hettige

20

Layout Managers • Responsible for layout out (arranging) components in a Container • Several different types with different uses • None of them provide for precise x-y alignment, unlike VB forms

Budditha Hettige

21

Border Layout • This is the default layout for JFrame • Divides the content pane into 5 areas (north, south, east, west, center) • Areas are expanded/contracted as needed, along with their contents. – Therefore ignores preferred size of the components.

• Center is the default if not specified. • Adding two components to the same zone means they get added one on top of the other – Instead add the components to a JPanel, and then add that instead. Budditha Hettige

22

Border Layout X NORTH

WEST

CENTER

EAST

SOUTH

Budditha Hettige

23

Grid Layout • Divides the container into a rectangular grid – Configurable number rows/columns

• Each grid location is of equal size, one component assigned to each. • Automatically assigns components to next available location

Budditha Hettige

24

Other layout managers • Flow Layout (default for JPanel) – Arranges components left-to-right – Used to arrange buttons on a panel

• Card Layout – Arranges components like a deck of cards – Only one card visible at a time

• Box Layout, Grid Bag Layout – Very sophisticated managers, used by GUI builders for very precise GUI designs. – Not recommended for hand use!

Budditha Hettige

25

Menus • A Jframe can have only a single menu bar – Instance of the Jmenu object

• A menu bar can have several menus on it – Instances of the Jmenu object

• A menu can have several items on it – Instances of the JmenuItem object

• Example

Budditha Hettige

26

Controls

Budditha Hettige

27

Swing Controls - Label • Use to display text • Codes private javax.swing.JLabel jLabel1; jLabel1 = new javax.swing.JLabel(); // create object jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); jLabel1.setText("jLabel1"); // Set lables

// Set fonts

// place the control in to the pane layout.setVerticalGroup( ..... .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) layout.setHorizontalGroup( ..... .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) Budditha Hettige

28

Text field • Use to input/output a text • Sample Codes private javax.swing.JTextField jTextField1; jTextField1 = new javax.swing.JTextField();

jTextField1.setText("jTextField1"); layout.setVerticalGroup( ..... .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE) layout.setHorizontalGroup( ..... .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) Budditha Hettige

29

Text field data access • Set text jTextField1.setText(“text");

• Get text form the text field String data; data = jTextField1.getText();

Budditha Hettige

30

Buttons • • • •

Place the button Rename the button Add action event Modify the function private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: }

Budditha Hettige

31

Combo box • Select a item from a list • Codes private javax.swing.JComboBox jComboBox1;

jComboBox1 = new javax.swing.JComboBox(); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

Budditha Hettige

32

Data Access • Get selected item from the combo box String ss; ss = (String)jComboBox1.getSelectedItem();

Type casting

Budditha Hettige

33

Event Handling

Budditha Hettige

34

Handling Basics • Swing Events Examples – Actions – Mouse Events – Window Events

Budditha Hettige

35

Event Handling Conventions • Event object typically extend java.awt.Event – Some of the „newer‟ ones don‟t

• Events share some common attributes – a timestamp, source object, etc

Budditha Hettige

36

Action Events • Very tedious implementation if all activities were dealt with as individual clicks • Swing provides higher level „action‟ event • Meaning of event depends on component – E.g. button click, menu selection, etc

• Basic classes: – ActionEvent – identifies action, key modifiers, etc – ActionListener – single actionPerformed method – addActionListener, removeActionListener methods on Component

Budditha Hettige

37

Code Use

Action Listener java.awt.event.ActionListener Action Event java.awt.event.ActionEvent Code jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } });

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: }

Budditha Hettige

38

Event Handling Conventions

Budditha Hettige

39

Mouse Events • Natural for Swing to expose mouse-related events – It‟s how the user interacts with the GUI

• MouseListener interface describes the basic events • Each method accepts a MouseEvent object parameter • java.awt.Component has add/remove listener methods

Budditha Hettige

40

Mouse Events

Budditha Hettige

41

Mouse Events • So, capturing basic mouse events involves: – Creating an implementation of MouseListener – Calling addMouseListener on one or more Components to register it

Budditha Hettige

42

Window Events • Swing allows the capturing of window related events – Activate, deactivate, minimise, open, close etc

• setDefaultCloseOperation is only useful if you don‟t want to do anything complex • Basic classes/methods – WindowEvent – identifies Window – WindowListener – range of methods – addWindowListener, removeWindowListener methods on JFrame, JWindow, JDialog

Budditha Hettige

43

Other Swing Events • More Mouse events – Mouse motion, mouse wheels

• Item events – Selecting/deselecting items in lists, checkboxes, etc

• Key Events – Raw keyboard input

• Tree Events – Opening/closing nodes in a tree component

• Drag and drop • …and many more. See javax.swing.event and java.awt.event packages. Budditha Hettige

44

Mouse events Use

Mouse Event Mouse Listener

java.awt.event.MouseEvent java.awt.event.MouseAdapter

Code jButton2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { jButton2MouseEntered(evt); } }); private void jButton2MouseEntered(java.awt.event.MouseEvent evt) { // TODO add your handling code here: }

Budditha Hettige

45

Key events Use java.awt.event.KeyEvent Code jButton2.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jButton2KeyPressed(evt); } }); private void jButton2KeyPressed(java.awt.event.KeyEvent evt) { // TODO add your handling code here: } Budditha Hettige

46

Dialog Boxes • A dialog box is a small graphical window that displays a message to the user or requests input. • A variety of dialog boxes can be displayed using the JOptionPane class. – Message Dialog - a dialog box that displays a message. – Input Dialog - a dialog box that prompts the user for input. – Confirm Dialog This is a dialog box that asks the user a Yes/No question. Budditha Hettige

47

Dialog Boxes The JOptionPane class provides static methods to display each type of dialog box.

Budditha Hettige

48

Message Dialogs • JOptionPane.showMessageDialog method is used to display a message dialog. • There are several overloaded versions of this method. showMessageDialog(Component parent, Object message) showMessageDialog(Component parent, Object message, String title, int messageType)

Budditha Hettige

49

Message Dialogs JOptionPane.showMessageDialog(null, "Hello World");

• The first argument can be a reference to a graphical component. – The dialog box is displayed inside that component. – If null is passed as the first argument, which causes the dialog box to be displayed in the center of the screen.

• The second argument is the message that is to be displayed.

Budditha Hettige

50

Message Dialogs • By default the dialog box has: – the string “Message” displayed in its title bar, and – an information icon (showing the letter “i) is displayed. JOptionPane.showMessageDialog(null, "Invalid Data", "My Message Box", JOptionPane.ERROR_MESSAGE);

• The third option is the title bar text.

Budditha Hettige

51

Message Dialogs • These constants can be use to control the icon that is displayed. – JOptionPane.ERROR_MESSAGE – JOptionPane.INFORMATION_MESSAGE – JOptionPane.WARNING_MESSAGE – JOptionPane.QUESTION_MESSAGE – JOptionPane.PLAIN_MESSAGE

Budditha Hettige

52

Message Dialogs

Budditha Hettige

53

Input Dialogs • An input dialog is a quick and simple way to ask the user to enter data. • The dialog displays a text field, an Ok button and a Cancel button. • If Ok is pressed, the dialog returns the user‟s input. • If Cancel is pressed, the dialog returns null.

Budditha Hettige

54

Input Dialogs • The JOptionPane has several overloaded versions of the static showInputDialog method. • Here are two of them: showInputDialog(Object message) showInputDialog(Component parent, Object message, String title, int messageType) Budditha Hettige

55

Input Dialogs String name; name = JOptionPane.showInputDialog("Enter your name.");

• The argument passed to the method is the message to display. • If the user clicks on the OK button, name references the string entered by the user. • If the user clicks on the Cancel button, name references null.

Budditha Hettige

56

Input Dialogs • By default the input dialog box: – has the string “Input” in its title bar, and – displays a question icon. String value; value = JOptionPane.showInputDialog(null, "Enter the value again.", "Enter Carefully!", JOptionPane.WARNING_MESSAGE);

Budditha Hettige

57

Confirm Dialog • A confirm dialog box typically asks the user a yes or no question. • By default Yes, No, and Cancel buttons are displayed. • The showConfirmDialog method is used to display a confirm dialog box. • There are several overloaded versions of this method. int showConfirmDialog(Component parent, Object message) int showConfirmDialog(Component parent, Object message, String title, int optionType) Budditha Hettige

58

Confirm Dialog int value; value = JOptionPane.showConfirmDialog(null, "Are you sure?");

• By default the confirm dialog box displays: – “Select an Option” in its title bar, – Yes, No, and Cancel buttons.

Budditha Hettige

59

Confirm Dialog • The showConfirmDialog method returns an integer that represents the button clicked by the user. • The button that was clicked is determined by comparing the method‟s return value to one of the following constants: – JOptionPane.YES_OPTION – JOptionPane.NO_OPTION – JOptionPane.CANCEL_OPTION Budditha Hettige

60

Confirm Dialog int value; value = JOptionPane.showConfirmDialog(null, "Are you sure?"); if (value == JOptionPane.YES_OPTION){ //If the user clicked Yes, this code is executed. } else if (value == JOptionPane.NO_OPTION){ //If the user clicked no, this code is executed. } else if (value == JOptionPane.CANCEL_OPTION){ //If the user clicked Cancel, this code is executed. }

Budditha Hettige

61

Confirm Dialog int value; value = JOptionPane.showConfirmDialog(null, "Are you sure?", "Please Confirm", JOptionPane.YES_NO_OPTION);

• One of the following constants can be used for the fourth parameter: – JOptionPane.YES_NO_OPTION – JOptionPane.YES_NO_CANCEL_OPTION

Example: TestAverageDialog.java

Budditha Hettige

62

Example - Calculator Create a calculator application to calculate the numbers and print the result Supported Operators + - / * ^ and squrt Supported action C , < (Back) Display – total with number of numbers used for calculation

Budditha Hettige

63