• No results found

Graphical User Interfaces

N/A
N/A
Protected

Academic year: 2020

Share "Graphical User Interfaces"

Copied!
54
0
0

Loading.... (view fulltext now)

Full text

(1)

Graphical User Interfaces

(2)

AWT and Swing

• Java provides two sets of components for GUI

programming:

– AWT: classes in the java.awt package

(3)

Abstract Window Toolkit (AWT)

• The Abstract Window Toolkit is a portable GUI library.

• AWT provides the connection between your application and the native GUI.

• AWT provides a high-level abstraction since it hides you from the underlying details of the GUI your program will be running on.

• AWT components depend on native code counterparts (called peers) to handle their functionality. Thus, these components are often called heavyweight components.

(4)

Swing

• Swing implements GUI components that build on

AWT technology.

• Swing is implemented entirely in Java.

• Swing components do not depend on peers to

handle their functionality. Thus, these

components are often called lightweight

components.

(5)
(6)
(7)

AWT vs SWING

Java AWT Java Swing 1) AWT components are

platform-dependent.

Java swing components are

platform-independent.

2) AWT components are heavyweight. Swing components are lightweight. 3) AWT doesn't support pluggable look and

feel. Swing supports pluggable look and feel.

4) AWT provides less components than Swing.

Swing provides more powerful

components such as tables, lists,

scrollpanes, colorchooser, tabbedpane etc.

5)

AWT doesn't follows MVC(Model View Controller) where model represents data, view represents presentation and controller acts as an interface between model and view.

(8)

AWT: Pros and Cons

• Pros

– Speed: native components speed performance.

– Look and feel: AWT components more closely reflect the look and feel of the OS they run on.

• Cons

– Portability: use of native peers creates platform specific limitations.

– Features: AWT supports only the lowest common denominator—e.g. no tool tips or icons.

(9)

Swing: Pros and Cons

• Pros

– Portability: Pure Java implementation.

– Features: Not limited by native components.

– Look and Feel: Pluggable look and feel. Components automatically have the look and feel of the OS their running on.

• Cons

– Performance: Swing components handle their own

painting (instead of using APIs like DirectX on Windows). – Look and Feel: May look slightly different than native

(10)
(11)

Top-level Containers

• There are three top-level Swing containers

– JFrame

: window that has decorations,

such as a border, a title, and buttons for

iconifying and closing the window

– JDialog

: a window that's dependent

on another window

– JApplet

: applet's display area within a

(12)

Containment Hierarchy

• In the Hello World example, there was a

content pane.

• Every top-level container indirectly

contains an intermediate container known

as a content pane.

• As a rule, the content pane contains,

directly or indirectly, all of the visible

components in the window's GUI.

• To add a component to a container, you

use one of the various forms of the add

method.

(13)

Containment Hierarchy

JFrame

content pane

JLabel

(14)

Swing has a lot of classes

containers

things that hold other things eg JFrame

controls

User I/O widgets eg JButton

(15)

Containers

top level containers - JFrame JApplet JDialog

general purpose containers - panel

scroll pane split pane tabbed pane tool bar

(16)

JPanel ( in createAndShowGUI)

JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("I am a JFrame");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(20,30,300,100);

frame.setLayout(null); //Create a panel

JPanel myPanel = new JPanel();

myPanel.setBackground(new Color(255,3,25)); myPanel.setOpaque(true);

//Make it the content pane.

frame.setContentPane(myPanel); frame.setVisible(true);

(17)

JPanel

• Is a subclass of JComponent

• So are all the other Swing components except

the top-level containers

• You can add a border

• And a tool-tip

(18)

Tooltip and border

..

myPanel.setOpaque(true); myPanel.setToolTipText("I'm a JPanel"); myPanel.setBorder(BorderFactory.createLineBorder(Color.white)); frame.setContentPane(myPanel); ..

(19)

JSplitPane

..

setLayout(null);

//Create a split pane

JSplitPane myPane = new JSplitPane(); myPane.setOpaque(true);

frame.setContentPane(myPane); frame.setVisible(true);

(20)

JSplitPane with JPanels

//Create a split pane

JSplitPane myPane = new JSplitPane(); myPane.setOpaque(true);

myPane.setDividerLocation(150); // make two panels

JPanel right = new JPanel();

right.setBackground(new Color(255,0,0)); JPanel left = new JPanel();

left.setBackground(new Color(0,255,0)); // set as left and right in split

myPane.setRightComponent(right); myPane.setLeftComponent(left);

(21)

Hello World Example

import javax.swing.*;

public class HelloWorldSwing {

public static void main(String[] args) {

JFrame frame = new JFrame("HelloWorldSwing"); final JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } }

(22)

JButton class

JButton(): creates a button with no text and icon.

JButton(String s): creates a button with the specified text.

JButton(Icon i): creates a button with the specified icon object. Methods:

public void setText(String s): is used to set specified text on button. public String getText(): is used to return the text of the button.

public void setEnabled(boolean b): is used to enable or disable the button. public void setIcon(Icon b): is used to set the specified Icon on the button. public Icon getIcon(): is used to get the Icon of the button.

(23)

