Unit 3 java Introduction to AWT & SWING
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT is heavy weight i.e. its components are using the resources of underlying operating system (OS).
The java.awt package
provides classes
for AWT API such as TextField
, Label
, TextArea
, RadioButton, CheckBox
, Choice
, List
etc.
Why AWT is platform independent?
Java AWT calls the native platform calls the native platform (operating systems) subroutine for creating API components like TextField, ChechBox, button, etc.
For example, an AWT GUI with components like TextField, label and button will have different look and feel for the different platforms like Windows, MAC OS, and Unix. The reason for this is the platforms have different view for their native components and AWT directly calls the native subroutine that creates those components.
In simple words, an AWT application will look like a windows application in Windows OS whereas it will look like a Mac application in the MAC OS.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT, there are classes for each component as shown in above diagram. In order to place every component in a particular position on a screen, we need to add them to a container.
Container
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another window for creating a window. We need to create an instance of Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic container for holding the components. It can have other components like button, text field etc. An instance of Panel class creates a container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can have other components like button, text field, scrollbar etc. Frame is most widely used container while developing an AWT application.
he Container is a component in AWT that can contain another components like buttons
, textfields, labels etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel.
It is basically a screen where the where the components are placed at their specific locations. Thus it contains and controls the layout of components.
Window Fundamentals
The AWT defines windows according to a class hierarchy that adds functionality and specificity with each level. he two most common windows are those derived from Panel, which is used by applets, and those derived from Frame, which creates a standard application window. Much of the functionality of these windows is derived from their
parent classes. Thus, a description of the class hierarchies relating to these two classes fundamental to their understanding. Figure 25-1 shows the class hierarchy for Panel and
Frame. Let’s look at each of these classes now.
Component
At the top of the AWT hierarchy is the Component class. Component is an abstract class that encapsulates all of the attributes of a visual component. Except for menus,
subclasses of Component. It defines over a hundred public methods that are responsible for managing events, such as mouse and keyboard input, positioning and sizing the window, and repainting. A Component object is responsible for remembering the current foreground and background colors and the currently selected text font.
Container
The Container class is a subclass of Component. It has additional methods that allow other Component objects to be nested within it. Other Container objects can be stored inside of a Container (since they are themselves instances of Component). This makes for a multileveled containment system. A container is responsible for laying out
(that is, positioning) any components that it contains. It does this through the use of various
layout managers,
Panel
The Panel class is a concrete subclass of Container. A Panel may be thought of as a recursively nestable, concrete screen component. Panel is the superclass for Applet. When screen output is directed to an applet, it is drawn on the surface of a Panel object. In essence, a Panel is a window that does not contain a title bar, menu bar, or border. This is why you don’t see these items when an applet is run inside a browser. When you run an applet using an applet viewer, the applet viewer provides the title and border.
Window
The Window class creates a top-level window. A top-level window is not contained within any other object; it sits directly on the desktop. Generally, you won’t create Window objects directly. Instead, you will use a subclass of Window called Frame, described next. Frame
Frame encapsulates what is commonly thought of as a “window.” It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. The precise look of a Frame will differ among environments. A number of environments are reflected in the screen captures shown throughout this book.
Canvas
Although it is not part of the hierarchy for applet or frame windows, there is one other type of window that you will find valuable: Canvas. Derived from Component, Canvas encapsulates a blank window upon which you can draw. You will see an example of Canvas later in this book.
Working with Frame Windows
In addition to the applet, the type of AWT-based window you will most often create is derived from Frame. You will use it to create child windows within applets, and top-level or child windows for stand-alone applications. As mentioned, it creates a standard-style window. Here are two of Frame’s constructors:
Frame( ) throws HeadlessException Frame(String title) throws HeadlessException The first form creates a standard window that does not contain a title. The second form creates a window with the title specified by title. Notice that you cannot specify the dimensions
of the window. Instead, you must set the size of the window after it has been created. A HeadlessException is thrown if an attempt is made to create a Frame instance in
an environment that does not support user interaction.
There are several key methods you will use when working with Frame windows. They are examined here.
Setting the Window’s Dimensions
The setSize( ) method is used to set the dimensions of the window. Its signature is shown here:
void setSize(int newWidth, int newHeight) void setSize(Dimension newSize) The new size of the window is specified by newWidth and newHeight, or by the width and height fields of the Dimension object passed in newSize. The dimensions are specified in terms of pixels.
The getSize( ) method is used to obtain the current size of a window. One of its forms is shown here:
Dimension getSize( )
This method returns the current size of the window contained within the width and height fields of a Dimension object.
Hiding and Showing a Window
After a frame window has been created, it will not be visible until you call setVisible( ). Its signature is shown here:
void setVisible(boolean visibleFlag)
The component is visible if the argument to this method is true. Otherwise, it is hidden. Setting a Window’s Title
You can change the title in a frame window using setTitle( ), which has this general form: void setTitle(String newTitle)
Here, newTitle is the new title for the window.
Closing a Frame Window
When using a frame window, your program must remove that window from the screen when it is closed, by calling setVisible(false). To intercept a window-close event, you must implement the windowClosing( ) method of the WindowListener
interface. Inside windowClosing( ), you must remove the window from the screen. The example in the next section illustrates this technique.
Displaying Graphics in Applet
java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to draw the specified string. 2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the specified font.
Example of Graphics in applet:
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
working with color & fonts
Java programming language allows us to create different types of applications like windows application or web application. The user interface is an important factor while developing an application. The GUI of the Java application can be made interactive using different colors available in Java programming.
Java Color Constants
The color constants in Java are values that cannot be changed and can be used with different Java programs.
The following table shows the color constants available in the Java programming. The all-capital version depicts a constant value. But lowercase version also works fine.
import java.awt.*;
import javax.swing.*;
class ColorExample extends JFrame
{
ColorExample()
{
super("color");
Color c1 = new Color(0, 0, 204);
JPanel p = new JPanel();
p.setBackground(c1);
setSize(200, 200);
add(p);
show();
}
public static void main(String args[])
{
ColorExample c = new ColorExample();
}
}
Java Font
In Java, Font is a class that belongs to the java.awt package. It implements the Serializable interface. FontUIResource is the direct known subclass of the Java Font class.
It represents the font that are used to render the text. In Java, there are two technical terms that are used to represent font are characters and Glyphs.
Types of Fonts in Java
There are two types of fonts in Java:
o Physical Fonts
o Logical Fonts
Physical Fonts
Physical fonts are actual Java font library. It contains tables that maps character sequence to glyph sequences by using the font technology such as TrueType Fonts (TTF) and PostScript Type 1 Font. Note that all implementation of Java must support TTF. Using other font technologies is implementation dependent. Physical font includes the name such as Helvetica, Palatino, HonMincho, other font names.
The property of the physical font is that it uses the limited set of writing systems such as Latin characters or only Japanese and Basic Latin characters. It may vary as to
configuration changes. If any application requires a specific font, user can bundle and instantiate that font by using the createFont() method of the Java Font class.
Logical Fonts
Java defines five logical font families that are Serif, SansSerif, Monospaced, Dialog, and DialogInput. It must be supported by the JRE. Note that JRE maps the logical font names to physical font because these are not the actual font libraries. Usually, mapping
implementation is locale dependent. Each logical font name map to several physical fonts in order to cover a large range of characters.
For example, AWT components such as Label and TextField uses logical fonts only. Font Faces and Names
A font may have many faces such as heavy, regular, medium, oblique, gothic, etc. All font faces have the similar typograph design.
A Font object have three different names that are:
o Logical font name: It is the name that is used to construct the font.
o Font face name: It is the name of particular font face. For example, Helvetica Bold. o Family name: It is the name of the font family. It determines the typograph design among several faces.
The Java Font class represents an instance of a font face from a collection of font faces that are present in the system resources of the host system. Example of font faces are Arial Bold, Courier Bold Italic, etc. A font face (each differing in size, style, transform and font feature) may associate with several Font objects.
import java.applet.Applet;
import java.awt.Font;
import java.awt.Graphics;
public class JavaFontExample extends Applet
{
public void paint(Graphics gph)
{
Font font= new Font("Courier", Font.PLAIN, 20);
gph.setFont(font);
gph.drawString("Javatpoint is the best learning platform.", 12, 45);
}
}
Border Layout (Layout Managers)
Java Layout Managers
The LayoutManagers are used to arrange components in a particular manner. The Java LayoutManagers facilitates us to control the positioning and size of the components in GUI forms. LayoutManager is an interface that is implemented by all the classes of layout managers. There are the following classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west, and center. Each region (area) may contain one component only. It is the default layout of a frame or window. The BorderLayout provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
o BorderLayout(): creates a border layout but with no gaps between the components. o BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between the components.
Example of BorderLayout class: Using BorderLayout() constructor
FileName: Border.java
import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame f;
Border()
{
f = new JFrame();
JButton b1 = new JButton("NORTH");
JButton b2 = new JButton("SOUTH");
JButton b3 = new JButton("EAST");
JButton b4 = new JButton("WEST");
JButton b5 = new JButton("CENTER");
f.add(b1, BorderLayout.NORTH);
f.add(b2, BorderLayout.SOUTH);
f.add(b3, BorderLayout.EAST);
f.add(b4, BorderLayout.WEST);
f.add(b5, BorderLayout.CENTER);
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Introduction to Swing
Swing is the collection of user interface components for Java programs. It is part of Java Foundation classes that are referred to as JFC. In simple words, Swing is the graphical user interface toolkit that is used for developing windows based java applications or programs. It is the successor of AWT, which is known as Abstract window toolkit API for Java, and AWT components are mainly heavyweight.
The components are lightweight as compared to AWT components. It provides a good interface to the user for all the platforms. It is not specifically for one platform. The components are written in Java and platform-independent as well. The Java foundation classes were first appeared in 1997, and then, later on, it is termed as Swing. To use the swing in java, javax. swing package needs to be used or import. It is also known as Java Swing.
Features of Swing
The features of the Swing are as follows:
1. Platform Independent: It is platform-independent; the swing components that are used to build the program are not platform-specific. It can be used on any platform and anywhere.
2. Lightweight: Swing components are lightweight, which helps in creating the UI lighter. The swings component allows it to plug into the operating system user interface framework that includes the mappings for screens or devices and other user interactions like keypress and mouse movements.
3. Plugging: It has a powerful component that can be extended to provide support for the user interface that helps in a good look and feel to the application. It refers to the highly modular based architecture that allows it to plug into other customized implementations and frameworks for user interfaces. Its components are imported through a package called java.swing.4. Manageable: It is easy to manage and configure. Its mechanism and composition
pattern allows changing the settings at run time as well. The uniform changes can be provided to the user interface without doing any changes to the application code.
5. MVC: They mainly follow the concept of MVC that is the Model View Controller. With the help of this, we can do the changes in one component without impacting or touching other components. It is known as loosely coupled architecture as well.
6. Customizable: Swing controls can be easily customized. It can be changed, and the visual appearance of the swing component application is independent of its internal representation.
Examples of Swing
The component class is mainly used, and there are some of the methods that are frequently used, like adding a component in another component (add (Component a)), setting the size, layout, and visibility of components accordingly.
Below is the example:
public class Test extends JFrame {
public Test() {
setDefaultCloseOperation(WindowCo
add(new JLabel("Test, Application!")); pack();
setVisible(true);
}
public static void main(final String[] args) { new Test();
}
JApplet
JApplet is a java swing public class designed for developers usually written in Java. JApplet is generally in the form of Java bytecode that runs with the help of a Java virtual machine (JVM) or Applet viewer from Sun Microsystems. It was first introduced in 1995.
JApplet can also be written in other programming languages and can later be compiled to Java byte code.
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements ActionListener{
JButton b;
JTextField tf;
public void init(){
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}
Icons &labels button & Label
Buttons and Labels
We’ll start with the simplest components: buttons and labels. Frankly, there isn’t much to say about them. If you’ve seen one button, you’ve seen them all, (HelloJava3 and HelloJava4). A button generates an ActionEvent when the user presses it. To receive these events, your program registers an ActionListener, which must implement the actionPerformed() method. The argument passed to actionPerformed() is the event itself.
There’s one more thing worth saying about buttons, which applies to any component that generates an action event. Java lets us specify an “action command” string for buttons (and other components, like menu items, that can generate action events). The action command is less interesting than it sounds. It is just a String that serves to identify the component that sent the event. By default, the action command of a JButton is the same as its label; it is included in action events so that you could use it to figure out which button
an event came from. However, you’ll often know this from the context of your event listener.
To get the action command from an action event, call the event’s getActionCommand() method. The following code checks whether the user pressed the button labeled Yes:
public void actionPerformed(ActionEvent e){
if (e.getActionCommand().equals("Yes") {
//the user pressed "Yes"; do something
...
}
}
Yes is a string, not a command per se. You can change the action command by calling the button’s setActionCommand() method. The following code changes button myButton’s action command to “confirm:”
myButton.setActionCommand("confirm");
It’s a good idea to get used to setting action commands explicitly; this helps to prevent your code from breaking when you or some other developer internationalizes it or otherwise changes the button’s label. If you rely on the button’s label, your code stops working as soon as that label changes; a French user might see the label Oui rather than Yes.
Swing buttons can have an image in addition to a label. The JButton class includes constructors that accept an Icon object, which knows how to draw itself. You can create buttons with captions, images, or both. A handy class called ImageIcon takes care of loading an image for you and can be used to add an image to a button. The following example shows how this works:
//file: PictureButton.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PictureButton {
public static void main(String[] args)
{
JFrame frame = new JFrame();
Icon icon = new ImageIcon("rhino.gif");
JButton button = new JButton(icon);
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println("Urp!");
}
});
frame.getContentPane().add( button );
frame.pack();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setVisible(true);
}
}
The example creates an ImageIcon from the rhino.gif file. Then, a JButton is created from the ImageIcon. The whole thing is displayed in a JFrame. This example also shows the idiom of using an anonymous inner class as an ActionListener.
There’s even less to be said about JLabel components. They’re just text strings or images housed in a component. There aren’t any special events associated with labels; about all you can do is specify the text’s alignment, which controls the position of the text within the label’s display area. As with buttons, JLabels can be created with Icons if you want to create a picture label. The following code creates some labels with different options:
JLabel label1 = new JLabel("Lions");
JLabel label2 = new JLabel("Tigers", SwingConstants.LEFT);
JLabel label3 = new JLabel();
Icon icon = new ImageIcon("rhino.gif");
JLabel label4 = new JLabel(icon);
label3.setText("and Bears");
label3.setHorizontalAlignment(SwingConstants.RIGHT);
The alignment constants are defined in the SwingConstants interface.
We’ve built several labels using a variety of constructors and several of the class’s methods. To display the labels, just add them to a container by calling the container’s add() method.
You can set other label characteristics, such as changing their font or color, using the methods of the Component class, JLabel’s distant ancestor. For example, you can call setFont() and setBackground() on a label, as with any other component.
Given that labels are so simple, why do we need them at all? Why not find a way to draw a text string directly on the container object? Remember that a JLabel is a JComponent. That means that labels have the normal complement of methods for setting fonts and colors that we mentioned earlier as well as the ability to be persistently and sensibly managed by a layout manager. Therefore, they’re much more flexible than a text string drawn procedurally at an arbitrary location within a container. Speaking of layouts—if you use the setText() method to change the text of your label, the label’s preferred size may change. But the label’s container automatically lays out its components when this happens so you don’t have to worry about it.
Text Field & Toggle Buttons
A JToggleButton is a two-state button. The two states are selected and unselected. The JRadioButton and JCheckBox classes are subclasses of this class. When the user presses the toggle button, it toggles between being pressed or unpressed. JToggleButton is used to select a choice from a list of possible choices. Buttons can be configured, and to some degree controlled, by Actions. Using an Action with a button has many benefits beyond directly configuring a button.
Constructors in JToggleButton:
1. JToggleButton(): Creates an initially unselected toggle button without setting the text or image.
2. JToggleButton(Action a): Creates a toggle button where properties are taken from the Action supplied.
3. JToggleButton(Icon icon): Creates an initially unselected toggle button with the specified image but no text.
4. JToggleButton(Icon icon, boolean selected): Creates a toggle button with the specified image and selection state, but no text.
5. JToggleButton(String text): Creates an unselected toggle button with the specified text.
6. JToggleButton(String text, boolean selected): Creates a toggle button with the specified text and selection state.
7. JToggleButton(String text, Icon icon): Creates a toggle button that has the specified text and image, and that is initially unselected.
8. JToggleButton(String text, Icon icon, boolean selected): Creates a toggle button with the specified text, image, and selection state.
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
public class JToggleButtonExamp {
public static void main(String args[])
{
JFrame frame = new JFrame("Selecting Toggle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JToggleButton toggleButton = new JToggleButton("Toggle Button");
ItemListener itemListener = new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent)
{
int state = itemEvent.getStateChange();
if (state == ItemEvent.SELECTED) {
System.out.println("Selected");
}
else {
System.out.println("Deselected");
}
}
};
toggleButton.addItemListener(itemListener);
frame.add(toggleButton, BorderLayout.NORTH);
frame.setSize(300, 125);
frame.setVisible(true);
}
}
Checkboxes
Checkbox control is used to turn an option on(true) or off(false). There is label for each checkbox representing what the checkbox does.The state of a checkbox can be changed by clicking on it.
Class declaration
Following is the declaration for java.awt.Checkbox class:
import java.awt.*;
public class CheckboxExample1
{
CheckboxExample1() {
Frame f = new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
checkbox2.setBounds(100, 150, 50, 50);
f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main (String args[])
{
new CheckboxExample1();
}
}
Radio Button
We use the JRadioButton class to create a radio button. Radio button is use to select one option from multiple options. It is used in filling forms, online objective papers and quiz.
We add radio buttons in a ButtonGroup so that we can select only one radio button at a time. We use “ButtonGroup” class to create a ButtonGroup and add radio button in a group.
Methods Used :
1. JRadioButton() : Creates a unselected RadioButton with no text. Example:
2. JRadioButton j1 = new JRadioButton()
3. JButton(String s) : Creates a JButton with a specific text.
Example:
4. JButton b1 = new JButton("Button")
5. JLabel(String s) : Creates a JLabel with a specific text.
Example:
6. JLabel L = new JLabel("Label 1")
7. ButtonGroup() : Use to create a group, in which we can add JRadioButton. We can select only one JRadioButton in a ButtonGroup.
Steps to Group the radio buttons together.
∙ Create a ButtonGroup instance by using “ButtonGroup()” Method. ∙ ButtonGroup G = new ButtonGroup()
∙ Now add buttons in a Group “G”, with the help of “add()” Method. Example:
G.add(Button1);
G.add(Button2);
8. isSelected() : it will return a Boolean value true or false, if a JRadioButton is selected it Will return true otherwise false.
Example:
JRadioButton.isSelected()
9. Set(…) and Get(…) Methods :
i) Set and get are used to replace directly accessing member variables from external classes.
ii) Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them.
import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){ f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
Combo Box & Lists
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 .
import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
Scroll panes
A JscrollPane is used to make scrollable view of a component. When screen size is limited, we use a scroll pane to displalarge component or a component whose size can change dynamically.
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;
public class JScrollPaneExample {
private static final long serialVersionUID = 1L;
private static void createAndShowGUI() {
final JFrame frame = new JFrame("Scroll Pane Example");
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout());
JTextArea textArea = new JTextArea(20, 20);
JScrollPane scrollableTextArea = new JScrollPane(textArea);
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Trees
If I had to pick the single most important topic in software development, it would be data structures. One of the most common and easiest ones is a tree – a hierarchical data structure. In this article, let’s explore Trees in Java.
What is a Binary Tree?
A Tree is a non-linear data structure where data objects are generally organized in terms of hierarchical relationship. The structure is non-linear in the sense that, unlike Arrays, Linked Lists, Stack and Queues, data in a tree is not organized linearly. A binary tree is a recursive tree data structure where each node can have 2 children at most.
Binary trees have a few interesting properties when they’re perfect:
∙ Property 1: The number of total nodes on each “level” doubles as you move down the tree. ∙ Property 2: The number of nodes on the last level is equal to the sum of the number of nodes on all other levels, plus 1
Each data element stored in a tree structure called a node. A Tree node contains the following parts:
1. Data
2. Pointer to left child
3. Pointer to the right child
In Java, we can represent a tree node using class. Below is an example of a tree node with integer data.
1
static class Node {
2
int value;
3
Node left, right;
4
5
Node(int value){
6
this.value = value;
left = null;
7
right = null;
8
}
9
Now that you know what is a binary tree, let’s check out different types of binary trees. Types of Binary Trees
Full Binary Tree
A full binary tree is a binary tree where every node has exactly 0 or 2 children. The example of fully binary tress is:
Perfect Binary Tree
A binary tree is perfect binary Tree if all internal nodes have two children and all leaves are at the same level. The example of perfect binary tress is:
Complete Binary Tree
A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. An example of a complete binary tree is:
Now that you are aware of different types of binary trees, let’s check out how to create a binary tree.
Binary Tree Implementation
For the implementation, there’s an auxiliary Node class that will store int values and keeps a reference to each child. The first step is to find the place where we want to add a new node in order to keep the tree sorted. We’ll follow these rules starting from the root node:
∙ if the new node’s value is lower than the current node’s, go to the left child ∙ if the new node’s value is greater than the current node’s, go to the right child ∙ when
Tables
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.
import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
Menu Bars & menus
The JMenuBar class is used to display menubar on the window or frame. It may have several menus.
The object of JMenu class is a pull down menu component which is displayed from the menu bar. It inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must belong to the JMenuItem or any of its subclass.
import javax.swing.*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}}
Tools Bars
JToolBar is a part of Java Swing package. JToolBar is an implementation of toolbar. The JToolBar is a group of commonly used components such as buttons or drop down menu.
JToolBar can be dragged to different locations by the user
Constructors of the class are:
1. JToolBar() : creates a new toolbar with horizontal orientation
2. JToolBar(int o) : creates a new toolbar with specified orientation 3. JToolBar(String n) : creates a new toolbar with specified name
4. JToolBar(String n, int o) : creates a new toolbar with specified name and orientation.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Tool extends JFrame {
static JToolBar tb;
static JButton b1, b2;
static JFrame f;
static JComboBox x;
public static void main()
{
f = new JFrame("Toolbar demo");
f.setLayout(new BorderLayout())
tb = new JToolBar();
JPanel p = new JPanel();
x = new JComboBox(new String[] { "item 1", "item 2", "item 3" });
b1 = new JButton("button 1");
b2 = new JButton("button 2");
p.add(b1);
p.add(b2);
p.add(x);
tb.add(p);
f.add(tb, BorderLayout.NORTH);
f.setSize(500, 500);
f.setVisible(true);
}
}
Dialog Boxes
Java class named JOptionPane that produce dialog boxes. A dialog box is a GUI object in which you can place messages that you want to display on the screen. The showMessageDialog() method that is part of the JOptionPane class. The showMessageDialog() method is followed by a set of parentheses. The showMessageDialog() are two arguments. The first argument is null.
its means the message box should be shown in the center of the screen. After the comma, second argument is the string that should be output.
import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Hello, Welcome to Javatpoint.");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
File Dialog
Introduction
FileDialog control represents a dialog window from which the user can select a file. Class declaration
Following is the declaration for java.awt.FileDialog class:
Field
Following are the fields for java.awt.Image class:
∙ static int LOAD -- This constant value indicates that the purpose of the file dialog window is to locate a file from which to read.
∙ static int SAVE -- This constant value indicates that the purpose of the file dialog window is to locate a file to which to write.
Class constructors
Progress bar
JProgressBar is a part of Java Swing package. JProgressBar visually displays the progress of some specified task. JProgressBar shows the percentage of completion of specified task.The progress bar fills up as the task reaches it completion. In addition to show the percentage of completion of task, it can also display some text . Constructors of JProgressBar :
1. JProgressBar() : creates an progress bar with no text on it;
2. JProgressBar(int orientation) : creates an progress bar with a specified orientation. if SwingConstants.VERTICAL is passed as argument a vertical progress bar is created, if SwingConstants.HORIZONTAL is passed as argument a horizontal progress bar is created.
3. JProgressBar(int min, int max) : creates an progress bar with specified minimum and maximum value.
4. JProgressBar(int orientation, int min, int max) : creates an progress bar with specified minimum and maximum value and a specified orientation.if SwingConstants.VERTICAL is passed as argument a vertical progress bar is created, if SwingConstants.HORIZONTAL is passed as argument a horizontal progress bar is created.
Commonly used methods of JProgressBar are :
1. int getMaximum() : returns the progress bar’s maximum value. 2. int getMinimum() : returns the progress bar’s minimum value. 3. String getString() : get the progress bar’s string representation of current value. 4. void setMaximum(int n) : sets the progress bar’s maximum value to the value n. 5. void setMinimum(int n) : sets the progress bar’s minimum value to the value n. 6. void setValue(int n) : set Progress bar’s current value to the value n. 7. void setString(String s) : set the value of the progress String to the String s. 1. Program to create a simple progress bar
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class progress extends JFrame {
static JFrame f;
static JProgressBar b;
public static void main()
{
f = new JFrame("ProgressBar demo");
JPanel p = new JPanel();
b = new JProgressBar(); b.setValue(0);
b.setStringPainted(true); p.add(b);
f.add(p);
f.setSize(500, 500); f.setVisible(true);
fill();
}
public static void fill()
{
int i = 0;
try {
while (i <= 100) { b.setValue(i + 10); Thread.sleep(1000); i += 20;
}
}
catch (Exception e) {
}
}
}
Choosers
JFileChooser is a part of java Swing package. The java Swing package is part of JavaTM Foundation Classes(JFC) . JFC contains many features that help in building graphical user interface in java . Java Swing provides components such as buttons, panels, dialogs, etc . JFileChooser is a easy and an effective way to prompt the user to choose a file or a directory .
In this article we will see how to use JFileChooser in java swing .
Constructors of JFileChooser are :
1. JFileChooser() – empty constructor that points to user’s default directory ∙ Java
JFileChooser j = new JFileChooser();
j.showSaveDialog(null);
Output of the code snippet:
2. JFileChooser(String) – uses the given path ∙ Java
JFileChooser j = new JFileChooser("d:");
j.showSaveDialog(null);
Output of the code snippet:
3. JFileChooser(File) – uses the given File as the path
∙ Java
JFileChooser j = new JFileChooser(new File("C:\\Users\\pc\\Documents\\New folder\\")); j.showSaveDialog(null);
Output of the code snippet:
4. JFileChooser(FileSystemView) – uses the given FileSystemView ∙ Java
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView()); j.showSaveDialog(null);
Output of the code snippet:
5. JFileChooser(String, FileSystemView) – uses the given path and the FileSystemView ∙ Java
JFileChooser j = new JFileChooser("d:", FileSystemView.getFileSystemView());
j.showSaveDialog(null);
Output of the code snippet:
6. JFileChooser(File, FileSystemView) – uses the given current directory and the FileSystemView
∙ Java
File f = new File("C:\\Users\\pc\\Documents\\New folder\\");
JFileChooser j = new JFileChooser(f, FileSystemView.getFileSystemView()// Open the save dialog j.showSaveDialog(null);
Output of the code snippet:
Note : The code given above are code snippets not the full code, the code snippets given above should be used to invoke the constructor as per the need and discretion of the programmer, the paths mentioned above are arbitrary. User should set the path according to their need.
No comments:
Post a Comment