Title: Object Oriented Programming with JAVA
1- Object Oriented ProgrammingwithJAVA
- Graphical User Interface
- GUI
- Lecture 7
2Using Objects with Graphics
- import java.awt.
- import java.util..
- import javax.swing.
- class MyLine
- private int x1 // x coordinate of first endpoint
- private int y1 // y coordinate of first endpoint
- private int x2 // x coordinate of second
endpoint - private int y2 // y coordinate of second
endpoint - private Color myColor // color of this shape
- // constructor with input values
- public MyLine( int x1, int y1, int x2, int y2,
Color color ) - this.x1 x1 // set x coordinate of first
endpoint - this.y1 y1 // set y coordinate of first
endpoint - this.x2 x2 // set x coordinate of second
endpoint - this.y2 y2 // set y coordinate of second
endpoint - myColor color // set the color
- // end MyLine constructor
// Draw the line in the specified color public
void draw( Graphics g ) g.setColor( myColor
) g.drawLine( x1, y1, x2, y2 ) // end
method draw // end class MyLine
3Using Objects with Graphics ,cont
- class DrawPanel extends JPanel
- private Random randomNumbers new Random()
- private MyLine lines // array of lines
- // constructor, creates a panel with random
shapes - public DrawPanel()
- setBackground( Color.WHITE )
- lines new MyLine 5 randomNumbers.nextInt( 5
) - // create lines
- for ( int count 0 count lt lines.length
count ) - // generate random coordinates
- int x1 randomNumbers.nextInt( 300 )
- int y1 randomNumbers.nextInt( 300 )
- int x2 randomNumbers.nextInt( 300 )
- int y2 randomNumbers.nextInt( 300 )
- // generate a random color
- Color color new Color( randomNumbers.nextInt(
256 ), - randomNumbers.nextInt( 256 ), randomNumbers.nextIn
t( 256 ) ) - // add the line to the list of lines to be
displayed - lines count new MyLine( x1, y1, x2, y2,
color )
4Using Objects with Graphics ,cont
- // for each shape array, draw the individual
shapes - public void paintComponent( Graphics g )
- super.paintComponent( g )
- // draw the lines
- for ( MyLine line lines )
- line.draw( g )
- // end method paintComponent
- // end class DrawPanel
- public class TestDraw
- public static void main( String args )
- DrawPanel panel new DrawPanel()
- JFrame application new JFrame()
- application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE ) - application.add( panel )
- application.setSize( 300, 300 )
- application.setVisible( true )
- // end main
- // end class TestDraw
5Displaying Text and Images in a Window
- import java.awt.FlowLayout // specifies how
components are arranged - import javax.swing.JFrame // provides basic
window features - import javax.swing.JLabel // displays text and
images - import javax.swing.SwingConstants // common
constants used with Swing - import javax.swing.Icon // interface used to
manipulate images - import javax.swing.ImageIcon // loads images
- //Youcan just use gt import java.swing.
- public class LabelTest
-
- public static void main( String args )
-
- LabelFrame labelFrame new LabelFrame() //
create LabelFrame - labelFrame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE ) - labelFrame.setSize( 275, 180 ) // set frame size
- labelFrame.setVisible( true ) // display frame
- // end main
- // end class LabelTest
6Example cont
- class LabelFrame extends JFrame
- private JLabel label1 // JLabel with just text
- private JLabel label2 // JLabel constructed with
text and icon - private JLabel label3 // JLabel with added text
and icon - // LabelFrame constructor adds JLabels to JFrame
- public LabelFrame()
- super( "Testing JLabel" ) // to set title
- setLayout( new FlowLayout() ) // set frame
layout - //setLayout( new FlowLayout(FlowLayout.LEFT) )
// left right . center - // JLabel constructor with a string argument
- label1 new JLabel( "Label with text" )
- label1.setToolTipText( "This is label1" )
- // The tool tip text is displayed inside a
colored rectangle. When the user //moves the
mouse away, the tool tip is removed. - add( label1 ) // add label1 to JFrame
- // JLabel constructor with string, Icon and
alignment arguments
7Example cont
- label2 new JLabel( "Label with text and icon",
bug, SwingConstants.LEFT ) - label2.setToolTipText( "This is label2" )
- add( label2 ) // add label2 to JFrame
- label3 new JLabel() // JLabel constructor no
arguments - label3.setText( "Label with icon and text at
bottom" ) - label3.setIcon( bug ) // add icon to JLabel
- label3.setHorizontalTextPosition(
SwingConstants.CENTER ) - label3.setVerticalTextPosition(
SwingConstants.BOTTOM ) - label3.setToolTipText( "This is label3" )
- add( label3 ) // add label3 to JFrame
- // end LabelFrame constructor
- // end class LabelFrame
8(No Transcript)
9JApplet
- An applet is a Java program that is meant to be
embedded on a web page. When the applet is
activated, the applet code is downloaded to the
client's machine and executed - Import javax.swing.JApplet. .
10Introduction to buttons, events, and
ActionListener
- Input from user can be done by mouse, keyboard,
others. - Two ways,
- Blocking mode.
- Event driven mode.
- Scanner scannew Scanner(System.in)
- scan.nextInt()
- Not feasible for GUI.
11Common java.awt.Component methods
- boolean isVisible() checks if this component is
set to be visible. Components are initially
visible, with the exception of top-level
components such as JFrame. - void setVisible(boolean b) shows or hides the
component depending on whether b is true or
false. - boolean isEnabled() checks if this component is
enabled. An enabled component can receive
keyboard input. Components are initially enabled.
12Common java.awt.Component methods
- void setEnabled(boolean b) enables or disables
a component. - Point getLocation() returns the location of the
top-left corner of this component, relative to
the top-left corner of the surrounding container.
(A Point object p encapsulates an x- and a
ycoordinate which are accessible by p.x and p.y.) - Point getLocationOnScreen() returns the
location of the top-left corner of this
component, using the screen's coordinates. - void setBounds(int x, int y, int width, int
height) moves and resizes this component. The
location of the top-left corner is given by x and
y, and the new size is given by the width and
height parameters.
13Common java.awt.Component methods
- Dimension getSize() gets the current size of
this component. - void setSize(int width, int height) and
- void setSize(Dimension d) resizes the component
to the specified width and height.
14Ex Handling buttons
- import javax.swing.
- import java.awt.
- import java.awt.event. // must be
- public class ButtonTest
- public static void main(String args)
- MyFrame xnew MyFrame()
-
-
- enum EventTypeCLOSE, HELLO
- class MyFrame extends JFrame
- public MyFrame()
- initializeComponents()
- setSize(WIDTH, HEIGHT)
- setVisible(true)
15Ex Handling buttons , cont
- void initializeComponents()
-
- setLayout(new FlowLayout())
- //hello button
- btnHellonew JButton("Hello")
- btnHello.addActionListener(new myListener(EventTyp
e.HELLO)) - add(btnHello)
- //close button
- btnClosenew JButton("Close")
- btnClose.addActionListener(new myListener(EventTyp
e.CLOSE)) - add(btnClose)
-
- JButton btnClose
- JButton btnHello
- final int WIDTH300
- final int HEIGHT300
16Ex Handling buttons , cont..
- class myListener implements ActionListener
- EventType action
- public myListener(EventType action)
-
- this.actionaction
-
- public void actionPerformed(ActionEvent event)
// function in interface -
- switch(action)
-
- case HELLO
- JOptionPane.showMessageDialog(null,"Hello events
world") - break
- case CLOSE
- System.exit(0)
-
17JFrame
- Some common used methods inside the JFrame are
- The setTitle method for changing the text in
the title bar - The setResizable method, which takes a boolean
to determine if a frame will be resizeable by the
user. - The setLocation(x, y) sets the top-left corner
of the frame relative to the desktop origin. - The setBounds(x, y, width, height) lets you
resize and relocate a component in one step
18JFrame structure.
- The structure of a JFrame is very complex.
- Four panes are layered in a JFrame
- The root pane
- layered pane
- glass pane are of no interest to us
- They are required to organize the menu bar
and content pane and to implement the look and
feel. - The part that most concerns Swing programmers
is the content pane. When designing a frame, you
add components into the content pane.
19JFrame structure.
20Text Fields
- a single-line area in which the user can enter
text via the keyboard. - JTextField
- JPasswordField
- Methods commonly used
- setText(String)
- String getText()
- setToolTipText(String)
- private JTextField textField1 // text field with
set size - textField1 new JTextField( 10 )
- textField1.setText("initial")
- String s textField1.getText()
- JOptionPane.showMessageDialog( null, s)
- textField1.setToolTipText(" text field")
21Text field Example
- import java.awt.
- import java.awt.event.
- import javax.swing.
- class TextFieldFrame extends JFrame
- private JTextField textField1 // text field with
set size - private JTextField textField2 // text field
constructed with text - private JTextField textField3 // text field with
text and size - private JPasswordField passwordField // password
field with text - // TextFieldFrame constructor adds JTextFields to
JFrame - public TextFieldFrame()
- super("Testing JTextField and JPasswordField" )
- setLayout( new FlowLayout() ) // set frame
layout - // construct textfield with 10 columns
- textField1 new JTextField( 10 )
- add( textField1 ) // add textField1 to JFrame
- // construct textfield with default text
- textField2 new JTextField( "Enter text here" )
22Text field Example , cont..
- add( textField2 ) // add textField2 to JFrame
- // construct textfield with default text and 21
columns - textField3 new JTextField( "Uneditable text
field", 21 ) - textField3.setEditable( false ) // disable
editing - add( textField3 ) // add textField3 to JFrame
- // construct passwordfield with default text
- passwordField new JPasswordField( "Hidden text"
) - add( passwordField ) // add passwordField to
JFrame - // register event handlers
- TextFieldHandler handler new TextFieldHandler()
- textField1.addActionListener( handler )
- textField2.addActionListener( handler )
- textField3.addActionListener( handler )
- passwordField.addActionListener( handler )
- // end TextFieldFrame constructor
23- // private inner class for event handling
- private class TextFieldHandler implements
ActionListener - // process text field events
- public void actionPerformed( ActionEvent event )
- String string "" // declare string to display
- // user pressed Enter in JTextField textField1
- if ( event.getSource() textField1 )
- string String.format( "textField1 s",
- event.getActionCommand() )
- // user pressed Enter in JTextField textField2
- else if ( event.getSource() textField2 )
- string String.format( "textField2 s",
- event.getActionCommand() )
- // user pressed Enter in JTextField textField3
- else if ( event.getSource() textField3 )
- string String.format( "textField3 s",
- event.getActionCommand() )
- // user pressed Enter in JTextField passwordField
- else if ( event.getSource() passwordField )
24Text field Example , cont..
- public class TextFieldTest
-
- public static void main( String args )
-
- TextFieldFrame textFieldFrame new
TextFieldFrame() - textFieldFrame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE ) - textFieldFrame.setSize( 325, 150 ) // set frame
size - textFieldFrame.setVisible( true ) // display
frame - // end main
- // end class TextFieldTest
25Strings
- length() returns the length of the string
- charAt(i) returns the character at index I
- , also concat(str) for concatenation
- format(), like printf, it returns a formated
string - String fs
- fs String.format("The value of the float
variable is " "f, while the value of the
integer " "variable is d, and the string "
"is s", floatVar, intVar, stringVar) - System.out.println(fs)
26Strings cont.
- To convert strings to numbers, use the number
subclass parseyyyy(str) method. - float a Float.parseFloat(23.56)
- int b Integer.parseInt(203)
- To convert number to string you use the number
subclass method toString() - int i
- double d
- String s3 Integer.toString(i)
- String s4 Double.toString(d)
- you can also use concatenation int i4
String si
27String Useful methods
28String Useful methods, cont
29String Useful methods, cont
30Strings Example
- public class Filename
- private String fullPath
- private char pathSeparator, extensionSeparator
- public Filename(String str, char sep, char ext)
- fullPath str
- pathSeparator sep
- extensionSeparator ext
-
- public String extension()
- int dot fullPath.lastIndexOf(extensionSeparator)
- return fullPath.substring(dot 1)
-
- public String filename() // gets filename
without extension - int dot fullPath.lastIndexOf(extensionSeparator)
- int sep fullPath.lastIndexOf(pathSeparator)
- return fullPath.substring(sep 1, dot)
-
- public String path()
- int sep fullPath.lastIndexOf(pathSeparator)
31Strings Example
- public class FilenameDemo
- public static void main(String args)
- final String FPATH "/home/mem/index.html"
- Filename myHomePage new Filename(FPATH,'/',
'.') - System.out.println("Extension
"myHomePage.extension()) - System.out.println("Filename "
myHomePage.filename()) - System.out.println("Path " myHomePage.path())
-