• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Java

Java Example showOptionDialog

By Dinesh Thakur

A dialog box (“dialog” for short) is any box, or window, on the screen that you have a dialog with. You can decide to pop up some dialog boxes j to enter information in, or make choices about how a program works. “Other dialogs appear automatically to give you simple messages (such as “Your disk is full”) and ask you what you want to do about it.

 

Some people make a distinction between dialog boxes and alert boxes (where the computer warns you about something) or message boxes (where the computer just tells you about something), but that really only matters if you’re a programmer. Everyone will understand what you mean if you call them all dialog boxes.

import java.awt.*; 
import java.awt.event.*;
import javax.swing.*;
public class JavaExampleOptionPane
        {
            public static void main( String aa[] )
                  {
                    Object[] Btns = {"One", "Two", "Three", "Four" };
                     int Rspns =JOptionPane.showOptionDialog( null, "Message", "Option Pane In
Java",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE, null,Btns, "One" );
                     String Typ = "Undefined";
                     if( Rspns == JOptionPane.YES_OPTION ) { Typ = "Yes"; }
                     if( Rspns == JOptionPane.NO_OPTION ) { Typ = "No"; }
                     if( Rspns == JOptionPane.CANCEL_OPTION ) { Typ = "Cancel"; }
                     System.out.println( Typ + ": " + Rspns );
                  }
       }

showOptionDialog Java Example

JColorChooser Panel Java Example

By Dinesh Thakur

[Read more…] about JColorChooser Panel Java Example

JColorChooser Java Example

By Dinesh Thakur

[Read more…] about JColorChooser Java Example

JTabbedPane Java Example

By Dinesh Thakur

Sometimes a situation may arise when there are lots of components that cannot be accommodated in a single screen. In that case, tabbed pane is used to create tabs where each tab contains group of related components. When a particular tab is clicked, the components of that tab are displayed in the forefront. Tabbed pane is very common feature of GUI interfaces. It is commonly used in dialog boxes containing lots of commands. A tabbed pane is an object of JTabbedPane class.

Some of the constructors defined by JTabbedPane class are as follows:

JTabbedPane ()

JTabbedPane(int tabPlacement)

where,

tabPlacement specifies the position of tabs-can have one of the four values: TOP, BOTTOM, LEFT or RIGHT

[Read more…] about JTabbedPane Java Example

showConfirmDialog Java Example

By Dinesh Thakur

A confirmation dialog box is meant for asking a confirmation question and allows the user to give a yes/no/cancel response. It is created by using the static method showConfirmDialog() of JOptionPane. The general form of showConfirmDialog()method is

public static int showConfirmDialog(Component parentComponent,

Object message)

where,

parentComponent is the frame to which the dialog box is attached

message is the message to be displayed

[Read more…] about showConfirmDialog Java Example

Java Example Image Size Increaser

By Dinesh Thakur

[Read more…] about Java Example Image Size Increaser

Java Example Event Image

By Dinesh Thakur

[Read more…] about Java Example Event Image

FocusListener in Java Example

By Dinesh Thakur

When a component receives focus, ie, is the element of the screen that is active FocusEvent type events occur. 

To make an object can listen to events FocusEvent FocusListener type must implement the interface, and it must be added as to the method FocusListener

public void addFocusListener(FocusListener fl)
The methods of this interface are:
public void focusGained(FocusEvent e)
public void foculsLost(FocusEvent e)

Given the existence of temporary changes in focus (for example when using scroll bars associated with a TextArea, Choice List or component) or permanent (when you use the “Tab” key to navigate between components interface), the method is useful below:


Method

Description

isTemporary()

Determines whether the event focus change is temporary or permanent.

 

 

import java.awt.Dimension; 
import java.awt.GridLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Color;
import java.awt.Button;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
class JavaExampleShowingInterface extends Frame
  {
    private Label LblPass;
    private Label LblUsrNm;
    private TextField TxtNm;
    private TextField TxtPass;
    JavaExampleShowingInterface(String TTL)
     {
       setTitle(TTL);
       setLayout(new GridLayout(3,3));
       setSize(new Dimension(550,200));
       addWindowListener(new WindowAdapter()
        {
           public void windowClosing(WindowEvent ee)
             {
                System.exit(0);
             }
        });
               TxtNm=new TextField(30);
               TxtNm.addFocusListener(new FocusList());
               add(new Label("Your Name:")); 
               add(TxtNm);
               LblPass=new Label();
               add(LblPass);
               TxtPass=new TextField(30);
               TxtPass.setEchoChar('*');
               TxtPass.addFocusListener(new FocusList());
               add(new Label("Password Plz:"));
               add(TxtPass);
               LblPass=new Label();
               add(LblPass); 
               add(new Button("OK"));
               setVisible(true);
               validate();
    }
          class FocusList implements FocusListener
            {
               public void focusGained(FocusEvent ee){}
                    public void focusLost(FocusEvent ee)
                  {
                         TextField Txt=(TextField)ee.getSource();
                          if(Txt.getText().equals("") && Txt==TxtNm)
                        {
                               LblUsrNm.setForeground(Color.RED);
                               LblUsrNm.setText("User name can not be blank.");
                            }
                               else
                               LblUsrNm.setText("");
                               if(Txt.getText().equals("") && Txt==TxtPass)
                              {
                                     LblPass.setForeground(Color.RED);   
                                     LblPass.setText("Password can not be blank.");
                                 }
                                    else
                                    LblPass.setText("");
                      }
            }
                     public static void main(String[] aa)
                    {
                           new JavaExampleShowingInterface("Focus Listener In Java");
                        }
 }


FocusListener in Java Example

JInternalFrame Example in Java Swing

By Dinesh Thakur

An internal frame is similar to a regular frame which can be displayed within another window. It is a lightweight component which can be resized, closed, maximized or minimized depending upon the properties being set. It can also hold a title and a menu bar. An internal frame is an object of JinternalFrame class.

Some of the constructors defined by JinternalFrame class are as follows:

JinternalFrame()

JinternalFrame(String title)

JinternalFrame(String title, boolean resizable)

JinternalFrame(String title, boolean resizable, closable, boolean maximizable, boolean iconifiable)

where,

title specifies the title of the frame

resizable can have one of the two values: true, if the internal frame is resizable; otherwise false (default value)

closable can have one of the two values: true, if the internal frame is closeable, otherwise false (default value)

maximizable can have one of the two values: true, if the internal frame is maximizable, otherwise false (default value)

iconifiable can have one of the two values: true, if the internal frame is minimizable, otherwise false (default value)

The internal frame requires desktop pane which is capable of handling it. The purpose of desktop pane is to hold and manage the working of internal frames. A desktop pane is an object of JDesktopPane class and can be created by using its only constructor JDesktopPane ().

import javax.swing.*; 
public class JInternalFrameJavaExample extends JFrame
{
     public JInternalFrameJavaExample()
    {
       super();
    }
    public static void main(java.lang.String[] args)
    {
        JInternalFrameJavaExample InternalFrame = new JInternalFrameJavaExample();
        InternalFrame.pack();
        InternalFrame.setSize(500, 200);
        JInternalFrame IFrame = new JInternalFrame();
        IFrame.setVisible(true);
        IFrame.setTitle("JInternalFrame Example");
        InternalFrame.getContentPane().add(IFrame);
        InternalFrame.setTitle("JInternalFrame Example in Java Swing");
        InternalFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        InternalFrame.setVisible(true);
    }
}

JInternalFrame Example in Java Swing

TextField in Java Example

By Dinesh Thakur

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:

Method

Description

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

Java Clipboard in Swing Example

By Dinesh Thakur

The following example is a simple demonstration of cut, copy, and paste String data type with a JTextArea. One thing you will notice is that the keyboard sequences normally used to cut, copy and paste also work. But if you look at any JTextField or JTextArea in any other program, you will find that these also support keyboard sequences clipboard automatically. this example simply adds programmatic control of the clipboard, and You can use these techniques if you want to capture text from the clipboard into something else than a JTextComponent.

Creating and added menu and JTextArea should by now seem a prosaic activity. What is different is the creation of the field Cboard Clipboard, which is done through Toolkit.

All actions take place in the listeners. The Copy and listeners Cut are the same except for the last line Cut, erasing the line has been copied. The two special lines are creating an object StringSelection the String and the call to setContents () with this StringSelection. All that is there is to put a String to the clipboard.

Paste, the data is removed from the clipboard using getContents (). What comes back is a fairly anonymous Transferable object, and it is uncertain actually it contains. One way to know is to call getTransferFlavors (), which returns an array of DataFlavor objects indicating that flavors are supported by this particular object. It You can also ask directly isDataFlavorSupported () passing the taste in which we are interested. Here, however, a bold strategy is used: getTransferData () is called assuming content supports the flavor of String, and if it does the problem is solved in the exception handler.

import javax.swing.*; 
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
public class ClipboardJavaExample extends JFrame
{
       JMenuBar MenuBar = new JMenuBar();
       JMenu File = new JMenu("File");
       JMenu edit = new JMenu("Edit");
       JMenuItem cut = new JMenuItem("Cut"),
                        copy = new JMenuItem("Copy"),
                        paste = new JMenuItem("Paste");
       JTextArea TextArea = new JTextArea(20, 20);
       Clipboard Cboard = getToolkit().getSystemClipboard();
       public ClipboardJavaExample()
      {
             cut.addActionListener(new Cut());
             copy.addActionListener(new Copy());
             paste.addActionListener(new Paste());
             edit.add(cut);
             edit.add(copy);
             edit.add(paste);
             MenuBar.add(File);
             MenuBar.add(edit);
             setJMenuBar(MenuBar);
             getContentPane().add(TextArea);
       }
       class Copy implements ActionListener
      {
            public void actionPerformed(ActionEvent e)
           {
               String selection = TextArea.getSelectedText();
               if (selection == null)
                  return;
                 StringSelection clipString =new StringSelection(selection);
                 Cboard.setContents(clipString,clipString);
            }
      }
            class Cut implements ActionListener
           {
                      public void actionPerformed(ActionEvent e)
                     {
                            String selection = TextArea.getSelectedText();
                            if (selection == null)
                                 return;
                                 StringSelection clipString = new StringSelection(selection);
                                 Cboard.setContents(clipString, clipString);
                                 TextArea.replaceRange("", TextArea.getSelectionStart(), TextArea.getSelectionEnd());
                      }
            }
           class Paste implements ActionListener
          {
                  public void actionPerformed(ActionEvent e)
                 {
                    Transferable clipData = Cboard.getContents(ClipboardJavaExample.this);
                     try
                    {
                         String clipString = (String)clipData.getTransferData(DataFlavor.stringFlavor);
                         TextArea.replaceRange(clipString,TextArea.getSelectionStart(),TextArea.getSelectionEnd());
                    }   catch(Exception ex)
                              {
                                   System.err.println("Not Working");
                              }
               }
          }
                public static void main(String[] args)
               {
                    JFrame frame = new ClipboardJavaExample();
                    frame.setTitle("Clipboard in Java Swing Example");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setSize(320, 200);
                    frame.setVisible(true);
                   
               }
}

Clipboard in Java Swing Example

Sliders and Progress bars Java Example

By Dinesh Thakur

A slider allows the user to enter a point moving data back and forth, which is intuitive in some situations (volume control, for example). a progress bar displays data in a relative form of “full” to “empty” so the user gets a perspective.

The key to hooking the two components together is to share your model in the line:
ProgressBar.setModel(Slider.getModel());
The JProgressBar is fairly straightforward, but the JSlider has a lot of options, such as orientation and major and minor brands.
Here is the example of Sliders and Progress bars

/* <applet code= Progress.class width=320 height=200> </applet> */ import javax.swing.*; 
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class Progress extends JApplet
{
           JProgressBar ProgressBar = new JProgressBar();
           JSlider Slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 60);
           public void init()
          {
                Frame frm = (Frame)this.getParent().getParent();
                frm.setTitle("Sliders and Progress bars");
                Container container = getContentPane();
                container.setLayout(new GridLayout(2,1));
                container.add(ProgressBar);
                Slider.setValue(0);
                Slider.setPaintTicks(true);
                Slider.setMajorTickSpacing(20);
                Slider.setMinorTickSpacing(5);
                Slider.setBorder(new TitledBorder("Slide Bar (JSlider)"));
                ProgressBar.setModel(Slider.getModel());
                container.add(Slider);
          }
}

