Advanced Java BSc (ECS) Semester 6th

Advanced Java

Unit-I

Networking:

networking classes and interfaces

Java supports TCP/IP both by extending the already established stream I/O interface introduced in Chapter 20 and by adding the features required to build I/O objects across the network. Java supports both the TCP and UDP protocol families. TCP is used for reliable stream-based I/O across the network. UDP supports a simpler, hence faster, point-to-point datagram-oriented model. The classes contained in the java.net package are shown here:

Authenticator

CacheRequest

CacheResponse

ContentHandler

CookieHandler

CookieManager

DatagramPacket

DatagramSocket

DatagramSocketImpl

HttpCookie

HttpURLConnection

IDN

Inet4Address

Inet6Address

InetAddress

InetSocketAddress

InterfaceAddress

JarURLConnection

MulticastSocket

NetPermission

NetworkInterface

PasswordAuthentication

Proxy

ProxySelector

ResponseCache

SecureCacheResponse

ServerSocket

Socket

SocketAddress

SocketImpl

SocketPermission

StandardSocketOption

URI

URL

URLClassLoader

URLConnection

URLDecoder

URLEncoder

URLPermission (Added by JDK 8.)

URLStreamHandler

The java.net package’s interfaces are listed here:

ContentHandlerFactory

CookiePolicy

CookieStore

DatagramSocketImplFactory

FileNameMap

ProtocolFamily

SocketImplFactory

SocketOption

SocketOptions

URLStreamHandlerFactory

In the sections that follow, we will examine the main networking classes and show several examples that apply to them. Once you understand these core networking classes, you will be able to easily explore the others on your own.

using java.net package

Java programs are built specially to be run on a network. For the practice of these network applications, a set of classes is provided under this #.

A summary of various class #s is given below:

ClassDescription
AuthenticatorFor networking applications it is first important to fetch the authentication for a connection in a network. The object of the Authenticator class is responsible for obtaining the same. The class is declared as follows:
public class Authenticator extends Object
The class methods are inherited from the Object class.
CacheRequestWe all know about the cache memory, which is used for fast retrieval of information. The class CacheRequest does somewhat similar work by storing the responses in the CacheResponse class. The class is declared as follows:
public abstract class CacheRequest extends Object
The class methods are inherited from the Object class.
CacheResponseThe class aims at the retrieval of records from the CacheResponse. The class is declared as follows:
public abstract class CacheResponse extends Object
The class methods are inherited from the Object class.
ContentHandlerThe connection in a network is established with the help of URL. The class ContentHandler is the superclass of the classes which are appointed for reading the objects from the URL. The class is declared as follows:
public abstract class ContentHandler extends Object
The class methods are inherited from the Object class.
CookieHandlerThe class object is implied for the association of HTTP protocol handler with the HTTP state management policy implementation. The class is declared as follows:
public abstract class CookieHandler extends Object
The class methods are inherited from the Object class.
CookieManagerThe class extends the CookieHandler class i.e. The CookieManager implements the CookieHnadler. The class is declared as follows:
public abstract class CookieManager extends CookieHandler
The class methods are inherited from the CookieHandler and Object class.
DatagramPacketA datagram packet is rendered by the class. The class is declared as follows:
public final class DatagramPacket extends Object
The class methods are inherited from the Object class
DatagramSocketFor the transfer of datagram packets in a network an entity called as socket is required. The class provides the same. The class is declared as follows:
public final class DatagramSocket extends Object implements Closeable
The class methods are inherited from the Object class
DatagramSocketImplThe class serves as the parent for the implementation of sockets and datagram. The class is declared as:
public final class DatagramSocketImp extends Object implements SocketOptions
The class methods are inherited from the Object class
InterfaceAddressThe address of the network interface is represented by this class. The class is declared as follows:
public class InterfaceAddress extends Object 
The class methods are inherited from the Object class.
JarURLConnectionThe class is responsible for the establishment of the URL connection to the JAR files. The class is declared as follows:
public abstract class JarURLConnection extends URLConnection
The class methods are inherited from the URLConnection and Object class.
MulticastSocketFor the transfer of Multicast IP packets the class is implied. The class is declared as follows:
public abstract class MulticastSocket extends DatagramSocket.
The class methods are inherited from the DatagramSocket and Object class.
InetSocketAddressIP Socket Address is a combination of the IP address and the port number. The class provides the implementation of the same. It is declared as follows:
public class InetSocketAddress extends Object implements SocketAdress
The class methods are inherited from the Object class
InetAddressIP(Internet Protocol) address is represented by the class. The class is declared as:
public final class InetAddress extends Object implements Serializable 
The class methods are inherited from the Object class.
Inet4AddressThe internet address is represented as the Internet Protocol version 6 i.e Inet6 address. The class is declared as:
public final class Inet6Address extends InetAddress 
The class methods are inherited from the Object and InetAddress class.
Inet6AddressThe internet address is represented as the Internet Protocol version 4 i.e Inet4 address. The class is declared as:
public final class Inet4Address extends InetAddress 
The class methods are inherited from the Object and InetAddress class.
IDNThe class is implied for the conversion of IDN between the ACE and Unicode representation. The class is declared as:
public final class IDN extends Object 
The class methods are inherited from the Object class.
HttpURLConnectionThe class is implied for obtaining the URL connections and also has support for HTTP features. The class is declared as:
public final class HttpURLConnection extends URLConnection 
The class methods are inherited from the Object and URLConnection class.
HttpCookieWe all have heard about cookies in the web browsers which are appointed for carrying of information related to states between the client and the server. The class represents such HTTP cookies. The class is declared as:
public final class HttpCookie extends Object implements Cloneable
The class methods are inherited from the Object class.
NetPermissionFor providing various network related permissions the class is used. The class is declared as:
public final class NetPermission extends BasePermission
The class methods are inherited from the BasePermission class.
NetworkInterfaceA network interface is representation is provided by the class. The class is declared as:
public final class NetworkInterface extends Object
The class methods are inherited from the Object class.
PasswordAuthenticationThe class is used by the Authenticator as a data holder. The class is declared as:
public final class PasswordAuthentication extends Object
The class methods are inherited from the Object class.
ProxyThe class is used for proxy related settings. The class is declared as:
public final class Proxy extends Object
The class methods are inherited from the Object class.
ProxySelectorThe class is used for the selection for the proxy server to be used. The class is declared as:
public final class ProxySelector extends Object
The class methods are inherited from the Object class.
ResponseCacheCaches which are linked to the URL connections are represented by this class. The class is declared as:
public abstract class ResponseCache extends Object
The class methods are inherited from the Object class.
SecureCacheResponseA cache which is obtained through the use of secure means is represented by this class. The class is declared as:
public abstract class SecureCacheResponse extends CacheResponse
The class methods are inherited from the Object class.
ServerSocketThe class is implied for the implementation of server sockets. The class is declared as:
public abstract class ServerSocket extends Object implements Cloaseable.
The class methods are inherited from the Object class.
SocketThe sockets which are linked to the client side is implemented by the class. The class is declared as:
public abstract class Socket extends Object implements Cloaseable.
The class methods are inherited from the Object class.
SocketAddressThe class is implied for the representation of Socket Address. The class is declared as:
public abstract class SocketAddress extends Object implements Serializable
The class methods are inherited from the Object class.
SocketImplThe class is a parent class of all the socket implementing classes. The class is declared as:
public abstract class SocketImpl extends Object implements SocketOptions
The class methods are inherited from the Object class.
SocketPermissionThe class is implied for the provision of network access with the help of sockets. The class is declared as:
public final class SocketPermission extends Permission implements Serializable
The class methods are inherited from the Object and Permission class.
StandardSocketOptionsAs implied by the class name, the class is used to provide the standard socket options. The class is declared as:
public abstract class StandardSocketOptions extends Object 
The class methods are inherited from the Object class.
URIThe class is a representation of Uniform Resource Identifier. The class is declared as:
public final class URI extends Object implements Serializable, Comparable
The class methods are inherited from the Object class.
URLThe class is a representation of Uniform Resource Locator. The class is declared as:
public final class URL extends Object implements Serializable
The class methods are inherited from the Object class.
URLClassLoaderThe class is used for loading of loading of various classes and resources specified with the search path. The class is declared as:
public final class URL extends SecureClassLoader implements Closeable
The class methods are inherited from the SecureClassLoader class.
URLConnectionThe class is a parent class of the ones representing a communication between the application and an URL. The class is declared as:
public final class URLConnection extends Object 
The class methods are inherited from the Object class.
URLDecoderHTML forms are decoded by this class. The class is declared as:
public final class URLDecoder extends Object 
The class methods are inherited from the Object class.
URLEncoderHTML forms are encoded by this class. The class is declared as:
public final class URLEncoder extends Object 
The class methods are inherited from the Object class.
URLStreamHandlerThe class is a parent class of all the Stream Protocol Handlers. The class is declared as:
public final class URLStreamHandler extends Object 
The class methods are inherited from the Object class.

