+ All Categories
Home > Documents > Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Date post: 12-Jan-2016
Category:
Upload: paula-stephens
View: 214 times
Download: 2 times
Share this document with a friend
56
Graphical User Graphical User Interfaces (GUIs) Interfaces (GUIs) Chapter 13 Chapter 13 (available (available on the Web ) )
Transcript
Page 1: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Graphical User Interfaces (GUIs)Graphical User Interfaces (GUIs)

Chapter 13Chapter 13

(available (available on the Web))

Page 2: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

OverviewOverview

What is a GUI?What is a GUI? Creating GUIs in JavaCreating GUIs in Java GUI components & layout managersGUI components & layout managers GUI (sub)classesGUI (sub)classes Event controlEvent control

(getting the GUI to (getting the GUI to dodo somethingsomething)) NetBeans’ GUI design toolNetBeans’ GUI design tool

Page 3: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

What is a GUI?What is a GUI?

Graphical User InterfaceGraphical User Interface a graphical way to use the programa graphical way to use the program windows, icons, menus, pointing (WIMP)windows, icons, menus, pointing (WIMP)

Lots less typing for theLots less typing for theuseruser

Lots less things for themLots less things for themto rememberto remember see options by lookingsee options by looking

File Edit Help _ X

Mrph

Dpbl

Xvgl

Blah

Yuck

Eeew

Gross

OpenSave——Exit

Page 4: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Getting StartedGetting Started

Create a Java programCreate a Java program like the one’s we’ve been doing all alonglike the one’s we’ve been doing all along (later we’ll peek at making an applet)(later we’ll peek at making an applet)

Program class has a main methodProgram class has a main method compile & run program as usualcompile & run program as usual GUI window will appearGUI window will appear

» we’ll need to do something special to make sure our we’ll need to do something special to make sure our program ends when it’s supposed to!program ends when it’s supposed to!

Page 5: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Java GUIJava GUI

Java has two different GUI librariesJava has two different GUI libraries java.awt.*java.awt.* Frame, Label, …Frame, Label, … javax.swing.*javax.swing.* JFrame, JLabel, …JFrame, JLabel, … we need stuff from both of themwe need stuff from both of them

The Swing TutorialThe Swing Tutorial look up components in the following site: look up components in the following site:

http://java.sun.com/books/tutorial/uiswing

Page 6: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

The GUI WindowThe GUI Window

GUI starts with a window objectGUI starts with a window object give a title for the windowgive a title for the windowJFrame win = new JFrame(“My Win”);JFrame win = new JFrame(“My Win”);

Nothing happened!Nothing happened!win.setVisible(true);win.setVisible(true); it’s tiny!it’s tiny! but you can resize itbut you can resize it

win.setVisible(true)is the show/repaint command!

Page 7: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

The GUI WindowThe GUI Window

JFrame JFrame winwin = new JFrame(“ = new JFrame(“My WinMy Win”);”); win is a variable – will be the window objectwin is a variable – will be the window object JFrame is the class we’re creating an instance of JFrame is the class we’re creating an instance of

(class of windows)(class of windows) title of window (in title bar): “My Win”title of window (in title bar): “My Win”

winwin.setVisible(true);.setVisible(true); win is the window objectwin is the window object setVisible is the commandsetVisible is the command true is the argument true is the argument true = visible true = visible

Page 8: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Making it Bigger at the StartMaking it Bigger at the Start

Don’t want to have to re-size every windowDon’t want to have to re-size every windowwin.setSize(300, 200);win.setSize(300, 200); 300 pixels wide300 pixels wide 200 pixels tall200 pixels tall exactly how big that isexactly how big that is

depends on your screendepends on your screenresolution (number of pixels per inch)resolution (number of pixels per inch)

NOTE: dimensions are of outer edgesNOTE: dimensions are of outer edges

200

300

Page 9: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Our Window So FarOur Window So Far

Title barTitle bar cup of java iconcup of java icon title of windowtitle of window minimize, minimize,

maximize, maximize, close buttonsclose buttons

Note:Note: looks like other windows on your computerlooks like other windows on your computer

» will look like Mac window on Mac computerwill look like Mac window on Mac computer

Page 10: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Our Window So FarOur Window So Far

Window needs Window needs componentscomponents Components go into the Components go into the contentPanecontentPane