Sliders and Progress bars

HTML text on Swing Components Java Example

By Dinesh Thakur

Any component that can take text can also make HTML text , which will be formatted according to HTML rules. this means you can easily add text decorated in a Swing component. [Read more…] about HTML text on Swing Components Java Example

TextListener Java Swing Example

By Dinesh Thakur

The java.awt.event.TextListener interface allows to react to changes the text contained in components of type TextField and TextArea. The addTextListener () method enables a text component to generate user events. the method TextValueChanged () receives events.

Its interface requires that the method be implemented textValueChanged whose associated event, java.awt.event.TextEvent, has a specific method interest listed below:

Method

Description

toString()

Returns the string associated with the event.

 

import java.awt.*; 
import java.awt.event.*;
class JavaExampleTextEvent extends Frame implements TextListener
{
  TextField Txt;
  public JavaExampleTextEvent()
    {
      createAndShowGUI();
    }
      private void createAndShowGUI()
        {
          setTitle("Example of Text Listener");
          setLayout(new FlowLayout());
          Txt=new TextField(20);
          Txt.addTextListener(this);
          add(Txt);
          setSize(400,400);
          setVisible(true);
        }
          public void textValueChanged(TextEvent Evnt)
          {
             setTitle(Txt.getText());
          }
             public static void main(String aa[])
             {
                new JavaExampleTextEvent();
             }
 }