JTextField

• For single-line text input

• Methods getText, setText

(24)

Example of JTextField

• Check Main object fields for label and textfield • Make a panel, set as content pane

• Make and add text field • Make and add a label

JPanel myPanel = new JPanel(); JTextField t = new JTextField(10); myPanel.add(t);

(25)

JTextArea

JPanel myPanel = new JPanel();

JTextArea t = new JTextArea("Type here",5, 20); myPanel.add(t);

(26)

ImageIcon

• Some Swing components can be decorated with an

icon—a fixed-size image.

• A Swing icon is an object that adheres to the Icon interface.

• Swing provides a particularly useful implementation of the Icon interface: ImageIcon.

(27)

ImageIcon Example

import javax.swing.*;

public class ImageIconExample extends JFrame { public static void main(String[] args) {

JFrame frame = new JFrame("ImageIcon Example"); ImageIcon icon = new ImageIcon("smallfrog.jpg"); JPanel panel = new JPanel();

JButton button = new JButton(icon); panel.add(button);

frame.getContentPane().add(panel); frame.setVisible(true);

} }

(28)

JCheckBox

• You may not want to be alerted every time the

user selects or deselects a checkbox.

• A more common use is to check the state of the

button when the user clicks a button signifying

that he/she is done and ready to advance.

(29)

JRadioButton

• ButtonGroup

ensures that only one radio

button in the group can be selected at a time.

• setSelected

sets initial state. (Good for

defaults).

(30)

JRadiobutton andJCheckBox

import javax.swing.*; class Check1

{

public static void main(String g[]) {

JFrame f=new JFrame("Checkbox"); JPanel p=new JPanel();

JCheckBox c1=new JCheckBox("Male",true); JCheckBox c2=new JCheckBox("FeMale"); JRadioButton r1=new JRadioButton("B.tech"); JRadioButton r2=new JRadioButton("M.tech"); p.add(c1); p.add(c2); p.add(r1); p.add(r2); f.getContentPane().add(p); f.setSize(300,300); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}

(31)

JComboBox

• A combo box is a button that when pressed,

presents a list of items that can be selected.

(32)

import javax.swing.*; public class Combo {

Combo(){

JFrame f=new JFrame("Combo ex");

JComboBox cb=new JComboBox(); cb.addItem("Red"); cb.addItem("Blue"); cb.addItem("Pink"); cb.setBounds(50,50,100,30); f.add(cb); f.setLayout(null); f.setSize(400,500); f.setVisible(true); }

public static void main(String[] args) { new Combo();

} }

(33)

Dialogs - JOptionPane

• Dialogs are windows that are more limited than frames.

• Every dialog is dependent on a frame. When that frame is destroyed, so are its dependent dialogs. When the frame is iconified, its dependent dialogs disappear from the screen. When the frame is deiconified, its dependent dialogs return to the screen.

• To create simple dialogs, use the JOptionPane class. • The dialogs that JOptionPane provides are modal.

• When a modal dialog is visible, it blocks user input to all other windows in the program.

(34)

JOptionPane

Examples

// show an error dialog

JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);

(35)

JOptionPane

Examples

// show Yes/No dialog

int x = JOptionPane.showConfirmDialog(null,

"choose one", "choose one", JOptionPane.YES_NO_OPTION); System.out.println("User clicked button " + x);

(36)

JOptionPane

Examples

// show input dialog

