Java AWT Canvas Example
The java.awt.Canvas component is a “web” rectangular area for supporting drawing operations defined by the application as well as monitor input events performed by the user. This component does not encapsulate another feature except the support for rendering, providing a base class for creating new components.
This object can be used for double buffering techniques to avoid the effects of blinking, first painting on canvas and then adding to the canvas once already built screen.
Once we have drawn only the Canvas add any other ingredient. It is quite usual to derive a class of Canvas to redefine the functions we want to draw shapes and then add this new component to the relevant panel or window. The method that will schedule what we always draw.
public void paint(Graphics g)
This class provides a constructor and two methods of which we selected:
Method | Description |
Canvas () | Constructs a new Canvas object. |
paint (Graphics) | Renders the Canvas object through its graphics context. |
Picture Zooming in Java Swing Example
getImage in Java Swing Example
Hello Program in Japplet Java Swing Example
JApplet is a class that represents the Swing applet. It is a subclass of Applet class and must be extended by all the applets that use Swing. It provides all the functionalities of the AWT applet as well as support for menubars and layering of components. Whenever we require to add a component to it, the component is added to the content pane.
The JApplet defines the following constructor.
JApplet ()
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JHello2JavaExample extends JApplet implements ActionListener
{
JLabel Grtng = new JLabel("Hello. Who are you?");
Font FntOne = new Font("Arial", Font.BOLD, 36);
Font FntTwo = new Font("Arial", Font.ITALIC, 48);
JTextField answr = new JTextField(10);
JButton PrsMe = new JButton("Press me");
JLabel PrsnlGrtng = new JLabel(" ");
Container cntnr = getContentPane();
public void init()
{
Grtng.setFont(FntOne);
PrsnlGrtng.setFont(FntTwo);
cntnr.add(Grtng);
cntnr.add(answr);
cntnr.add(PrsMe);
cntnr.setLayout(new FlowLayout());
cntnr.setBackground(Color.YELLOW);
PrsMe.addActionListener(this);
answr.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String name = answr.getText();
cntnr.remove(Grtng);
cntnr.remove(PrsMe);
cntnr.remove(answr);
PrsnlGrtng.setText("Hello, " + name + "! ");
cntnr.add(PrsnlGrtng);
cntnr.setBackground(Color.CYAN);
validate();
}
}
Stroke Patteren in Java Swing Example
Gradient in Java Swing Example
Find Font List in Java Swing Example
Draw Star in Java Swing Example
3D Rectangles in Java Swing Example
Round Rectangles in Java Swing Example
The RoundRectangle2D class lets you draw a rectangle with corners rounded. The construction of the box is identical to that made with the class Rectangle2D, the only difference in this case are two additional parameters to end of the constructor, which indicate the width and length of the curve defining each corner. The larger these values will have higher level of rounding the corners.
import javax.swing.*;
import java.awt.*;
public class JRoundRectanglesJavaExample extends JFrame
{
public void paint(Graphics gr)
{
super.paint(gr);
int x = 30;
int y = 50;
final int WIDTH = 90, HEIGHT = 100;
final int HORIZ_GAPP = 110;
gr.drawRoundRect(x, y, WIDTH, HEIGHT, 0, 0);
x += HORIZ_GAPP;
gr.drawRoundRect(x, y, WIDTH, HEIGHT, 30, 30);
x += HORIZ_GAPP;
gr.drawRoundRect(x, y, WIDTH, HEIGHT, 50, 50);
x += HORIZ_GAPP;
gr.drawRoundRect(x, y, WIDTH, HEIGHT, 90, 90);
}
public static void main(String[] ars)
{
JRoundRectanglesJavaExample frm = new JRoundRectanglesJavaExample();
frm.setSize(470, 200);
frm.setVisible(true);
}
}
Draw Rectangles in Java Swing Example
Font in Java Swing Example
Change Component Location While Clicking Button In Java Swing
A button, also known as push button, is an active control that has a 3-dimensional appearance. It triggers an event when it is clicked or activated. Swing also provides an ability to associate an icon, a string, or both with the buttons. A push button is an object of JButton class.
Some of the constructors defined by JButton class are as follows.
JButton ()
JButton(Icon icon)
JButton(String string)
where,
string represents the string used for the button
icon represents the icon used for the button
Note: All the buttons are derived .from Abstract Button class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JLocationJavaExample extends JFrame implements ActionListener
{
JButton ClckBtn = new JButton("Click Here");
int x = 0, y = 0;
final int GP = 40;
public JLocationJavaExample()
{
setTitle("Change Component Location While Clicking Button In Java Swing");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(ClckBtn);
ClckBtn.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
ClckBtn.setLocation(x, y);
x += GP;
y += GP;
}
public static void main(String[] aa)
{
JLocationJavaExample frm = new JLocationJavaExample();
frm.setSize(190, 170);
frm.setVisible(true);
}
}
Paint Method in Java Swing Example
MenuBar Example in Java Swing
A menu bar represents a list of menus which can be added to the top of a top-level window. Each menu is associated with a drop-down list of menu items. The concept of menu bar can be implemented by using three Java classes: JMenuBar, Menu and JMenuitem. A menu bar is represented by the object of class JMenuBar in which only the default constructor is defined. A menu bar may consist of one or more menus represented by the objects of the class JMenu. A menu contains a list of menu items represented by the objects of the class JMenuitem.
The JMenu class defines the following constructors.
JMenu () //first
JMenu(String optionName) //second
JMenu(String optionName, boolean removable) //third
The first constructor creates an empty menu. The second constructor creates a menu with the name of the menu specified by optionName. In the third constructor, removable may have one of the two values: true or false. Ifit is true then the menu can float freely in the application window, otherwise it remains attached to the menu bar.
The JMenuitem class defines the following constructors.
JMenuitem () //first
JMenuitem(String itemName) //second
JMenuitem(String itemName, Icon icon) //third
The first constructor creates a menu item with no name and no menu shortcut. In the second constructor, itemName specifies the name of the menu item. In the third constructor, icon specifies the icon associated with the menu item.
A checkable menu item can also be created by using a subclass of JMenuitem called JCheckboxMenuitem.
The JCheckboxMenuitem class defines the following constructors.
JCheckboxMenuitem()
JCheckboxMenuitem(String itemName)
JCheckboxMenuitem(String itemName, boolean checkable)
The first constructor creates an unchecked menu item with no name. The second constructor creates an unchecked menu item with the name of the menu item specified by itemName. In the third constructor, checkable can either be true or false. If it is true then the menu item is initially checked, otherwise it is unchecked.
There are two types of menus which are given below.
• Regular menus: They are placed at the top of the application window within a menu bar.
• Pop-up menus: They appear in the window when the user clicks. For example, a pop-up menu appears on right click of the mouse.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JMenuBar2JavaExample extends JFrame
{
private JMenuBar MnuBar = new JMenuBar();
private JMenu MnuOne = new JMenu("File");
private JCheckBoxMenuItem chkOne = new JCheckBoxMenuItem("Check Box First");
private JCheckBoxMenuItem chkTwo = new JCheckBoxMenuItem("Check Box Second");
private JRadioButtonMenuItem RdoOne = new JRadioButtonMenuItem("Radio Button One");
private JRadioButtonMenuItem RdoTwo = new JRadioButtonMenuItem("Radio Button Two");
private JRadioButtonMenuItem RdoThree = new JRadioButtonMenuItem("Radio Button Three");
private ButtonGroup BtnGrp = new ButtonGroup();
public JMenuBar2JavaExample()
{
setTitle("Menu Bar2 In java Swing");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
setJMenuBar(MnuBar);
MnuBar.add(MnuOne);
MnuOne.add(chkOne);
MnuOne.add(chkTwo);
MnuOne.addSeparator();
MnuOne.add(RdoOne);
MnuOne.add(RdoTwo);
MnuOne.add(RdoThree);
BtnGrp.add(RdoOne);
BtnGrp.add(RdoTwo);
BtnGrp.add(RdoThree);
}
public static void main(String[] ds)
{
JMenuBar2JavaExample frm = new JMenuBar2JavaExample();
final int WIDTH = 170;
final int HEIGHT = 220;
frm.setSize(500,500);
frm.setVisible(true);
}
}
JMenuBar in Java Swing Example
JMenuBar, which is a drop down menu bar at the top application, and JPopupMenu, a menu you get when you press the button right mouse on a particular area. The menus are comprised of different items:
The components of a menu can be constructed using the JMenuBar, JMenu, JMenultem, JCheckBoxMenultem and JRadioButtonMenultem classes in a way similar to the MenuBar, Menu and Menultem classes of AWT.
When anyone of the menu items in Menu object “BackGround” is selected, the background colour of the frame is changed to the corresponding colour selected in the menu item. In the same way, when any of the menu items in the menu for Foreground is selected, the foreground colour of the frame will change to corresponding colour selected in the menu, which is displayed in the text field. Similarly if the Exit menu item is selected from exit menu, the frame is closed.
Constructors and methods of the JMenuBar class.
Names of methods | Description |
JMenuBar() | Constructs a new menu bar. |
JMenu add(Menu menu) | Adds the menu specified by a parameter, to the end of the menu bar. |
Component getComponentAtlndex (int index) | Returns the component at the specified index passed as a parameter. |
int getComponentlndex(Component c) | Returns the index of the component specified by the parameter. |
JMenugetMenu(int index) | Returns the menu at the specified index that is passed as a parameter to the function. |
int getMenuCount() | Returns the number of menus in the menu bar. |
This is demonstrated in Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JMenuBarJavaExample extends JFrame implements ActionListener
{
private JMenuBar MnuBar = new JMenuBar();
private JMenu MnuOne = new JMenu("File");
private JMenu MnuTwo = new JMenu("Colors");
private JMenuItem xit = new JMenuItem("Exit");
private JMenu bright = new JMenu("Bright");
private JMenuItem dark = new JMenuItem("Dark");
private JMenuItem white = new JMenuItem("White");
private JMenuItem pink = new JMenuItem("Pink");
private JMenuItem yellow = new JMenuItem("Yellow");
private JLabel Lbl = new JLabel("Hello");
public JMenuBarJavaExample()
{
setTitle("Menu Bar In java Swing");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
setJMenuBar(MnuBar);
MnuBar.add(MnuOne);
MnuBar.add(MnuTwo);
MnuOne.add(xit);
MnuTwo.add(bright);
MnuTwo.add(dark);
MnuTwo.add(white);
bright.add(pink);
bright.add(yellow);
xit.addActionListener(this);
dark.addActionListener(this);
white.addActionListener(this);
pink.addActionListener(this);
yellow.addActionListener(this);
add(Lbl);
Lbl.setFont(new Font("Times New Roman", Font.BOLD, 22));
}
public void actionPerformed(ActionEvent e)
{
Object src = e.getSource();
Container cntnr = getContentPane();
if(src == xit)
System.exit(0);
else if(src == dark)
cntnr.setBackground(Color.BLACK);
else if(src == white)
cntnr.setBackground(Color.WHITE);
else if(src == pink)
cntnr.setBackground(Color.PINK);
else cntnr.setBackground(Color.YELLOW);
repaint();
}
public static void main(String[] de)
{
JMenuBarJavaExample frm = new JMenuBarJavaExample();
final int WIDTH = 270;
final int HEIGHT = 220;
frm.setSize(500,500);
frm.setVisible(true);
}
}
Mouse Actions in Java Swing Example
Adding the Contents of Two objects by passing objects as parameter.
Calculate hra,da and gross salary of worker by passing Object as Parameter
Passing student Object as Parameter in Java Example
Example of this Pointer in Java
Demonstration of this Pointer
Example of Super Class By Feeding Employee Detail
Example of Super Class And Calculate Average of Three Variables
Example of Super Method in Java
Final Variable in Java Example
The final modifier indicates that an object is fixed and cannot be changed. When we use this modifier at a class level, it means that the class can never have subclasses. When we apply this modifier to a method, the method can never be overridden. When we apply this modifier to a variable, the value of the variable remains constant. We will get a compile-time error if we try to override a final method or class. We will also get a compile-time error if we try to change the value of a final variable. [Read more…] about Final Variable in Java Example
Example of Multilevel Inheritance in Java
Key Frame in Java Swing Example
Example JScrollPane in Java Swing
A scroll pane is a container that represents a small area to view other component. If the component is larger than the visible area, scroll pane provides horizontal and/or vertical scroll bars automatically for scrolling the components through the pane. A scroll pane is an object of the JScrollPane class which extends JComponent.
Some of the constructors defined by JScrollPane class are as follows.
JSrollPane ()
JScrollPane(Component component)
JScrollPane(int ver, int hor)
JScrollPane(Component component, int ver, int hor)
where,
component is the component to be added to the scroll pane
ver and hor specify the policies to display the vertical and horizontal scroll bar, respectively. Some of the standard policies are:
HORIZONTAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_AS_NEEDED, VERTICAL_SCROLLBAR_ALWAYS, VERTICAL_SCROLLBAR_AS_NEEDED
Note: JScrollPane is a lightweight container.
import javax.swing.*;
import java.awt.*;
public class JavaExampleJScrollPane extends JFrame
{
private JPanel Pnl = new JPanel();
private JScrollPane Scrl = new JScrollPane(Pnl,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
private JLabel Lbl = new JLabel("JScrollPane in Java Swing Example");
private Font font = new Font("Arial", Font.PLAIN, 20);
private Container cntnr;
public JavaExampleJScrollPane()
{
super("JScrollPane in Java Swing Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cntnr = getContentPane();
Lbl.setFont(font);
cntnr.add(Scrl);
Pnl.add(Lbl);
}
public static void main(String[] args)
{
final int WIDTH = 180;
final int HEIGHT = 100;
JavaExampleJScrollPane Scroll = new JavaExampleJScrollPane();
Scroll.setSize(250,300);
Scroll.setVisible(true);
}
}