TextListener

JSpinner Java Swing Example

By Dinesh Thakur

JSpinner: Selects a value from a range of possible options to Like the drop-down lists, but show no such list. values changed by pressing the scroll buttons. You can also enter a  value directly.

import java.awt.BorderLayout; 
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class JavaExampleSpinner extends JFrame implements ChangeListener
  {
    JLabel LblQty;
    JLabel LblDt;
    JSpinner Spnr;
    JSpinner DateSpnr;
    JavaExampleSpinner(String Tytl)
     {
       setTitle(Tytl);
       setSize(500,200);
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       Container Cntnr=getContentPane();
       Cntnr.setLayout(new GridLayout(2,1));
       JPanel Pnl=new JPanel();
       Pnl.setLayout(new GridLayout(2,2));
       Pnl.setBorder(BorderFactory.createTitledBorder("Sale Entry"));
       SpinnerNumberModel SpnrNmbrMdl=new SpinnerNumberModel(10,1,100,1);
       Spnr=new JSpinner(SpnrNmbrMdl);
       Spnr.addChangeListener(this);
       Pnl.add(new JLabel("Select Quantity to Be Sold:"));
       Pnl.add(Spnr);
       Date Dt=new Date();
       SpinnerDateModel SpnrDtMdl=new SpinnerDateModel(Dt,null,null,Calendar.DATE);
       DateSpnr=new JSpinner(SpnrDtMdl);
       DateSpnr.setEditor(new JSpinner.DateEditor(DateSpnr,"dd:MM:yyyy"));
       DateSpnr.addChangeListener(this);
       Pnl.add(new JLabel("Select Sale Date:"));
       Pnl.add(DateSpnr);
       Cntnr.add(Pnl,BorderLayout.CENTER);
       JPanel Panl=new JPanel();
       Panl.setLayout(new FlowLayout());
       LblQty=new JLabel();
       LblQty.setForeground(Color.GREEN);
       LblDt=new JLabel();
       LblDt.setForeground(Color.RED);
       Panl.add(LblQty);
       Panl.add(LblDt);
       Panl.setBorder(BorderFactory.createTitledBorder("Information"));
       Cntnr.add(Panl); 
       setVisible(true);
     }
       public void stateChanged(ChangeEvent ee)
        {
           JSpinner JSpnr=(JSpinner)ee.getSource();
           try
            {
               JSpnr.commitEdit();
            }
              catch(ParseException PrsEx){}
              if(JSpnr==Spnr)
              LblQty.setText("Quantity:"+JSpnr.getValue().toString());
              else if(JSpnr==DateSpnr)
              LblDt.setText("Date:"+JSpnr.getValue().toString());
        }
              public static void main(String[] aa)
            {
                   new JavaExampleSpinner("Example Date Spinner In Java");
                }
 }

JSpinner

JSlider in Java Example

By Dinesh Thakur