String inputValue = JOptionPane.showInputDialog("Please input “ +

“a value");

(37)

Layout Management

• Layout managers control the size and arrangement of components in a container.

• There are 6 common layout managers:

– BorderLayout (demo’d) – BoxLayout – FlowLayout (demo’d) – GridBagLayout – GridLayout (demo’d) – CardLayout (demo’d)

(38)
(39)

FlowLayout

• Components are placed in a row from left to right in the order in which they are added.

• A new row is started when no more components can fit in the current row.

• The components are centered in each row by default.

• The programmer can specify the size of both the vertical and horizontal gaps between the components.

(40)

FlowLayout

Example

public class FlowLayoutTest extends JFrame { JButton b1=new JButton("Red"),

b2=new JButton("Green"),b3=new JButton("Blue"), b4=new JButton("Yellow"),b5=newJButton("Pink"); public FlowLayoutTest() {

setTitle("FlowLayout Test");

Container pane = getContentPane(); pane.setLayout(new FlowLayout()); setBounds(0,0,400,100);

pane.add(b1); pane.add(b2); pane.add(b3); pane.add(b4); pane.add(b5);

}

public static void main(String args[]) { JFrame f = new FlowLayoutTest();

f.setVisible(true); }

(41)

BorderLayout

• Defines five locations where a component or components can be added:

– North, South, East, West, and Center

• The programmer specifies the area in which a component should appear.

• The relative dimensions of the areas are governed by the size of the components added to them.

(42)

BorderLayout

North

South

(43)

Border-Layout

Example

public class BorderLayoutTest extends JFrame { JButton b1=new JButton("Red"),

b2=new JButton("Green"),b3=new JButton("Blue"), b4=new JButton("Yellow"),b5=new JButton("Pink"); public BorderLayoutTest() {

setTitle("BorderLayout Test");

Container pane = getContentPane(); pane.setLayout(new BorderLayout()); setBounds(0,0,400,150); pane.add(b1,"North"); pane.add(b2,"South"); pane.add(b3,"East"); pane.add(b4,"West"); pane.add(b5,"Center"); }

public static void main(String args[]) { JFrame f = new BorderLayoutTest();

f.setVisible(true); }

}

(44)

GridLayout

• Components are placed in a grid with a user-specified number of columns and rows.

• Each component occupies exactly one grid cell. • Grid cells are filled left to right and top to bottom. • All cells in the grid are the same size.

• Specifying zero for either rows or columns means any number of items can be placed in that row or column.

(45)

GridLayout

Example

public class GridLayoutTest extends JFrame { JButton b1=new JButton("Red"),

b2=new JButton("Green"),b3=new JButton("Blue"), b4=new JButton("Yellow"),b5=new JButton("Pink"); public GridLayoutTest() {

setTitle("GridLayout Test");

Container pane = getContentPane(); pane.setLayout(new GridLayout(2,3)); setBounds(0,0,300,100);

pane.add(b1); pane.add(b2); pane.add(b3); pane.add(b4); pane.add(b5);

}

public static void main(String args[]) { JFrame f = new GridLayoutTest();

f.setVisible(true); }

(46)

CardLayout

• Components governed by a card layout are "stacked"

such that only one component is displayed on the screen at any one time.

• Components are ordered according to the order in which they were added to the container.

• Methods control which component is currently visible in the container.

• CardLayouts might be appropriate for wizards (with the

(47)

CardLayout

Example (1 of 3)

public class CardLayoutTest extends JFrame implements ActionListener {

JButton b1 = new JButton("Red"),b2 = new JButton("Green"), b3 = new JButton("Blue"),b4 = new JButton("Yellow"), b5 = new JButton("Pink");

CardLayout lo = new CardLayout(); Container pane; public CardLayoutTest() { setTitle("CardLayout Test"); pane = getContentPane(); pane.setLayout(lo); setBounds(0,0,200,100);

pane.add(b1,"1"); pane.add(b2,"2"); pane.add(b3,"3"); pane.add(b4,"4"); pane.add(b5,"5");

); }

(48)

CardLayout

Example (2 of 3)

public static void main(String args[]) { JFrame f = new CardLayoutTest();

f.setVisible(true); }

}

define the behavior when the user clicks a button: in this case, we advance to the next

(49)

CardLayout

Example (3 of 3)

Every arrow denotes a button click event. Our code reacts

to the click by advancing to the next card. Note that the

(50)

Menus

JMenuBar

JMenu JMenuItem

(51)

Menu

..

JMenuBar myMenuBar = new JMenuBar(); JMenu menu1 = new JMenu("File");

JMenuItem item = new JMenuItem("Exit");

menu1.add(item);

myMenuBar.add(menu1);

frame.setJMenuBar(myMenuBar); ..

(52)

JToolBar

..

.. frame is BorderLayout ..

JToolBar toolBar = new JToolBar("Test");

JButton butt1 = new JButton(new ImageIcon("icon.gif")); toolBar.add(butt1);

..

(53)

paint

• JComponents have a paint() method

• This is called by the system when it needs to

display the object

• Initially and eg after a re-size

• You can over-ride paint() to control the

appearance of the component

• This implies you sub-class the component

• The paint method has a Graphics object as a

parameter

• This is a context eg color, font etc

(54)

Example

public class MyFrame extends JFrame { public MyFrame() { super("Some title"); setDefaultCloseOperation(EXIT_ON_CLOSE); setBounds(20,30,230,180);

myPanel = new MyPanel();

myPanel.setOpaque(true); setContentPane(myPanel); setVisible(true); } MyPanel myPanel; }

public class MyPanel extends JPanel {

public void paint(Graphics g) {

g.drawLine(0,0,getWidth(),getHeight());

g.drawString("Hello",getWidth()/2,getHeight()/2); }

References

Related documents

– a major part of the JFC is a new set of user interface components called Swing.. AWT Swing Accessibility

AWT provides basic GUI functions such as buttons, frames and dialogs, and is implemented in native code in the Java interpreter.. By contrast, Swing is not implemented in native code

• To respond to an event for a particular GUI component, you must create a class that represents the event handler and implements an appropriate event-listener interface (p. 16),

2.2 WebBrowser Using JEditorPane and JToolBar 2.2.1 Swing Text Components and HTML Rendering.. 2.2.2 Swing Toolbars 2.3

• Method createImage uses parameter to determine proper Image subclass from which to instantiate Image object. createImage(

public void mousePressed( MouseEvent e ) // MouseListener Called when a mouse button is pressed with the mouse cursor on a component. public void mouseClicked( MouseEvent e )

13.18.1 Creational Design Patterns 13.18.2 Structural Design Patterns 13.18.3 Behavioral Design Patterns 13.18.4 Conclusion... All

• when you want a JCheckBox to respond to a user’s clicks, you can use the addItemListener() method to register the JCheckBox as the type of object that can create an ItemEvent..