Doing TCP/IP and Datagram Programming

TCP/IP-style networking provides a serialized, predictable, reliable stream of packet data. This is not without its cost, however. TCP includes algorithms for dealing with congestion control on crowded networks, as well as pessimistic expectations about packet loss. This leads to inefficient way to transport data.
Clients and servers that communicate via a reliable channel, such as a TCP socket, have a dedicated point-to-point channel between themselves. To communicate, they establish a connection, transmit the data, and then close the connection. All data sent over the channel is received in the same order in which it was sent. This is guaranteed by the channel.
In contrast, applications that communicate via datagrams send and receive completely independent packets of information. These clients and servers do not have and do not need a dedicated point-to-point channel. The delivery of datagrams to their destinations is not guaranteed. Nor is the order of their arrival.

Datagram

A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed.

  • Datagrams plays a vital role as an alternative.
  • Datagrams are bundles of information passed between machines. Once the datagram has been released to its intended target, there is no assurance that it will arrive or even that someone will be there to catch it.
  • Likewise, when the datagram is received, there is no assurance that it hasn’t been damaged in transit or that whoever sent it is still there to receive a response and it is crucial point to note.

Java implements datagrams on top of the UDP (User Datagram Protocol) protocol by using two classes:

  1. DatagramPacket object is the data container.
  2. DatagramSocket is the mechanism used to send or receive the DatagramPackets.

DatagramSocket Class

DatagramSocket defines four public constructors. They are shown here:

  • DatagramSocket( ) throws SocketException :It creates a DatagramSocket bound to any unused port on the local computer.
  • DatagramSocket(int port) throws SocketException : It creates a DatagramSocket bound to the port specified by port.
  • DatagramSocket(int port, InetAddress ipAddress) throws SocketException : It constructs a DatagramSocket bound to the specified port and InetAddress.
  • DatagramSocket(SocketAddress address) throws SocketException : It constructs a DatagramSocket bound to the specified SocketAddress.

SocketAddress is an abstract class that is implemented by the concrete class InetSocketAddress. InetSocketAddress encapsulates an IP address with a port number. All can throw a SocketException if an error occurs while creating the socket. DatagramSocket defines many methods. Two of the most important are send( ) and receive( ), which are shown here:

  • void send(DatagramPacket packet) throws IOException
  • void receive(DatagramPacket packet) throws IOException

The send( ) method sends packet to the port specified by packet. The receive method waits for a packet to be received from the port specified by packet and returns the result.
Other methods give you access to various attributes associated with a DatagramSocket. Here is a sampling:

FUNCTIONUSAGE
InetAddress getInetAddress( )If the socket is connected, then the address is returned. Otherwise, null is returned.
int getLocalPort( )Returns the number of the local port.
int getPort( )Returns the number of the port to which the socket is connected. It returns –1 if the socket is not connected to a port.
boolean isBound( )Returns true if the socket is bound to an address. Returns false otherwise.
boolean isConnected( )Returns true if the socket is connected to a server. Returns false otherwise.
void setSoTimeout(int millis) throws SocketExceptionSets the time-out period to the number of milliseconds passed in millis.

DatagramPacket Class

DatagramPacket defines several constructors. Four are shown here:

  • DatagramPacket(byte data[ ], int size) : It specifies a buffer that will receive data and the size of a packet. It is used for receiving data over a DatagramSocket
  • DatagramPacket(byte data[ ], int offset, int size) : It allows you to specify an offset into the buffer at which data will be stored.
  • DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port) : It specifies a target address and port, which are used by a DatagramSocket to determine where the data in the packet will be sent.
  • DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port) : It transmits packets beginning at the specified offset into the data.

Think of the first two forms as building an “in box, ” and the second two forms as stuffing and addressing an envelope.

DatagramPacket defines several methods, including those shown here, that give access to the address and port number of a packet, as well as the raw data and its length. In general, the get methods are used on packets that are received and the set methods are used on packets that will be sent.

FUNCTIONUSAGE
InetAddress getAddress( )Returns the address of the source (for datagrams being received) or destination (for datagrams being sent).
byte[ ] getData( )Returns the byte array of data contained in the datagram. Mostly used to retrieve data from the datagram after it has been received.
int getLength( )Returns the length of the valid data contained in the byte array that would be returned from the getData( ) method. This may not equal the length of the whole byte array.
int getOffset( )Returns the starting index of the data.
int getPort( )Returns the port number.
void setAddress(InetAddress ipAddress)Sets the address to which a packet will be sent. The address is specified by ipAddress.
void setData(byte[ ] data)Sets the data to data, the offset to zero, and the length to number of bytes in data
void setData(byte[ ] data, int idx, int size)Sets the data to data, the offset to idx, and the length to size.
void setLength(int size)Sets the length of the packet to size.
void setPort(int port)Sets the port to port.

Unit-II

Introduction to Swing Technology:

JApplet

JApplet is a Swing JPanel with a mission. It is a GUI container that has some extra structure to allow it to be used in the “alien” environment of a web browser. Applets also have a lifecycle that lets them act more like an application than a static component. Although applets tend to be relatively simple, there’s no inherent restriction on their complexity other than the issues of downloading and caching their content. Historically, applets have tended to be small “widgets.”

The javax.swing.JApplet class defines the core functionality of an applet. (java.awt.Applet is the older, AWT-based form.)

Structurally, an applet is a wrapper for your Java code. In contrast to a standalone graphical Java application, which starts up from a main() method and creates a GUI, an applet itself is a component that expects to be dropped into someone else’s GUI. Thus, an applet can’t run by itself; it runs in the context of a web browser or a special applet-viewer program (which we’ll talk about later). Instead of having your application create a JFrame to hold your GUI, you stuff your application inside a JApplet (which itself extends Container) and let the browser add your applet to the page.

Applets are placed on web pages with the <applet> HTML tag, which we’ll cover later in this chapter. At its simplest, you just specify the name of the applet class and a size in pixels for the applet:

    <applet code="AnalogClock" width="100" height="100"></applet>

Pragmatically, an applet is an intruder into someone else’s environment and therefore has to be treated with suspicion. The web browsers that run applets impose restrictions on what the applet is allowed to do. The restrictions are enforced by an applet security manager. The browser provides everything the applet needs through an applet context—the API the applet uses to interact with its environment.

JApplet expects to be embedded in a page and used in a viewing environment that provides it with resources. In all other respects, however, applets are just ordinary Panel objects. As Figure 23-1 shows, an applet is a kind of Panel. Like any other Panel, a JApplet can contain user interface components and use all the basic drawing and event-handling capabilities of the Component class. You can draw on a JApplet by overriding its paint()method and respond to events in the JApplet’s display area by providing the appropriate event listeners. Applets also have additional structure that helps them interact with the browser environment.

Aside from the top-level structure and the security restrictions, there is no difference between an applet and an application. If your application can live within the limits imposed by a browser’s security manager, you can structure it to function as both an applet and a standalone application. Normally, you’ll use your applet class itself only as a thin wrapper to manage the lifecycle and appearance of your application—create the GUI, start, and stop. So, the bulk of your code should be easily adaptable to either a standalone or applet deployment.

The java.applet package

Figure 23-1. The java.applet package

JFrame and JComponent


JFrame

The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class. JFrame works like the main window where components like labels, buttons, textfields are added to create a GUI.

Unlike Frame, JFrame has the option to hide or close the window with the help of setDefaultCloseOperation(int) method.

Nested Class

Modifier and TypeClassDescription
protected classJFrame.AccessibleJFrameThis class implements accessibility support for the JFrame class.

Fields

Modifier and TypeFieldDescription
protected AccessibleContextaccessibleContextThe accessible context property.
static intEXIT_ON_CLOSEThe exit application default window close operation.
protected JRootPanerootPaneThe JRootPane instance that manages the contentPane and optional menuBar for this frame, as well as the glassPane.
protected booleanrootPaneCheckingEnabledIf true then calls to add and setLayout will be forwarded to the contentPane.

Constructors