Slider in Swing is similar to scroll bar which allows the user to select a numeric value from a specified range of integer values. It has a knob which can slide on a range of values and can be used to select a particular value. For example, sliders are used in media players, to adjust volume, to set channel frequency, etc. Like scroll bars, they can also be horizontal or vertical. A slider is an object of class JSlider which is direct subclass of JComponent. The class JSlider also implements the interface SwingConstants.

      Constructors and methods of the JSlider class

 

Constructors and Methods

Description

JSlider()

Constructs a horizontal slider with the range 0 to 100with the initial value set to 50.

JSlider(BoundedRangeModelbrm)

Constructs a horizontal slider with the specified bounded range model.

JSlider(int orientation)

Constructs a slider with the range 0 to 100. and the initial value is set to 50, with the specified orientation.

JSlider(int min, int max)

Constructs a horizontal slider having the range whose minimum value is specified by the first parameter and maximum value is specified by the second parameter, and

the initial value is set to 50.

JSlider(int min, int max, int value)

Constructs a horizontal slider having the range whose minimum value is specified by the first parameter, maximum value specified by the second parameter and whose initial value is set according to the last parameter.

JSlider(int orientation, int min, int max, int value)

Constructs a slider with the specified orientation having the range whose minimum and maximum values are specified by the second and third parameters, and the initial value is set accordingly depending on last parameter.

Void addChangeListener(ChangeListener I)

Adds a change listener to this slider.

int getMaximum()

Returns the maximum value the slider supports.

int getMinimum()

Returns the minimum value the slider supports.

int getOrientation()

Returns the slider’s horizontal or vertical orientation.

int getValue()

Returns the slider’s current value.

Void setValue(int value)

Sets the slider’s current value to the value specified by the parameter.

 

The creation and display of the JSlider control is explained in Program.

import javax.swing.*; 
import javax.swing.event.*;
import java.awt.*;
public class JavaExampleDynamicIcon
  {
    public static void main(String[] as)
      {
          final JSlider Wdth = new JSlider(JSlider.HORIZONTAL, 1, 150, 75);
          final JSlider Hght = new JSlider(JSlider.VERTICAL, 1, 150, 75);
          class DynamicIcon implements Icon
            {
                public int getIconWidth()
              {
                  return Wdth.getValue();
              }
                     public int getIconHeight()
                   {
                       return Hght.getValue();
                   }
                          public void paintIcon(Component Cmpnt, Graphics gr, int a, int b)
                       {
                              gr.fill3DRect(a, b, getIconWidth(), getIconHeight(), true);
                           }
            };
                  Icon Icn = new DynamicIcon();
                 final JLabel LblDynmc = new JLabel(Icn);
                 class Updater implements ChangeListener
                {
                        public void stateChanged(ChangeEvent Evnt)
                      {
                              LblDynmc.repaint();
                          }
                    };
                             Updater Updtr = new Updater();
                             Wdth.addChangeListener(Updtr);
                             Hght.addChangeListener(Updtr);
                             JFrame Frm = new JFrame();
                             Container Cntnr = Frm.getContentPane();
                             Cntnr.setLayout(new BorderLayout());
                             Cntnr.add(Wdth, BorderLayout.NORTH);
                             Cntnr.add(Hght, BorderLayout.WEST);
                             Cntnr.add(LblDynmc, BorderLayout.CENTER);
                             Frm.setSize(210,210);
                             Frm.setVisible(true);
        }
  }

JSlider

KeyEvent Java Example

By Dinesh Thakur

The java.awt.event.KeyListener interface, present in virtually all AWT component is used to respond to events triggered by  keystrokes when the focus is on the component. Allows the preprocessing  the input provided by the user and other sophisticated actions. its  interface requires the keyPressed, keyReleased method are implemented and  keyTyped. The associated event, java.awt.event.KeyEvent has the following methods  of particular interest are listed below:

 

Method

Description

getKeyChar()

Returns the characterassociated with thekeythat originated theevent.

getKeyCode()

Returns thekey codeassociated withthatkeyoriginated the event.

getKeyModifiersText(int)

Returnsa string describingthe modifier keys“Shift”, “Ctrl” ortheir combination.

getKeyText(int)

Returnsa string describingthe keyas“Home“, “F1″ or “A”.

isActionKey()

Determines whetheror notthe associated keyis akeyaction.

setKeyChar(char)

Replaces the characterassociated with thekeythat originated theevent.

 

import javax.swing.*; 
import java.awt.*;
import java.awt.event.*;
public class JavaExampleKeyEvent extends JFrame implements KeyListener
  {
    private JLabel LblPrmpt = new JLabel("Press keys as Desired Below:");
    private JLabel LblOutPt = new JLabel("Key Typed is:");
    private JTextField Txt = new JTextField(10);
    public JavaExampleKeyEvent()
     {
       setTitle("Java Example of Key Event");
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       setLayout(new BorderLayout());
       add(LblPrmpt,BorderLayout.NORTH);
       add(Txt, BorderLayout.CENTER);
       add(LblOutPt,BorderLayout.SOUTH);
       addKeyListener(this);
       Txt.addKeyListener(this);
     }
       public void keyTyped(KeyEvent Evnt)
        {
          char s = Evnt.getKeyChar();
          LblOutPt.setText("Last key Pressed:" + s);
        }
          public void keyPressed(KeyEvent Evnt)
           {
           }
             public void keyReleased(KeyEvent Evnt)
             {
             }
               public static void main(String[] ar)
                {
                  JavaExampleKeyEvent Frm = new JavaExampleKeyEvent();
                  final int WIDTH = 250;
                  final int HEIGHT = 100;
                  Frm.setSize(300,300);
                  Frm.setVisible(true);
                }
  }