win.getContentPane()win.getContentPane() addadd method method

What can we add?What can we add? all kinds of stuff!all kinds of stuff!

contentPane

Page 11: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Some Swing ComponentsSome Swing Components

javax.swing.JLabeljavax.swing.JLabel javax.swing.JTextFieldjavax.swing.JTextField javax.swing.JButtonjavax.swing.JButton javax.swing.JComboBoxjavax.swing.JComboBox javax.swing.JCheckBoxjavax.swing.JCheckBox javax.swing.JRadioButtonjavax.swing.JRadioButton ……

Page 12: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

LabelsLabels

Label needs to know its textLabel needs to know its text need to tell the window to repaint itselfneed to tell the window to repaint itselfJLabel lbl1 = new JLabel(“Hello, World!”);JLabel lbl1 = new JLabel(“Hello, World!”);win.getContentPane.add(lbl1);win.getContentPane.add(lbl1);win.setVisible(true);win.setVisible(true);

Didn’t say where to put theDidn’t say where to put thelabel, so it filled the panelabel, so it filled the pane add method can be told where to put the objectadd method can be told where to put the object

Page 13: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Component PlacementComponent Placement

Default “layout” gives you five places to put Default “layout” gives you five places to put components:components: PAGE_START (NORTH)PAGE_START (NORTH) PAGE_END (SOUTH)PAGE_END (SOUTH) LINE_START (WEST)LINE_START (WEST) LINE_END (EAST)LINE_END (EAST) CENTERCENTER

Need to Need to import java.awt.*;import java.awt.*; use like: use like: BorderLayout.NORTHBorderLayout.NORTH

PAGE_START

PAGE_END

LIN

E_E

ND

LIN

E_S

TA

RT

CENTER

Page 14: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Text FieldsText Fields

Labels don’t do anythingLabels don’t do anything For text you can edit, use JTextFieldFor text you can edit, use JTextField

JTextField tf = new JTextField(“Initial Text”);JTextField tf = new JTextField(“Initial Text”);win.getContentPane().add(tf, win.getContentPane().add(tf,

BorderLayout.PAGE_END);BorderLayout.PAGE_END);win.setVisible(true);win.setVisible(true); small amount of plain textsmall amount of plain text JTextPane for more textJTextPane for more text

Page 15: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

The Content PaneThe Content Pane

Saying Saying win.getContentPane() win.getContentPane() every time is every time is getting oldgetting old let’s save the content pane in a variablelet’s save the content pane in a variableContainer pane = win.getContentPane();Container pane = win.getContentPane(); Container is the class for the content paneContainer is the class for the content pane pane is a variable – now referring to the content pane is a variable – now referring to the content

pane of our (only) windowpane of our (only) window» text uses “content” instead of “pane”text uses “content” instead of “pane”» it’s a variable, you can call it what you likeit’s a variable, you can call it what you like

Page 16: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

ButtonsButtons

Buttons can be clickedButtons can be clicked lets the user select an action to carry outlets the user select an action to carry outJButton b1 = new JButton(“OK”);JButton b1 = new JButton(“OK”);pane.add(b1);pane.add(b1);win.setVisible(true);win.setVisible(true); computer put it CENTER, computer put it CENTER,

right over the label, becauseright over the label, becausewe didn’t say where it wentwe didn’t say where it went

Page 17: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Window Layout ManagersWindow Layout Managers

It’s possible to tell the window exactly It’s possible to tell the window exactly where you want each piece you add to itwhere you want each piece you add to it how many pixels across, downhow many pixels across, down looks real good if you do it rightlooks real good if you do it right generally gets messed up user resizes windowgenerally gets messed up user resizes window

Easier and more portable to use managerEasier and more portable to use manager default manager: BorderLayoutdefault manager: BorderLayout others available: we’ll look at two moreothers available: we’ll look at two more

Page 18: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Window Layout ManagersWindow Layout Managers

Window layout managers in java.awtWindow layout managers in java.awt BorderLayoutBorderLayout CardLayoutCardLayout FlowLayoutFlowLayout GridBagLayoutGridBagLayout GridLayoutGridLayout

Each has its own way of determining what Each has its own way of determining what goes where…goes where…

We’ll look atBorderLayoutFlowLayoutGridLayout

Page 19: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

BorderLayoutBorderLayout