ConstructorDescription
JFrame()It constructs a new frame that is initially invisible.
JFrame(GraphicsConfiguration gc)It creates a Frame in the specified GraphicsConfiguration of a screen device and a blank title.
JFrame(String title)It creates a new, initially invisible Frame with the specified title.
JFrame(String title, GraphicsConfiguration gc)It creates a JFrame with the specified title and the specified GraphicsConfiguration of a screen device.

Useful Methods

Modifier and TypeMethodDescription
protected voidaddImpl(Component comp, Object constraints, int index)Adds the specified child Component.
protected JRootPanecreateRootPane()Called by the constructor methods to create the default rootPane.
protected voidframeInit()Called by the constructors to init the JFrame properly.
voidsetContentPane(Containe contentPane)It sets the contentPane property
static voidsetDefaultLookAndFeelDecorated(boolean defaultLookAndFeelDecorated)Provides a hint as to whether or not newly created JFrames should have their Window decorations (such as borders, widgets to close the window, title…) provided by the current look and feel.
voidsetIconImage(Image image)It sets the image to be displayed as the icon for this window.
voidsetJMenuBar(JMenuBar menubar)It sets the menubar for this frame.
voidsetLayeredPane(JLayeredPane layeredPane)It sets the layeredPane property.
JRootPanegetRootPane()It returns the rootPane object for this frame.
TransferHandlergetTransferHandler()It gets the transferHandler property.

JFrame Example

  1. import java.awt.FlowLayout;  
  2. import javax.swing.JButton;  
  3. import javax.swing.JFrame;  
  4. import javax.swing.JLabel;  
  5. import javax.swing.Jpanel;  
  6. public class JFrameExample {  
  7.     public static void main(String s[]) {  
  8.         JFrame frame = new JFrame(“JFrame Example”);  
  9.         JPanel panel = new JPanel();  
  10.         panel.setLayout(new FlowLayout());  
  11.         JLabel label = new JLabel(“JFrame By Example”);  
  12.         JButton button = new JButton();  
  13.         button.setText(“Button”);  
  14.         panel.add(label);  
  15.         panel.add(button);  
  16.         frame.add(panel);  
  17.         frame.setSize(200, 300);  
  18.         frame.setLocationRelativeTo(null);  
  19.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  20.         frame.setVisible(true);  
  21.     }  
  22. }  

Output

Java Jframe


JComponent

The JComponent class is the base class of all Swing components except top-level containers. Swing components whose names begin with “J” are descendants of the JComponent class. For example, JButton, JScrollPane, JPanel, JTable etc. But, JFrame and JDialog don’t inherit JComponent class because they are the child of top-level containers.

The JComponent class extends the Container class which itself extends Component. The Container class has support for adding components to the container.

Fields

Modifier and TypeFieldDescription
protected AccessibleContextaccessibleContextThe AccessibleContext associated with this JComponent.
protectedEventListenerListlistenerListA list of event listeners for this component.
static StringTOOL_TIP_TEXT_KEYThe comment to display when the cursor is over the component, also known as a “value tip”, “flyover help”, or “flyover label”
protected ComponentUIuiThe look and feel delegate for this component.
static intUNDEFINED_CONDITIONIt is a constant used by some of the APIs to mean that no condition is defined.
static intWHEN_ANCESTOR_OF_FOCUSED_COMPONENTIt is a constant used for registerKeyboardAction that means that the command should be invoked when the receiving component is an ancestor of the focused component or is itself the focused component.
static intWHEN_FOCUSEDIt is a constant used for registerKeyboardAction that means that the command should be invoked when the component has the focus.
static intWHEN_IN_FOCUSED_WINDOWConstant used for registerKeyboardAction that means that the command should be invoked when the receiving component is in the window that has the focus or is itself the focused component.

Constructor

ConstructorDescription
JComponent()Default JComponent constructor.

Useful Methods

Modifier and TypeMethodDescription
voidsetActionMap(ActionMap am)It sets the ActionMap to am.
voidsetBackground(Color bg)It sets the background color of this component.
voidsetFont(Font font)It sets the font for this component.
voidsetMaximumSize(Dimension maximumSize)It sets the maximum size of this component to a constant value.
voidsetMinimumSize(Dimension minimumSize)It sets the minimum size of this component to a constant value.
protected voidsetUI(ComponentUI newUI)It sets the look and feel delegate for this component.
voidsetVisible(boolean aFlag)It makes the component visible or invisible.
voidsetForeground(Color fg)It sets the foreground color of this component.
StringgetToolTipText(MouseEvent event)It returns the string to be used as the tooltip for event.
ContainergetTopLevelAncestor()It returns the top-level ancestor of this component (either the containing Window or Applet), or null if this component has not been added to any container.
TransferHandlergetTransferHandler()It gets the transferHandler property.

Java JComponent Example

  1. import java.awt.Color;  
  2. import java.awt.Graphics;  
  3. import javax.swing.JComponent;  
  4. import javax.swing.JFrame;  
  5. class MyJComponent extends JComponent {  
  6.       public void paint(Graphics g) {  
  7.         g.setColor(Color.green);  
  8.         g.fillRect(30, 30, 100, 100);  
  9.       }  
  10. }  
  11. public class JComponentExample {  
  12.       public static void main(String[] arguments) {  
  13.         MyJComponent com = new MyJComponent();  
  14.         // create a basic JFrame  
  15.         JFrame.setDefaultLookAndFeelDecorated(true);  
  16.         JFrame frame = new JFrame(“JComponent Example”);  
  17.         frame.setSize(300,200);  
  18.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  19.         // add the JComponent to main frame  
  20.         frame.add(com);  
  21.         frame.setVisible(true);  
  22.       }  
  23. }  

Output:

Java Jcomponent

Icons and Labels

Labels

Introduction

The class JLabel can display either text, an image, or both. Label’s contents are aligned by setting the vertical and horizontal alignment in its display area. By default, labels are vertically centered in their display area. Text-only labels are leading edge aligned, by default; image-only labels are horizontally centered, by default.