KeyEvent

ItemListener Java Example

By Dinesh Thakur

The java.awt.event.ItemListener interface is responsible for processing events  java.awt.event.ItemEvent action generated by the activation of checkboxes (Checkbox), option buttons (CheckboxGroup) and items in menus option type  (CheckboxMenuItem). Its implementation requires the inclusion of the method  itemStateChanged these classes.

Method

Description

getItem()

Returns the itemthat triggered theevent.

getStateChange()

Returns thetype ofstate changeoccurred.

import java.awt.*; 
import javax.swing.*;
import java.awt.event.*;
public class JavaExampleCheckBox extends JFrame implements ItemListener
{
    FlowLayout Flw = new FlowLayout();
    JLabel LblChc = new JLabel("What would you like to Choose?");
    JCheckBox Cappuccino = new JCheckBox("Coffee", false);
    JCheckBox SoftDrink = new JCheckBox("Pepsi", false);
    JCheckBox Mlk = new JCheckBox("Milk", false);
    JCheckBox Wtr = new JCheckBox("Water", false);
    String Outpt,InsChsn;
    public JavaExampleCheckBox()
     {
       super("Java Example Of Check Box Function");
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       setLayout(new FlowLayout());
       LblChc.setFont(new Font("Times New Roman", Font.ITALIC, 22));
       Cappuccino.addItemListener(this);
       SoftDrink.addItemListener(this);
       Mlk.addItemListener(this);
       Wtr.addItemListener(this);
       add(LblChc);
       add(Cappuccino);
       add(SoftDrink);
       add(Mlk);
       add(Wtr);
     }
           public void itemStateChanged(ItemEvent Chk){}
            public static void main(String[] aa)
            {
              final int FRAME_WIDTH = 330;
              final int FRAME_HEIGHT = 110;
              JavaExampleCheckBox Frm =new JavaExampleCheckBox();
              Frm.setSize(FRAME_WIDTH, FRAME_HEIGHT);
              Frm.setVisible(true);
            }
}

ItemListener

java.awt.event.ActionListener Java Example

By Dinesh Thakur

The java.awt.event.ActionListener interface is responsible for processing events java.awt.event.ActionEvent action generated by the drive buttons (Button), selection items (MenuItem) in suspended (drop-down) or independent menus (popup) at Pressing the “Enter” in inboxes (TextField) and double-click boxes list (List). Its implementation requires the inclusion of the actionPerformed method in these classes.

As a complement, the ActionEvent event has the following specific methods associated with:

 

Method

Description

getActionCommand()

Returns the string associated with this component

getModifiers()

Obtain the modifiers used in the instant the generation of this event.

 

import javax.swing.*; 
import java.awt.*;
import java.awt.event.*;
public class JavaExampleHello2JApplet extends JApplet implements ActionListener
 {
   JLabel LblGrtng = new JLabel("Hi Welcome...!Who are you?");
   Font FntOne = new Font("Times New Roman", Font.BOLD, 36);
   Font FntTwo = new Font("Times New Roman", Font.ITALIC, 48);
   JTextField TxtAns = new JTextField(10);
   JButton BtnClck = new JButton("Click Here");
   JLabel LblPrsnlGrtng = new JLabel(" ");
   Container Cntnr = getContentPane();
   public void init()
    {
      LblGrtng.setFont(FntOne);
      LblPrsnlGrtng.setFont(FntTwo);
      Cntnr.add(LblGrtng);
      Cntnr.add(TxtAns);
      Cntnr.add(BtnClck);
      Cntnr.setLayout(new FlowLayout());
      Cntnr.setBackground(Color.CYAN);
      BtnClck.addActionListener(this);
      TxtAns.addActionListener(this);
    }
      public void actionPerformed(ActionEvent ee)
      {
        String Nme = TxtAns.getText();
        Cntnr.remove(LblGrtng);
        Cntnr.remove(BtnClck);
        Cntnr.remove(TxtAns);
        LblPrsnlGrtng.setText("Hello, " + Nme + "! ");
        Cntnr.add(LblPrsnlGrtng);
        Cntnr.setBackground(Color.WHITE);
        validate();
      }
}
/*<applet code= JavaExampleHello2JApplet.class Height=300 width=240></applet>*/

java.awt.event.ActionListener

JoptionPane Java Example

By Dinesh Thakur

JOptionPane is a subclass of JComponent which includes static methods for creating and customizing modal dialog boxes using a simple code. Previously, you have seen that creating a dialog box using JDialog makes the code cumbersome. So JOptionPane is used instead of JDialog to minimize the complexity of the code. JOptionPane displays the dialog boxes with one of the four standard icons (question, information, warning, and error) or the custom icons specified by the user.

Some of the constructors defined by the JOptionPane class are as follows.

JOptionPane ()

JOptionPane(Object message)

JOptionPane(Object message, int messageType)

JOptionPane(Object message, int messageType, int optionType)

JOPtionPane (Object message, int messageType, int optionType, Icon icon)

JOPtionPane (Object message, int messageType, int optionType, Icon icon, Object[] options)

JOPtionPane (Object message, int messageType, int optionType, Icon icon, Object[] options, Object initialValue)

where,

message is the message to be displayed in the dialog box

messageType specifies the type of the message to be displayed. It has various values which are represented as: ERROR_MESSAGE, INFORMATION_MESSAGE,WARNING_MESSAGE, QUESTION_MESSAGE or PLAIN_MESSAGE