Five locations to place objectsFive locations to place objects objects in the same location are placed one on objects in the same location are placed one on

top of the othertop of the other objects are stretched or objects are stretched or

squashed in order to fill the squashed in order to fill the space allottedspace allotted

empty locations are not usedempty locations are not used(other objects expand)(other objects expand)

PAGE_START

PAGE_END

LIN

E_E

ND

LIN

E_S

TA

RT

CENTER

Page 20: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

FlowLayoutFlowLayout

FlowLayout just puts the objects into the FlowLayout just puts the objects into the window one after the otherwindow one after the other if there’s not enough room if there’s not enough room

across, it goes down to the across, it goes down to the next “line”next “line”

objects centred on each lineobjects centred on each line objects move around when objects move around when

window gets resizedwindow gets resized

FIRST SECOND

THIRD FOURTH

FIFTH

Page 21: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

GridLayoutGridLayout

Creates a small tableCreates a small table each object goes in the next cell of the tableeach object goes in the next cell of the table

Need to say how many Need to say how many rows & columnsrows & columns can also say how much can also say how much

space to leave between cellsspace to leave between cells

1st 2nd 3rd

Fourth Fifth

Page 22: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Choosing a Layout ManagerChoosing a Layout Manager

Create a new layout object and tell the content Create a new layout object and tell the content pane to use it (setLayout method)pane to use it (setLayout method) flow layoutflow layoutpane.setLayout(new FlowLayout());pane.setLayout(new FlowLayout()); border layoutborder layoutpane.setLayout(new BorderLayout());pane.setLayout(new BorderLayout()); grid layout (2 rows, 3 columns)grid layout (2 rows, 3 columns)pane.setLayout(new GridLayout(2, 3));pane.setLayout(new GridLayout(2, 3));

Page 23: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Some WindowsSome Windows

Page 24: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Putting it TogetherPutting it Together

We have created a lot of objectsWe have created a lot of objects window (JFrame), label (JLabel), text fields window (JFrame), label (JLabel), text fields

(JTextField), buttons (JButton)(JTextField), buttons (JButton) Want them all to work togetherWant them all to work together

but we’ve done it all in a very but we’ve done it all in a very proceduralprocedural way way should do should do object orientedobject oriented way way

Create a class for this kind of windowCreate a class for this kind of window create window objects as requiredcreate window objects as required

» (use main to test: create an object and show it)(use main to test: create an object and show it)

Page 25: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

GUI Window ClassGUI Window Class

Create a window class that inherits from the Java Create a window class that inherits from the Java window class (javax.swing.JFrame)window class (javax.swing.JFrame)