Class Declaration

Following is the declaration for javax.swing.JLabel class −

Field

Following are the fields for javax.swing.JLabel class −

protected Component labelFor

Class Constructors

Sr.No.Constructor & Description
1JLabel()Creates a JLabel instance with no image and with an empty string for the title.
2JLabel(Icon image)Creates a JLabel instance with the specified image.
3JLabel(Icon image, int horizontalAlignment)Creates a JLabel instance with the specified image and horizontal alignment.
4JLabel(String text)Creates a JLabel instance with the specified text.
5JLabel(String text, Icon icon, int horizontalAlignment)Creates a JLabel instance with the specified text, image, and horizontal alignment.
6JLabel(String text, int horizontalAlignment)Creates a JLabel instance with the specified text and horizontal alignment.

Class Methods

Sr.No.Method & Description
1protected int checkHorizontalKey(int key, String message)Verify that key is a legal value for the horizontalAlignment properties.
2protected int checkVerticalKey(int key, String message)Verify that key is a legal value for the verticalAlignment or verticalTextPosition properties.
3AccessibleContext getAccessibleContext()Get the AccessibleContext of this object.
4Icon getDisabledIcon()Returns the icon used by the label when it’s disabled.
5int getDisplayedMnemonic()Return the keycode that indicates a mnemonic key.
6int getDisplayedMnemonicIndex()Returns the character, as an index, that the look and feel should provide decoration for as representing the mnemonic character.
7int getHorizontalAlignment()Returns the alignment of the label’s contents along the X axis.
8int getHorizontalTextPosition()Returns the horizontal position of the label’s text, relative to its image.
9Icon getIcon()Returns the graphic image (glyph, icon) that the label displays.
10int getIconTextGap()Returns the amount of space between the text and the icon displayed in this label.
11Component getLabelFor()Get the component this is labelling.
12String getText()Returns the text string that the label displays.
13LabelUI getUI()Returns the L&F object that renders this component.
14String getUIClassID()Returns a string that specifies the name of the l&f class which renders this component.
15int getVerticalAlignment()Returns the alignment of the label’s contents along the Y axis.
16int getVerticalTextPosition()Returns the vertical position of the label’s text, relative to its image.
17boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h)This is overridden to return false if the current Icon’s image is not equal to the passed in Image img.
18protected String paramString()Returns a string representation of this JLabel.
19void setDisabledIcon(Icon disabledIcon)Sets the icon to be displayed if this JLabel is “disabled” (JLabel.setEnabled(false)).
20void setDisplayedMnemonic(char aChar)Specifies the displayedMnemonic as a char value.
21void setDisplayedMnemonic(int key)Specifies a keycode that indicates a mnemonic key.
22void setDisplayedMnemonicIndex(int index)Provides a hint to the look and feel as to which character in the text should be decorated to represent the mnemonic.
23void setHorizontalAlignment(int alignment)Sets the alignment of the label’s contents along the Xaxis.
24void setHorizontalTextPosition(int textPosition)Sets the horizontal position of the label’s text, relative to its image.
25void setIcon(Icon icon)Defines the icon this component will display.
26void setIconTextGap(int iconTextGap)If both the icon and text properties are set, this property defines the space between them.
27void setLabelFor(Component c)Sets the component, this is labelling.
28void setText(String text)Defines the single line of text this component will display.
29void setUI(LabelUI ui)Sets the L&F object that renders this component.
30void setVerticalAlignment(int alignment)Sets the alignment of the label’s contents along the Yaxis.
31void setVerticalTextPosition(int textPosition)Sets the vertical position of the label’s text, relative to its image.
32void updateUI()Resets the UI property to a value from the current look and feel.

Multithreading in Java

Multithreading in java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared memory area. They don’t allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.


Advantages of Java Multithreading

1) It doesn’t block the user because threads are independent and you can perform multiple operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn’t affect other threads if an exception occurs in a single thread.

Text fields

The AWT provides java.awt.TextField class through the component box input text or just text box. This component enables the editing and input a single line of text in a very convenient way for the user.Hence, this control is called editable control. Any data entered through this component is treated primarily as text, should be explicitly converted to another type if desired.

The TextField control is a sub-class of the TextComponent class. It can be created using the following constructors:

TextField text=new TextField( );
TextField text=new TextField(int numberofchar);
TextField text=new TextField(String str);
TextField text=new TextField(String str, int numberolchar);

The first constructor creates the default TextField. The second creates a TextField of size specified by the number of characters. The third type creates a text field with the default constructor. The text field control has the methods getText() and set Text(String str) for getting and setting the values in the text field. The text field can be made editable or non-editable by using the following methods:
setEditable(Boolean edit);
isEditable()
The isEditable() method returns the boolean value true if the text field is editable and the value false if the text field is non-editable. Another important characteristic of the text field is that the echo character can be set, while entering password-like values. To set echo characters the following method is called:
void setEchoCharacter(char ch)
The echo character can be obtained and it can be checked it the echo character has been set using the following methods:
getEchoCharacter();
boolean echoCharlsSet();
Since text field also generates the ActionEvent, the ActionListener interface can be used to handle any type of action performed in the text field. The selected text within the text field can be obtained by using the TextField Interface.

The java.awt.TextField class contains, among others, the following constructors and methods:
Following is a table that lists some of the methods of this class:

MethodDescription
TextField()Constructs new text box with no content.
TextField(String)Constructs new text box with content given.
TextField(String, int)Constructs new text box with content and given the specified width in columns.
addActionListener(ActionListener)Registers a listener class (processor events) ActionListener for the TextField.
echoCharIsSet()Verifies that character echo is triggered.
getColumns()Gets the current number of columns.
getEchoChar()Obtain current character echo.
SetColumns(int) setEchoChar(char)               specifies the number of columns. Specifies character echo.
import java.awt.*; 
import java.awt.event.*; 
public class TextFieldJavaExample extends Frame 

       TextField textfield; 
       TextFieldJavaExample() 
       { 
           setLayout(new FlowLayout()); 
           textfield = new TextField("Hello Java", 12); 
           add(textfield); 
           addWindowListener(new WindowAdapter(){ 
           public void windowClosing(WindowEvent we) 
           { 
              System.exit(0); 
           } 
           }); 
       } 
       public static void main(String argc[]) 
             { 
                    Frame frame = new TextFieldJavaExample(); 
                    frame.setTitle(" TextField in Java Example"); 
                    frame.setSize(320, 200); 
                    frame.setVisible(true); 
                    
             } 
}
TextField in Java Example

Buttons –

The JButton class

The JButton class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed. It inherits AbstractButton class.

JButton class declaration

Let’s see the declaration for javax.swing.JButton class.

  1. public class JButton extends AbstractButton implements Accessible  

Commonly used Constructors:

ConstructorDescription
JButton()It creates a button with no text and icon.
JButton(String s)It creates a button with the specified text.
JButton(Icon i)It creates a button with the specified icon object.

Commonly used Methods of AbstractButton class:

MethodsDescription
void setText(String s)It is used to set specified text on button
String getText()It is used to return the text of the button.
void setEnabled(boolean b)It is used to enable or disable the button.
void setIcon(Icon b)It is used to set the specified Icon on the button.
Icon getIcon()It is used to get the Icon of the button.
void setMnemonic(int a)It is used to set the mnemonic on the button.
void addActionListener(ActionListener a)It is used to add the action listener to this object.

Java JButton Example

  1. import javax.swing.*;    
  2. public class ButtonExample {  
  3. public static void main(String[] args) {  
  4.     JFrame f=new JFrame(“Button Example”);  
  5.     JButton b=new JButton(“Click Here”);  
  6.     b.setBounds(50,100,95,30);  
  7.     f.add(b);  
  8.     f.setSize(400,400);  
  9.     f.setLayout(null);  
  10.     f.setVisible(true);   
  11. }  
  12. }  

Output:

JAVA Jbutton 1

Check Boxes

The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false). Clicking on a CheckBox changes its state from “on” to “off” or from “off” to “on “.It inherits JToggleButton class.

JCheckBox class declaration

Let’s see the declaration for javax.swing.JCheckBox class.

  1. public class JCheckBox extends JToggleButton implements Accessible  

Commonly used Constructors:

ConstructorDescription
JJCheckBox()Creates an initially unselected check box button with no text, no icon.
JChechBox(String s)Creates an initially unselected check box with text.
JCheckBox(String text, boolean selected)Creates a check box with text and specifies whether or not it is initially selected.
JCheckBox(Action a)Creates a check box where properties are taken from the Action supplied.

Commonly used Methods:

MethodsDescription
AccessibleContext getAccessibleContext()It is used to get the AccessibleContext associated with this JCheckBox.
protected String paramString()It returns a string representation of this JCheckBox.

Java JCheckBox Example

  1. import javax.swing.*;  
  2. public class CheckBoxExample  
  3. {  
  4.      CheckBoxExample(){  
  5.         JFrame f= new JFrame(“CheckBox Example”);  
  6.         JCheckBox checkBox1 = new JCheckBox(“C++”);  
  7.         checkBox1.setBounds(100,100, 50,50);  
  8.         JCheckBox checkBox2 = new JCheckBox(“Java”, true);  
  9.         checkBox2.setBounds(100,150, 50,50);  
  10.         f.add(checkBox1);  
  11.         f.add(checkBox2);  
  12.         f.setSize(400,400);  
  13.         f.setLayout(null);  
  14.         f.setVisible(true);  
  15.      }  
  16. public static void main(String args[])  
  17.     {  
  18.     new CheckBoxExample();  
  19.     }}  

Output:

JAVA Jcheckbox 1

JRadioButton

The JRadioButton class is used to create a radio button. It is used to choose one option from multiple options. It is widely used in exam systems or quiz.

It should be added in ButtonGroup to select one radio button only.

JRadioButton class declaration

Let’s see the declaration for javax.swing.JRadioButton class.

  1. public class JRadioButton extends JToggleButton implements Accessible  

Commonly used Constructors:

ConstructorDescription
JRadioButton()Creates an unselected radio button with no text.
JRadioButton(String s)Creates an unselected radio button with specified text.
JRadioButton(String s, boolean selected)Creates a radio button with the specified text and selected status.

Commonly used Methods:

MethodsDescription
void setText(String s)It is used to set specified text on button.
String getText()It is used to return the text of the button.
void setEnabled(boolean b)It is used to enable or disable the button.
void setIcon(Icon b)It is used to set the specified Icon on the button.
Icon getIcon()It is used to get the Icon of the button.
void setMnemonic(int a)It is used to set the mnemonic on the button.
void addActionListener(ActionListener a)It is used to add the action listener to this object.

Java JRadioButton Example

  1. import javax.swing.*;    
  2. public class RadioButtonExample {    
  3. JFrame f;    
  4. RadioButtonExample(){    
  5. f=new JFrame();     
  6. JRadioButton r1=new JRadioButton(“A) Male”);    
  7. JRadioButton r2=new JRadioButton(“B) Female”);    
  8. r1.setBounds(75,50,100,30);    
  9. r2.setBounds(75,100,100,30);    
  10. ButtonGroup bg=new ButtonGroup();    
  11. bg.add(r1);bg.add(r2);    
  12. f.add(r1);f.add(r2);      
  13. f.setSize(300,300);    
  14. f.setLayout(null);    
  15. f.setVisible(true);    
  16. }    
  17. public static void main(String[] args) {    
  18.     new RadioButtonExample();    
  19. }    
  20. }    

Output:

JAVA Jradiobutton 1

Combo boxes

JComboBox is a part of Java Swing package. JComboBox inherits JComponent class . JComboBox shows a popup menu that shows a list and the user can select a option from that specified list . JComboBox can be editable or read- only depending on the choice of the programmer .

Constructor of the JComboBox are:

  1. JComboBox() : creates a new empty JComboBox .
  2. JComboBox(ComboBoxModel M) : creates a new JComboBox with items from specified ComboBoxModel
  3. JComboBox(E [ ] i) : creates a new JComboBox with items from specified array.
  4. JComboBox(Vector items) : creates a new JComboBox with items from the specified vector

Commonly used Methods are :

  1. addItem(E item) : adds the item to the JComboBox
  2. addItemListener( ItemListener l) : adds a ItemListener to JComboBox
  3. getItemAt(int i) : returns the item at index i
  4. getItemCount(): returns the number of items from the list
  5. getSelectedItem() : returns the item which is selected
  6. removeItemAt(int i) : removes the element at index i
  7. setEditable(boolean b) : the boolean b determines whether the combo box is editable or not .If true is passed then the combo box is editable or vice versa.
  8. setSelectedIndex(int i): selects the element of JComboBox at index i.
  9. showPopup() :causes the combo box to display its popup window.
  10. setUI(ComboBoxUI ui): sets the L&F object that renders this component.
  11. setSelectedItem(Object a): sets the selected item in the combo box display area to the object in the argument.
  12. setSelectedIndex(int a): selects the item at index anIndex.
  13. setPopupVisible(boolean v): sets the visibility of the popup.
  14. setModel(ComboBoxModel a) : sets the data model that the JComboBox uses to obtain the list of items.
  15. setMaximumRowCount(int count): sets the maximum number of rows the JComboBox displays.
  16. setEnabled(boolean b): enables the combo box so that items can be selected.
  17. removeItem(Object anObject) : removes an item from the item list.
  18. removeAllItems(): removes all items from the item list.
  19. removeActionListener(ActionListener l): removes an ActionListener.
  20. isPopupVisible() : determines the visibility of the popup.
  21. addPopupMenuListener(PopupMenuListener l) : adds a PopupMenu listener which will listen to notification messages from the popup portion of the combo box.
  22. getActionCommand() : returns the action command that is included in the event sent to action listeners.
  23. getEditor(): returns the editor used to paint and edit the selected item in the JComboBox field.
  24. getItemCount() : returns the number of items in the list.
  25. getItemListeners(): returns an array of all the ItemListeners added to this JComboBox with addItemListener().
  26. createDefaultKeySelectionManager() : returns an instance of the default key-selection manager.
  27. fireItemStateChanged(ItemEvent e) : notifies all listeners that have registered interest for notification on this event type.
  28. firePopupMenuCanceled() : notifies PopupMenuListeners that the popup portion of the combo box has been canceled.
  29. firePopupMenuWillBecomeInvisible() : notifies PopupMenuListeners that the popup portion of the combo box has become invisible.
  30. firePopupMenuWillBecomeVisible() : notifies PopupMenuListeners that the popup portion of the combo box will become visible.
  31. setEditor(ComboBoxEditor a): sets the editor used to paint and edit the selected item in the JComboBox field.
  32. setActionCommand(String a) : sets the action command that should be included in the event sent to actionListeners.
  33. getUI() : returns the look and feel object that renders this component.
  34. paramString() : returns a string representation of this JComboBox.
  35. getUIClassID() : returns the name of the Look and feel class that renders this component.
  36. getAccessibleContext() : gets the AccessibleContext associated with this JComboBox.

Java JTabbedPane

The JTabbedPane class is used to switch between a group of components by clicking on a tab with a given title or icon. It inherits JComponent class.

JTabbedPane class declaration

Let’s see the declaration for javax.swing.JTabbedPane class.

  1. public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingConstants  

Commonly used Constructors:

ConstructorDescription
JTabbedPane()Creates an empty TabbedPane with a default tab placement of JTabbedPane.Top.
JTabbedPane(int tabPlacement)Creates an empty TabbedPane with a specified tab placement.
JTabbedPane(int tabPlacement, int tabLayoutPolicy)Creates an empty TabbedPane with a specified tab placement and tab layout policy.

Java JTabbedPane Example

  1. import javax.swing.*;  
  2. public class TabbedPaneExample {  
  3. JFrame f;  
  4. TabbedPaneExample(){  
  5.     f=new JFrame();  
  6.     JTextArea ta=new JTextArea(200,200);  
  7.     JPanel p1=new JPanel();  
  8.     p1.add(ta);  
  9.     JPanel p2=new JPanel();  
  10.     JPanel p3=new JPanel();  
  11.     JTabbedPane tp=new JTabbedPane();  
  12.     tp.setBounds(50,50,200,200);  
  13.     tp.add(“main”,p1);  
  14.     tp.add(“visit”,p2);  
  15.     tp.add(“help”,p3);    
  16.     f.add(tp);  
  17.     f.setSize(400,400);  
  18.     f.setLayout(null);  
  19.     f.setVisible(true);  
  20. }  
  21. public static void main(String[] args) {  
  22.     new TabbedPaneExample();  
  23. }}  

Output:

JAVA Jtabbedpane 1

Scroll Panes

JScrollPane scrolls to view the contents of the component added to it. Scrollbars are used to scroll the contents horizontally and vertically. From JDK 1.4, new methods for mouse wheel movements are added like processMouseWheelEvent(MouseWheelEvent) etc. The mouse wheel can be used to enlarge a photo by rotating the wheel in the display area.

Tree

  • A Tree is a recursive data structure containing the set of one or more data nodes where one node is designated as the root of the tree while the remaining nodes are called as the children of the root.
  • The nodes other than the root node are partitioned into the non empty sets where each one of them is to be called sub-tree.
  • Nodes of a tree either maintain a parent-child relationship between them or they are sister nodes.
  • In a general tree, A node can have any number of children nodes but it can have only a single parent.
  • The following image shows a tree, where the node A is the root node of the tree while the other nodes can be seen as the children of A.
Tree

Basic terminology

  • Root Node :- The root node is the topmost node in the tree hierarchy. In other words, the root node is the one which doesn’t have any parent.
  • Sub Tree :- If the root node is not null, the tree T1, T2 and T3 is called sub-trees of the root node.
  • Leaf Node :- The node of tree, which doesn’t have any child node, is called leaf node. Leaf node is the bottom most node of the tree. There can be any number of leaf nodes present in a general tree. Leaf nodes can also be called external nodes.
  • Path :- The sequence of consecutive edges is called path. In the tree shown in the above image, path to the node E is A→ B → E.
  • Ancestor node :- An ancestor of a node is any predecessor node on a path from root to that node. The root node doesn’t have any ancestors. In the tree shown in the above image, the node F have the ancestors, B and A.
  • Degree :- Degree of a node is equal to number of children, a node have. In the tree shown in the above image, the degree of node B is 2. Degree of a leaf node is always 0 while in a complete binary tree, degree of each node is equal to 2.
  • Level Number :- Each node of the tree is assigned a level number in such a way that each node is present at one level higher than its parent. Root node of the tree is always present at level 0.

Static representation of tree

  1. #define MAXNODE 500  
  2. struct treenode {  
  3.     int root;  
  4.     int father;  
  5.     int son;  
  6.     int next;   
  7. }   

Dynamic representation of tree

  1. struct treenode   
  2. {  
  3.     int root;  
  4.     struct treenode *father;   
  5.     struct treenode *son   
  6.     struct treenode *next;   
  7. }  

Types of Tree

The tree data structure can be classified into six different categories.

Tree

General Tree

General Tree stores the elements in a hierarchical order in which the top level element is always present at level 0 as the root element. All the nodes except the root node are present at number of levels. The nodes which are present on the same level are called siblings while the nodes which are present on the different levels exhibit the parent-child relationship among them. A node may contain any number of sub-trees. The tree in which each node contain 3 sub-tree, is called ternary tree.

Forests

Forest can be defined as the set of disjoint trees which can be obtained by deleting the root node and the edges which connects root node to the first level node.

Tree

Binary Tree

Binary tree is a data structure in which each node can have at most 2 children. The node present at the top most level is called the root node. A node with the 0 children is called leaf node. Binary Trees are used in the applications like expression evaluation and many more. We will discuss binary tree in detail, later in this tutorial.

Binary Search Tree

Binary search tree is an ordered binary tree. All the elements in the left sub-tree are less than the root while elements present in the right sub-tree are greater than or equal to the root node element. Binary search trees are used in most of the applications of computer science domain like searching, sorting, etc.

Expression Tree

Expression trees are used to evaluate the simple arithmetic expressions. Expression tree is basically a binary tree where internal nodes are represented by operators while the leaf nodes are represented by operands. Expression trees are widely used to solve algebraic expressions like (a+b)*(a-b). Consider the following example.

Q. Construct an expression tree by using the following algebraic expression.

(a + b) / (a*b – c) + d

Tree

Tournament Tree

Tournament tree are used to record the winner of the match in each round being played between two players. Tournament tree can also be called as selection tree or winner tree. External nodes represent the players among which a match is being played while the internal nodes represent the winner of the match played. At the top most level, the winner of the tournament is present as the root node of the tree.

For example, tree .of a chess tournament being played among 4 players is shown as follows. However, the winner in the left sub-tree will play against the winner of right sub-tree.

Tree

Table

Java Swing | JTable

The JTable class is a part of Java Swing Package and is generally used to display or edit two-dimensional data that is having both rows and columns. It is similar to a spreadsheet. This arranges data in a tabular form.

Constructors in JTable:

  1. JTable(): A table is created with empty cells.
  2. JTable(int rows, int cols): Creates a table of size rows * cols.
  3. JTable(Object[][] data, Object []Column): A table is created with the specified name where []Column defines the column names.

Functions in JTable:

  1. addColumn(TableColumn []column) : adds a column at the end of the JTable.
  2. clearSelection() : Selects all the selected rows and columns.
  3. editCellAt(int row, int col) : edits the intersecting cell of the column number col and row number row programmatically, if the given indices are valid and the corresponding cell is editable.
  4. setValueAt(Object value, int row, int col) :Sets the cell value as ‘value’ for the position row, col in the JTable.

Below is the program to illustrate the various methods of JTable:filter_none

// Packages to import import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable;  public class JTableExamples { // frame JFrame f; // Table JTable j;  // Constructor JTableExamples() { // Frame initiallization f = new JFrame();  // Frame Title f.setTitle("JTable Example");  // Data to be displayed in the JTable String[][] data = { { "Kundan Kumar Jha", "4031", "CSE" }, { "Anand Jha", "6014", "IT" } };  // Column Names String[] columnNames = { "Name", "Roll Number", "Department" };  // Initializing the JTable j = new JTable(data, columnNames); j.setBounds(30, 40, 200, 300);  // adding it to JScrollPane JScrollPane sp = new JScrollPane(j); f.add(sp); // Frame Size f.setSize(500, 200); // Frame Visible = true f.setVisible(true); }  // Driver  method public static void main(String[] args) { new JTableExamples(); } }
output

Leave a Reply

Your email address will not be published. Required fields are marked *