optionType is used to specify the options. It can have various values which are represented as: DEFAULT_OPTION, YES_NO_OPTION, YES_NO_CANCEL_OPTION or OK_CANCEL_OPTION icon specifies the icon to be displayed

options is an array of options to be displayed in the dialog box with none of them selected

initialValue specifies the default option selected from the list provided in options

JOptionPane class is used to display four types of dialog boxes namely, 

● MessageDialog – dialog box that displays a message making it possible to add icons to alert the user.
● ConfirmDialog – dialog box that besides sending a message, enables the user to answer a question.
● InputDialog – dialog box that besides sending a message, allows entry of a text.
● OptionDialog – dialog box that covers the three previous types.

import javax.swing.JOptionPane; 
public class JavaExampleOptionPaneSalaryDialog
  {
    public static void main(String[] aa)
     {
       String StrngWg, StrngDpndnt;
       double Salary,WklyPay;
       int Dpndnts;
       final double HOURS_IN_WEEK = 37.5;
       StrngWg = JOptionPane.showInputDialog(null,"Enter Worker's Hourly Wage", "First Salary Dialog",JOptionPane.INFORMATION_MESSAGE);
       WklyPay = Double.parseDouble(StrngWg) *HOURS_IN_WEEK;StrngDpndnt = JOptionPane.showInputDialog(null,"How many Dependents?", "Second Salary Dialog
",JOptionPane.QUESTION_MESSAGE);
       Dpndnts = Integer.parseInt(StrngDpndnt);
       JOptionPane.showMessageDialog(null,"Weekly Pay is $" +WklyPay+ "\nDeductions will be made for :" +Dpndnts+ "Dependents");
     }
  }

JoptionPane

showOptionDialog Java Example

By Dinesh Thakur

The option dialog box provides the feature of all the above three discussed dialog boxes. It is created by using the static method showOptionDialog () of JOptionPane. The general form of showOptionDialog () method is

public static int showOptionDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon, Object[] options, Object initialValue))

where,

parentComponent is the frame in which the dialog box is displayed

message is the message to be displayed

title is a string of text to be displayed in the title bar of the dialog box

optionType specifies options available on the dialog box such as YES_NO_OPTION or YES_NO_CANCEL_OPTION

messageType specifies the type of message such as error message, information message, warning message, question message or plain message

icon specifies the icon on the dialog box

options allows the user to use components other than buttons

initialValue determines the initial choice

import java.util.*; 
import javax.swing.*;
public class JavaExampleAgeCalculator
  {
    public static void main(String[] as)
     {      
               GregorianCalendar Current = new GregorianCalendar();
       int CrntYear;
       int YearofBrth;
       int YrsOld;
       YearofBrth = Integer.parseInt(JOptionPane.showInputDialog(null,"In Which year You Were born?"));
       CrntYear = Current.get(GregorianCalendar.YEAR);
       YrsOld = CrntYear - YearofBrth;JOptionPane.showMessageDialog(null,"At Present year you become " + YrsOld +" Years Old");
     }
  }

showOptionDialog

What is the default initialization of an array in Java?

By Dinesh Thakur

Before using the element of an array, it must have an initial value. In some programming languages ​​do not set initial values default, and then when trying to access to an item an error occurs. In Java, all the variables, including the elements array have initial default value (default initial value). This default initial value is equal to 0 in numeric types or equivalent types (eg null for objects and false for boolean).

Of course, the initial values ​​can be set explicitly. this can take place in different ways. A is possible through the use of literal expression for the elements of the array (array literal expression):
int[] myArray = {1, 2, 3, 4, 5, 6};
In this case, create and initialize the array simultaneously. Here’s how look in the memory array, then its values ​​are initialized yet at the time of declaration:
In this syntax brackets replace the new operator and between has listed the initial value of the array, separated by commas. Their number determines its length.

Declaring and initializing the array – an example

Here’s another example of declaring and initializing immediately array:

String[] daysOfWeek = { “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday” };

In this case, the array is allocated with 7 elements of type String. Type String is reference type (object) and its values ​​are stored in the dynamic memory.

Stack is allocated variable daysOfWeek, which points to stretch in dynamic memory that contains the elements of the array. Each of the 7 elements is an object of type string that itself points to another area of dynamic memory, which keeps its value.

Declaring and Allocating Arrays in Java

By Dinesh Thakur

In Java arrays have a fixed length that is specified during initialization, and determines the number of its elements. Once we set the length of the array is not possible to change it.

Declaring an array
Arrays in Java declare as follows:

int[] myArray;

Here the variable myArray is the name of the array, which is of type (int []) ie We declare an array of integers. With [] indicates that the variable that will declare an array rather than a single element.
In return the name of the variable which is of type array is a reference (reference), which points to null, as it is not yet memory allocated for the array elements.
Here is how a variable of type array that is declared, but has not allocate memory for array elements:

Creation (allocation) array – operator new

In Java, an array is created with the keyword new, which serves to allocate (allocating) memory:

int[] myArray = new int[6];

In the example, allocate an array of size 6 elements of an integer. this means that dynamic memory (heap) dedicates a section of 6-then consecutive integers. Elements of arrays are always stored in dynamic memory (in the so-called heap).

To allocate array in brackets set the number of its elements (nonnegative integer) and so its length is fixed. The type of elements to write after new, to indicate which type elements must allocate memory. Array already set length may change i.e. Arrays are fixed length.

Type Conversion in Java Example

By Dinesh Thakur

Java has a wide variety of data types from which we can choose the suitable for a particular purpose. To operate on variables from two different types of data we have to convert Both types to the same. [Read more…] about Type Conversion in Java Example