The constructor adds componentsThe constructor adds componentspublic class MyWinClass extends JFrame {public class MyWinClass extends JFrame {

public MyWinClass(String title) {public MyWinClass(String title) {super(title);super(title);Container pane = this.getContentPane();Container pane = this.getContentPane();pane.setLayout(…);pane.setLayout(…);pane.add(…);pane.add(…);……

Page 26: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

super Constructorsuper Constructor

It’s the parent’s constructorIt’s the parent’s constructor MyWinClass extends JFrameMyWinClass extends JFrame super(title) super(title) JFrame(String) JFrame(String)

» as in as in JFrame win = new JFrame(“My Win”);JFrame win = new JFrame(“My Win”); sets title of JFrame windowsets title of JFrame window

Must be first thing in constructor bodyMust be first thing in constructor body can use any constructor Parent hascan use any constructor Parent has

» but not grandparent!but not grandparent! if left out, Java uses if left out, Java uses super()super()

Page 27: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

GUI Window ClassGUI Window Class

The object created will be a window object The object created will be a window object (in the class JFrame)(in the class JFrame) it will have a content pane: it will have a content pane: getContentPane()getContentPane() or or this.getContentPane()this.getContentPane()

» NOT win.getContentPane() — there is no NOT win.getContentPane() — there is no winwin here here

Don’t make it visible in the constructorDon’t make it visible in the constructor client might not always want it visible right client might not always want it visible right

awayaway

Page 28: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Adder Dialog Mock-UpAdder Dialog Mock-Up

Adding Numbers

Enter two numbers to add together:

First number:

Second number:

Result:

10

25

35

CalculateCalculate DoneDone

Page 29: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Adder Dialog Grid Mock-UpAdder Dialog Grid Mock-Up

Adding Numbers

Enter two numbers to add…

First number:

Second number:

Result:

10

25

35

CalculateCalculate DoneDone

note this empty cell…

Page 30: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Adder Dialog (version 1)Adder Dialog (version 1)

public class AdderDialog1 extends JFrame {public class AdderDialog1 extends JFrame {public AdderDialog1() {public AdderDialog1() {

super(“Adding Numbers”);super(“Adding Numbers”);setSize(450, 250);setSize(450, 250);Container pane = getContentPane();Container pane = getContentPane();pane.setLayout( new GridLayout(5, 2, 10, 5) );pane.setLayout( new GridLayout(5, 2, 10, 5) );

… … // add labels/fields/buttons to content pane// add labels/fields/buttons to content pane}}

}}5 rows, 2 columns10 pixels between columns5 pixels between rows

Page 31: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Adder Dialog (version 1) mainAdder Dialog (version 1) main

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

AdderDialog1 ad1 = new AdderDialog1();AdderDialog1 ad1 = new AdderDialog1();ad1.setVisible(true);ad1.setVisible(true);

}}}}

Create the windowMake it visible

Page 32: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Now Do Something!Now Do Something!

Our windows do nothingOur windows do nothing (other than resize)(other than resize)

Want actions to go with the buttonsWant actions to go with the buttons read values from text boxes, mayberead values from text boxes, maybe add results & put back into another boxadd results & put back into another box

Need event controllersNeed event controllers methods that are called when something methods that are called when something

happens (happens (e.g. e.g. button pushed)button pushed)

Page 33: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Getting the Program to EndGetting the Program to End

First we want the program to end when the First we want the program to end when the adder dialog box is closedadder dialog box is closed JFrames have an easy way to do thatJFrames have an easy way to do thatsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add that line to the constructor, and then closing add that line to the constructor, and then closing

the adder window ends the applicationthe adder window ends the application For other events, we need an For other events, we need an ActionListenerActionListener

Page 34: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

The ActionListener InterfaceThe ActionListener Interface

One method needs to be implemented:One method needs to be implemented:public void actionPerformed(ActionEvent e) {…}public void actionPerformed(ActionEvent e) {…} this called this called whenever anything happens whenever anything happens in a in a

componentcomponent of the window of the window» notnot when the minimize/resize/close buttons clicked when the minimize/resize/close buttons clicked

methods needs to see what event happened…methods needs to see what event happened…» button clicked, text changed, …button clicked, text changed, …

……and deal with itand deal with it

You don’t call this method!It gets called when it’s needed: “event control”

Page 35: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Implementing ActionListenerImplementing ActionListener

You You couldcould make a separate class… make a separate class… and create an object of that classand create an object of that class

……but we will use the window class insteadbut we will use the window class instead we already have an object of that class: we already have an object of that class: thisthispublic class MyWindowClass extends JFrame public class MyWindowClass extends JFrame

implements ActionListener { … }implements ActionListener { … } need to import more classesneed to import more classesimport java.awt.event.*;import java.awt.event.*;

Page 36: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

The actionPerformed MethodThe actionPerformed Method

Has one parameterHas one parameter an ActionEvent – an object representing the an ActionEvent – an object representing the

event that just occurredevent that just occurred knows which component the event happened toknows which component the event happened to e.getActionCommand() e.getActionCommand() returns a string that returns a string that

represents the commandrepresents the command» for our buttons, the name of the buttonfor our buttons, the name of the buttone.getActionCommand().equals(“Done”)e.getActionCommand().equals(“Done”)e.getActionCommand().equals(“Calculate”)e.getActionCommand().equals(“Calculate”)

Page 37: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Our actionPerformed MethodOur actionPerformed Method

If it’s the Done button, exit the programIf it’s the Done button, exit the programSystem.exit(0);System.exit(0);

If it’s the Calculate button, get and add the If it’s the Calculate button, get and add the numbersnumbers we’ll have a separate method to do thatwe’ll have a separate method to do thatif (e.getActionCommand().equals(“Done”))if (e.getActionCommand().equals(“Done”))

System.exit(0);System.exit(0);else if (e.getActionCommand().equals(“Calculate”))else if (e.getActionCommand().equals(“Calculate”))

addTheNumbers();addTheNumbers();

Page 38: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

One More Thing…One More Thing…

We need to tell the buttons that this object is We need to tell the buttons that this object is waiting to be told when they’re clickedwaiting to be told when they’re clickedJButton doneButton = new JButton(“Done”);JButton doneButton = new JButton(“Done”);doneButton.addActionListener(this);doneButton.addActionListener(this);pane.add(doneButton);pane.add(doneButton); addActionListener method “registers” an object as addActionListener method “registers” an object as

waiting to be told about a clickwaiting to be told about a click» more than one object may be waiting to hearmore than one object may be waiting to hear

this (window) object is the ActionListener, so this (window) object is the ActionListener, so thisthis is the object we need to registeris the object we need to register

Page 39: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Our Adder Dialog So FarOur Adder Dialog So Far

Clicking the close box or Done button Clicking the close box or Done button closes the window and ends the applicationcloses the window and ends the application

Clicking on the Calculate buttonClicking on the Calculate button calls our addTheNumbers methodcalls our addTheNumbers method currently a stub!currently a stub!

Need to say how to add the numbersNeed to say how to add the numbers need to get the two numbers from the text fieldsneed to get the two numbers from the text fields add them up & put result in result fieldadd them up & put result in result field

Page 40: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Getting & Setting Text FieldsGetting & Setting Text Fields

Getter & setter for JTextFieldsGetter & setter for JTextFields gets/sets the text in the text fieldgets/sets the text in the text fieldfield1.setText(“Hello?”);field1.setText(“Hello?”);String f1Text = field1.getText();String f1Text = field1.getText(); use getText to get the numbers the user typed inuse getText to get the numbers the user typed in use setText to show the resultuse setText to show the result

Now we just need the text fields…Now we just need the text fields… ummm, where did we put the text fields?ummm, where did we put the text fields? in local variables… they’re gone now…in local variables… they’re gone now…

Page 41: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Keeping Track of Your FieldsKeeping Track of Your Fields

Object needs to keep a record of its fieldsObject needs to keep a record of its fields so it can talk about them laterso it can talk about them later instance variablesinstance variablesprivate JTextField numField1;private JTextField numField1; set in the constructorset in the constructornumField1 = new JTextField();numField1 = new JTextField();pane.add(numField1);pane.add(numField1); now it won’t forget them when constructor endsnow it won’t forget them when constructor ends and now addTheNumbers can get at themand now addTheNumbers can get at them

Page 42: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

addTheNumbersaddTheNumbers

Get the text and parse it as an integerGet the text and parse it as an integerint n1 = Integer.parseInt(numField1.getText());int n1 = Integer.parseInt(numField1.getText()); getText gets the text from the boxgetText gets the text from the box parseInt tries to change it to an integerparseInt tries to change it to an integer

» may throw a NumberFormatExceptionmay throw a NumberFormatException

Add them upAdd them upint result = n1 + n2;int result = n1 + n2;

Drop it back into resultField as textDrop it back into resultField as textresultField.setText(Integer.toString(result));resultField.setText(Integer.toString(result));

Page 43: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

addTheNumbersaddTheNumbers

Catch the exceptionCatch the exception set the result field to an error messageset the result field to an error messagepublic void addTheNumbers() {public void addTheNumbers() { try {try { int n1 = Integer.parseInt(numField1.getText());int n1 = Integer.parseInt(numField1.getText()); int n2 = Integer.parseInt(numField2.getText());int n2 = Integer.parseInt(numField2.getText()); int result = n1 + n2;int result = n1 + n2; resultField.setText(Integer.toString(result));resultField.setText(Integer.toString(result)); }} catch (NumberFormatException e) {catch (NumberFormatException e) { resultField.setText(“One of those is not a number!”);resultField.setText(“One of those is not a number!”); }}}}

Page 44: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Number Field ChangesNumber Field Changes

Number fields should align to the rightNumber fields should align to the rightnumField1.setHorizontalAlignment(JTextField.RIGHT);numField1.setHorizontalAlignment(JTextField.RIGHT);

Result field shouldn’t be editableResult field shouldn’t be editableresultField.setEditable(false);resultField.setEditable(false);

Make some space around the box edgesMake some space around the box edges Insets object gives number of pixels to be blankInsets object gives number of pixels to be blank

» top, left, bottom, righttop, left, bottom, rightInsets margin = new Insets(5, 5, 5, 5);Insets margin = new Insets(5, 5, 5, 5);numField1.setMargin(margin);numField1.setMargin(margin);

Page 45: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Adding Sub-PanesAdding Sub-Panes

You can create a JPanel and put objects You can create a JPanel and put objects inside it…inside it… using its own layout managerusing its own layout managerJPanel top = new JPanel();JPanel top = new JPanel();top.setLayout(new FlowLayout());top.setLayout(new FlowLayout());top.add(new JLabel(“Enter two numbers to add…”));top.add(new JLabel(“Enter two numbers to add…”));

……then put the JPanel into the windowthen put the JPanel into the window using the using the windowwindow’s layout manager’s layout managerpane.add(top, BorderLayout.NORTH);pane.add(top, BorderLayout.NORTH);

Page 46: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Exercise: Adding Sub-PanesExercise: Adding Sub-Panes

BorderLayout for full windowBorderLayout for full window NORTH, CENTER, SOUTHNORTH, CENTER, SOUTH

FlowLayout for top paneFlowLayout for top pane already done!already done!

GridLayout for middleGridLayout for middle 3 rows, 2 columns3 rows, 2 columns

FlowLayout for bottomFlowLayout for bottom

Enter two numbers to add…

Calculate Done

First number:

Second number:

Result:

Page 47: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

NetBeans GUI DesignerNetBeans GUI Designer

NetBeans provides a design toolNetBeans provides a design tool Add a new “JFrame Form…” to projectAdd a new “JFrame Form…” to project

opens in “Design” view (instead of “Source”)opens in “Design” view (instead of “Source”)

shows a “Palette” with shows a “Palette” with containers & controlscontainers & controls

» and more, but collapsedand more, but collapsed

Sometimes NetBeans will switch to “Source” view.Just click on the “Design” button to get back.

Page 48: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Adding Items to the WindowAdding Items to the Window

Drag and dropDrag and drop watch guidelines watch guidelines

for placementfor placement wide spacewide space medium spacemedium space align above and besidealign above and beside

Page 49: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Setting LabelsSetting Labels

Slow double-click label to set its textSlow double-click label to set its text other items mayother items may

move relative to move relative to new label contentsnew label contents

fix them by fix them by dragging to line up dragging to line up with other text with other text boxesboxes

Page 50: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Sizing Text BoxesSizing Text Boxes

Slow double click text fields to Slow double click text fields to change text inside the boxchange text inside the box box may resizebox may resize

Select box and drag corner/edge to resize itSelect box and drag corner/edge to resize it Similarly for buttonsSimilarly for buttons

I put it below “Calculate” so I I put it below “Calculate” so I could make them the same widthcould make them the same width

then I moved it to its final locationthen I moved it to its final location

Page 51: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Resizing WindowResizing Window

Drag from bottom-right corner until you get Drag from bottom-right corner until you get the size you wantthe size you want or double-click border and or double-click border and

type in the dimensions you type in the dimensions you wantwant

Page 52: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Changing PropertiesChanging Properties

Select the items to Select the items to changechange (e.g. all the text (e.g. all the text

boxes)boxes) Right-click to get Right-click to get

propertiesproperties change as desiredchange as desired

Page 53: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Changing NameChanging Name

NetBeans gives blah names:NetBeans gives blah names: jTextField1, jTextField2, jButton1, jButton2jTextField1, jTextField2, jButton1, jButton2

Should change to better namesShould change to better names variable name property in “Code” propertiesvariable name property in “Code” properties

Page 54: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Adding ActionsAdding Actions

Double-click button to add an actionDouble-click button to add an action switches to “Source” mode…switches to “Source” mode… ...in the method that handles click of that button...in the method that handles click of that button

Add code to do what you wantAdd code to do what you want

Page 55: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

DifferencesDifferences

Code generated by NetBeans will look very Code generated by NetBeans will look very different from what I told you beforedifferent from what I told you before code to lay out the fields is code to lay out the fields is veryvery different different code to add a listener to button is “anonymous”code to add a listener to button is “anonymous”

» creates unnamed object that just listens to the buttoncreates unnamed object that just listens to the button» no need for window to listenno need for window to listen» no need to check which button was pushed!no need to check which button was pushed!

Page 56: Graphical User Interfaces (GUIs) Chapter 13 (available on the Web) on the Webon the Web.

Questions?Questions?


Recommended