Compound Assignment Operators in Java Example

By Dinesh Thakur

Besides the assignment operator in Java has combined operators assignment. They contribute to reducing the amount of code as impracticable two operations by an operator. The combined operators have the following syntax:

operand1 operator = operand2 ;

The above expression is identical to the following :

operanda1 = operanda1 operator operanda2 ;

Here is an example of a combined assignment operator :

int x = 2 ;

int y = 4 ;

x * = y; / / Same as x = x * y;

System.out.println (x); / / 8

The most commonly used compound assignment operators are + = (value added operand2 to operand1) – = ( subtract the value of operand right by the value of the first on the left ) . Other composite operators assignment are * = , / = and % = . The following example gives a good idea of ​​the combined operators assignment and their use:

int x = 6 ;

int y = 4 ;

System.out.println (y * = 2 ); / / 8

int z = y = 3 ; / / y = 3 and z = 3

System.out.println (z); / / 3

System.out.println (x | = 1 ); / / 7

System.out.println (x + = 3 ); / / 10

System.out.println (x / = 2 );/ / 5

In the example, first create the variables x and y and we appropriate them values ​​6 and 4. On the next line print the bracket y, then we assign a new value to the operator * = 2 and literal. The result of the operation is 8. Further, in the example apply other compound assignment operators and earn the result of Console.

Comparison Operators in Java Example

By Dinesh Thakur

In this example we reviewed six comparison operator <, <=,>,> =, == And ! =. Comparison operators always produce a boolean result value (true or false). Java has several comparison operator, which can be used for the comparison of any combination of integers, with float or symbols.

Operator

Action

==

equal

! =

Not

> 

Greater

> =

Greater than or equal

< 

Less

<=

Less than or equal

 

In this sample Comparison Operators Example, first created two variables a and b and their appropriated values ​​100 and 50 . The next line printed on the console rules by the method println () to System.out, the result of the comparison of the two variables a and b by the operator > . The returned result is true, because a has a larger value of b. On the next 50 order prints the returned result from the use of the remaining 50 comparison operator with variables a and b.

Here’s a sample program that demonstrates the use of operators for comparison in Java:

public class ComparisonOperators 

{

     public static void main(String args[])

    {

          int a = 100, b = 50;

          System.out.println(“a > b : ” + (a > b)); // true

          System.out.println(“a < b : ” + (a < b)); // false

          System.out.println(“a >= b : ” + (a >= b)); // true

          System.out.println(“a <= b : ” + (a <= b)); // false

          System.out.println(“a == b : ” + (a == b)); // false

          System.out.println(“a != b : ” + (a != b)); // true

    }

}

TextAttribute Java Example

By Dinesh Thakur

The variable map is which allows you to assign design attributes of the object type source AttributedString. Through this variable may change any aspect of the font . TextAttribute example shown the code as follows:

import java.applet.Applet; 
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.*;
import java.awt.image.*;
import java.awt.Shape;
import java.awt.font.*;
import java.text.*;
import javax.swing.*;
public class DrawTextAttributeExample extends Applet {
public static void main(String[] args) {
Frame DrawTextAttribute  = new Frame("Draw TextAttribute  Example");
DrawTextAttribute .setSize(350, 250);
Applet DrawTextAttributeExample = new DrawTextAttributeExample();
DrawTextAttribute .add(DrawTextAttributeExample);
DrawTextAttribute .setVisible(true);
DrawTextAttribute .addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
      }
    });
  }
  public void paint(Graphics g) {
    g.setColor(Color.blue);
    g.setFont(new Font("Arial",Font.BOLD,14));
    g.drawString("TextAttribute in Java Example", 50, 40);
    g.setFont(new Font("Arial",Font.BOLD,10));
    g.drawString("http://ecomputernotes.com", 200, 205);
                Graphics2D G2D = (Graphics2D)g;
                G2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
                G2D.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
                G2D.setColor(Color.blue);
                String str = "Dinesh Thakur";
                AttributedString AttributedStr = new AttributedString (str);
                Font font = new Font("Arial", Font.ITALIC, 15);
                AttributedStr.addAttribute(TextAttribute.FONT,font,0,str.length()-2);
                Image image = (new ImageIcon("DineshThakur.jpg")).getImage();
                ImageGraphicAttribute ImageGA = new ImageGraphicAttribute (image,(int)CENTER_ALIGNMENT);
                AttributedStr.addAttribute(TextAttribute.CHAR_REPLACEMENT,ImageGA,1,2);
                AttributedStr.addAttribute(TextAttribute.CHAR_REPLACEMENT,ImageGA,8,9);
                font = new Font("Times", Font.ITALIC, 24);
                AttributedStr.addAttribute(TextAttribute.FONT,font,3,9);
                AttributedCharacterIterator AttributedCI = AttributedStr.getIterator();
                FontRenderContext FontRC = G2D.getFontRenderContext();
               TextLayout TextLay = new TextLayout(AttributedCI,FontRC);
               TextLay.draw(G2D, 80, 70);
  }
}

TextAttribute Java Example

Filling a clipping path with different objects Java Example

By Dinesh Thakur

This code can be seen as built a clipping path with the text area of the word ” Dinesh Thakur ” located in the middle of the window. In the drawn area can be seen as the image is painted behind the chain. As seen, the effect is very colorful and easy to perform.

 

import java.applet.Applet; 
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.*;
import java.awt.image.*;
import java.awt.Shape;
import java.awt.font.*;
public class DrawClippingPathExample extends Applet {
public static void main(String[] args) {
Frame DrawClippingPath  = new Frame("Draw ClippingPath  Example");
DrawClippingPath .setSize(350, 250);
Applet DrawClippingPathExample = new DrawClippingPathExample();
DrawClippingPath .add(DrawClippingPathExample);
DrawClippingPath .setVisible(true);
DrawClippingPath .addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
      }
    });
  }
  public void paint(Graphics g) {
    g.setColor(Color.blue);
    g.setFont(new Font("Arial",Font.BOLD,14));
    g.drawString("Filling a Clipping Path in Java Example", 50, 40);
    g.setFont(new Font("Arial",Font.BOLD,10));
    g.drawString("http://ecomputernotes.com", 200, 205);
                Graphics2D G2D = (Graphics2D)g;
                int w = getSize().width;
                int h = getSize().height;
               FontRenderContext FontRC = G2D.getFontRenderContext();
               Font font = new Font("Times",Font.BOLD,w/15);
               String str = new String ("Dinesh Thakur");
               TextLayout TextLay = new TextLayout(str,font,FontRC);
               float sw = (float)TextLay.getBounds().getWidth();
               AffineTransform AffineTrans = new AffineTransform();
               AffineTrans.setToTranslation(w/2-sw/2,h/1.5);
               Shape shp = TextLay.getOutline(AffineTrans);
               G2D.setClip(shp);
               G2D.setColor(Color.red);
               G2D.fill(shp.getBounds2D());
               G2D.setColor(Color.white);
               G2D.setStroke(new BasicStroke(2.0f));
               for ( double j = shp.getBounds().getY();
               j<shp.getBounds2D().getY()+shp.getBounds2D().getHeight();
               j=j+4) {
              Line2D L2D = new Line2D.Double(0.0,j,w,j);
              G2D.draw(L2D);
              }
  }
}

Filling a clipping path with different objects

Text Effect in Java Example

By Dinesh Thakur

This code can be seen as built a clipping path with the content of the text area of the word “Java ” located in the middle of the window.In the drawn area can be seen as the image is painted behind the chain. As seen, the effect is very colorful and easy to perform.

import java.applet.Applet; 
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.*;
import java.awt.image.*;
import java.awt.Shape;
import javax.swing.*;
public class DrawTextEffectExample extends Applet {
public static void main(String[] args) {
Frame DrawTextEffect  = new Frame("Draw TextEffect  Example");
DrawTextEffect .setSize(350, 250);
Applet DrawTextEffectExample = new DrawTextEffectExample();
DrawTextEffect .add(DrawTextEffectExample);
DrawTextEffect .setVisible(true);
DrawTextEffect .addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
      }
    });
  }
  public void paint(Graphics g) {
    g.setColor(Color.blue);
    g.setFont(new Font("Arial",Font.BOLD,14));
    g.drawString("Text Effect in Java Example", 50, 40);
    g.setFont(new Font("Arial",Font.BOLD,10));
    g.drawString("http://ecomputernotes.com", 200, 205);
                Graphics2D G2D = (Graphics2D)g;
                int w = getSize().width;
                int h = getSize().height;
                Image image = (new ImageIcon("Canada.jpg")).getImage();
                FontRenderContext FontRC = G2D.getFontRenderContext();
                Font font = new Font("Times",Font.BOLD,100);
                TextLayout TextLay = new TextLayout("Java",font,FontRC);
                float sw = (float)TextLay.getBounds().getWidth();
                AffineTransform AffineTran = new AffineTransform();
                AffineTran.setToTranslation(w/2-sw/2,h*5/8);
                Shape s = TextLay.getOutline(AffineTran);
               G2D.setClip(s);
               G2D.drawImage(image,50,60,this);
               G2D.setColor(Color.green);
               G2D.draw(s);
  }
}

Text Effect in Java Example

How to draw text on an image Java Example

By Dinesh Thakur

With this code we will study how text is drawn on a any image.

import java.applet.Applet; 
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.*;
import java.awt.image.*;
import java.awt.Shape;
import javax.swing.*;
public class DrawTextonImageExample extends Applet {
public static void main(String[] args) {
Frame DrawTextonImage = new Frame("Draw TextonImage Example");
DrawTextonImage.setSize(350, 250);
Applet DrawTextonImageExample = new DrawTextonImageExample();
DrawTextonImage.add(DrawTextonImageExample);
DrawTextonImage.setVisible(true);
DrawTextonImage.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
      }
    });
  }
  public void paint(Graphics g) {
    g.setColor(Color.blue);
    g.setFont(new Font("Arial",Font.BOLD,14));
    g.drawString("Draw text on an Image Java Example", 50, 40);
    g.setFont(new Font("Arial",Font.BOLD,10));
    g.drawString("http://ecomputernotes.com", 200, 205);
                Graphics2D G2D = (Graphics2D)g;
                int w = getSize().width;
                int h = getSize().height;
                Image image = (new ImageIcon("DineshThakur.jpg")).getImage();
                G2D.drawImage(image,140,80,this);
                FontRenderContext FontRC = G2D.getFontRenderContext();
                Font font = new Font("Times",Font.BOLD,w/25);
                String str = new String ("Dinesh Thakur");
                TextLayout TextL = new TextLayout(str,font,FontRC);
                float sw = (float)TextL.getBounds().getWidth();
                AffineTransform AffineTran = new AffineTransform();
                AffineTran.setToTranslation(w/2-sw/2,h*3/8);
                G2D.setColor(Color.green);
               Shape shape = TextL.getOutline(AffineTran);
               G2D.draw(shape);
               TextL.draw(G2D,w/2-sw/2,h*5/8);
  }
}

How to draw text on an image

« Previous Page
Next Page »

Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW