Powered by Blogger.

Java: Drawing Lines, Rectangles, and Ovals Java Applet Program

Drawing Lines, Rectangles, and Ovals Java Applet:-

Code 4-15 presents a variety if Graphics methods for drawing lines, rectangles, and ovals.

 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;

 public class TestLineRectOval extends JFrame{
   private static final long serialVersionUID=0;

   public TestLineRectOval(){
     super(”Lines Ractangles Ovals”);
     setSize(360, 450);
     show();
   }

   public void paint(Graphics g){
     g.setColor(Color.red);
     g.drawLine(50, 40, 300, 40);

     g.setColor(Color.blue);
     g.drawRect(50 ,60, 100, 60);
     g.fillRect(200, 60, 100, 60);

     g.setColor(Color.cyan);
     g.drawRoundRect(50, 150, 100, 60, 50, 50);
     g.fillRoundRect(200, 150, 100, 60, 50, 50);

     g.setColor(Color.yellow);
     g.draw3DRect(50, 250, 100, 60, true);
     g.fill3DRect(200, 250, 100, 60, true);

     g.setColor(Color.magenta);
     g.drawOval(50, 350, 100, 60);
     g.fillOval(200, 350, 100, 60);
   }

   public static void main(String[]args){
     TestLineRectOval tlro = new TestLineRectOval();
     tlro.addWindowListener(
       new WindowAdapter(){
         public void windowClosing(WindowEvent e){
           System.exit(0);
         }
       }
     );
   }
 }

Code 4-16 provides an password example using Jlabel, JtextField, JpasswordField, and Jbutton.

 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;

 public class Password extends JFrame{
   private static final long serialVersionUID=0;

   private JLabel l1, l2;
   private JTextField t1;
   private JPas swordField pw;
   private JButton b1, b2;

   public Password(){
     super(”Password Example”);
     Container c = getContentPane();
     c.setLayout(new FlowLayout());

     l1 = new JLabel(”Enter User Name”);
     c.add(l1);

     t1 = new JTextField(15);
     c.add(t1);

     l2 = new JLabel(”Enter Password”);
     c.add(l2);

     pw = new JPas swordField(10);
     c.add(pw);

     b1 = new JButton(”Enter”);
     b1.addActionListener(
       new ActionListener(){
         public void actionPerformed(ActionEvent e){
           if(t1.getText().equals(”Parvez”) && pw.getText(). equals (”123456
              JOptionPane.showMessageDialog(null, ”Welcome to Java”);
           }else{
              JOptionPane.showMessageDialog(null, ”Incorrect user name 38
           }
         }
       }
     );
     c.add(b1);

     b2 = new JButton (”Cancel”);
     b2.addActionListener(
       new ActionListener(){
          public void actionPerformed(ActionEvent e){
             String s = ” ”;
             t1.setText(s);
             pw.setText(s);
          }
       }
     );
     c.add(b2);

     setSize(300, 125);
     show();
     }

     public static void main(String[]args){
       Password PW = new Password();
       PW.addWindowListener(
         new WindowAdapter(){
           public void windowClosing(WindowEvent e){
              System.exit(0);
           }
         }
       );
     }
  }


Example of Jcomponents such as: JcheckBox, JradioButton, JcomboBox, Jlist, and JTextArea provided in code 4-17.

 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;

 public class TestJComt extends JFrame{
   private static final long serialVersionUID=0;

   private JCheckBox bold, italic;
   private JRadioButton male, female;
   private ButtonGroup radioGroup;
   private JComboBox cBox;
   private String[]str 1 = {”spring”, ”summer”, ”fall”};
   private JList colorList;
   private String[]str 2 = {”Red”, ”Green”, ”Blue”, ”Black”, ”White”, ”15 ”Orange”, ”Pink”, ”Magenta”, ”Sky”, ”Cyan 16 private JTextArea ta1;

   public TestJComt(){
     super(”Test JComponents”);
     Container c = getContentPane();
     c.setLayout(new FlowLayout());

     bold = new JCheckBox(”Bold”);
     c.add(bold);
     italic = new JCheckBox(”Italic”);
     c.add(italic);

     male = new JRadioButton(”Male”);
     c.add(male);
     female = new JRadioButton(”Female”);
     c.add(female);
     radioGroup = new ButtonGroup();
     radioGroup.add(male);
     radioGroup.add(female);

     cBox = new JComboBox(str 1);
     c.add(cBox);

     colorList = new JList(str 2);
     colorList.setVisibleRowCount(5);
     c.add(new JScrollPane(colorList));

     String s = ”Java is a object oriented programming language”;
     ta1 = new JTextArea(s, 10, 15);
     c.add(new JSc rollPane(ta1));

     setSize(200, 350);
     show();
   }

   public static void main(String[]args){
     TestJComt jc = new TestJComt ();
     jc.addWindowListener(
       new WindowAdapter(){
         public void windowClosing(WindowEvent e){
           System.exit(0);
         }
       }
     );
   }
 }

Using Example:

 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;

 public class OpenFile extends JFrame{
   private static final long serialVersionUID=0;
   private JButton b1;
   private JFileChooser jfc;

   public OpenFile(){
     super(”File Opener”);
     b1 = new JButton(”Open File Chooser”);
     b1.addActionListener(
       new ActionListener(){
          public void actionPer formed( ActionEvent e){
            abc();
          }
       }
     );
     getContentPane().add(b1, BorderLayout.NORTH);
     setSize(300, 200);
     show();
     }

     private void abc(){
       jfc = new JFileChooser();
       jfc.showOpenDialog(this);
     }

     public static void main(String[]args){
       OpenFile of = new OpenFile();
       of.addWindowListener(
          new WindowAdapter(){
              public void windowClosing(WindowEvent e){
                System.exit(0);
              }
          }
       );
     }
  }

Java:~ code for change Font in javaScript Program

Description:

The java.awt.Font class is used to create Font objects to set the font for drawing text, labels, text fields, buttons, etc.

Example:

       JButton b = new JButton("OK");
       b.setFont(new Font("sansserif", Font.BOLD, 32));

Available System Fonts:

For maximum portability, use the generic font names, but you can use any font installed in the system. It is suggested to use a font family name, and create the font from that, but you can also use the fonts directly. You can get an array of all available font family names or all fonts.

 // Font info is obtained from the current graphics environment.

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

//--- Get an array of font names (smaller than the number of fonts)

String[] fontNames = ge.getAvailableFontFamilyNames();

//--- Get an array of fonts.  It's preferable to use the names above.

Font[] allFonts = ge.getAllFonts();

Using Fonts for Graphics:

      Font f;
      f = new Font(String name, int style, int size);    // creates a new font
name is "Serif", "SansSerif", or "Monospaced", or a font on the system. style is Font.PLAIN. Font.BOLD, Font.ITALIC, or Font.BOLD+Font.ITALIC. size is the point size, typically in the range 8-48.

Example:

Font big = new Font("SansSerif", Font.Bold, 48);
. . .
g.setFont(big);
g.drawString("Greetings Earthling");

Fonts in Java:

In Java, Font class manages the font of Strings. The constructor of Font class takes three arguments: the font name, font style, and font size. The font name is any font currently supported by the system where the program is running such as standard Java fonts Monospaced, SansSerif, and Serif. The font style is Font.PLAIN, Font.ITALIC, or Font.BOLD. Font styles can be used in combination such as: Font.ITALIC + Font.BOLD.

Fonts in Java Example:

 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;

 public class TestFonts extends JFrame{
   private static final long serialVersionUID=0;

   public TestFonts(){
     super(”Font Examples”);
     setSize(300, 150);
     show();
   }

   public void paint(Graphics g){
     g.drawString(”Welcome to Java.”, 20, 50);
     g.setColor(Color.red);
     g.setFont(new Font(”Monospaced”, Font.BOLD, 14));
     g.drawString(”Welcome to Java.”, 20, 70);
     g.setColor(Color.blue);
     g.setFont(new Font(”SansSerif”, Font.BOLD +Font. ITALIC, 16));
     g.drawString(”Welcome to Java.”, 20, 90);
   }

   public static void main(String[]args){
     TestFonts tf = new TestFonts();
     tf.addWindowListener(
        new WindowAdapter(){
          public void windowClosing(WindowEvent e){
            System.exit(0);
          }
        }
      ) ;
    }
 }

Code for Change Font of Text in Java:

import java.awt.*;
import java.text.*;
import javax.swing.*;
import java.awt.font.*;

public class ShowColorAndFont extends JPanel {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    String text = "Java is an Object Oriented Programming Language.";
    Dimension dimension = getSize();

    Font font1 = new Font("Book Antiqua", Font.PLAIN, 30);
    Font font2 = new Font("Monotype Corsiva", Font.PLAIN, 30);

    AttributedString attributedString = new AttributedString(text);
    attributedString.addAttribute(TextAttribute.FONT, font1);
    attributedString.addAttribute(TextAttribute.FONT, font2, 1, 4);
   attributedString.addAttribute(TextAttribute.FONT, font2, 6, 7);
   attributedString.addAttribute(TextAttribute.FONT, font2, 9, 10);
   attributedString.addAttribute(TextAttribute.FONT, font2, 12, 17);
   attributedString.addAttribute(TextAttribute.FONT, font2, 19, 26);
   attributedString.addAttribute(TextAttribute.FONT, font2, 28, 38);
   attributedString.addAttribute(TextAttribute.FONT, font2, 40, 47);

  attributedString.addAttribute(TextAttribute.FOREGROUND, Color.red, 0, 1);
  attributedString.addAttribute(TextAttribute.FOREGROUND, Color.red, 5, 6);
  attributedString.addAttribute(TextAttribute.FOREGROUND, Color.red, 8, 9);
  attributedString.addAttribute(TextAttribute.FOREGROUND, Color.red, 11, 12);
  attributedString.addAttribute(TextAttribute.FOREGROUND, Color.red, 18, 19);
  attributedString.addAttribute(TextAttribute.FOREGROUND, Color.red, 27, 28);
  attributedString.addAttribute(TextAttribute.FOREGROUND, Color.red, 39, 40);
  
    g2d.drawString(attributedString.getIterator(), 40, 80);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("Show Color and Font");
    frame.getContentPane().add(new ShowColorAndFont());
    frame.setSize(700, 200);
    frame.show();

  }

Java Program: Using Layout Managers Example

Layout Managers:

In Java programming, the layout manager manages the layout of components in a container, which we can change by calling setLayout() method. The layout manage is responsible for deciding the layout policy and size of each of its container’s child components. The following layout managers are included with the Java programming language:

1. FlowLayout The FlowLayout is the default layout manager of Panel and Applet.
2. BorderLayout The BorderLayout is the default layout manager of Window, Dialog, and Frame.
3. Layout The GridLayout provides flexibility for placing components.
4. CardLayout The CardLayout provides functionality comparable to a primitive tabbed panel.
5. GridBagLayout.

FlowLayout manager uses line-by-line technique to place the components in a container. Each time a line is filled, a new line is started. It does not consider the size of components.

 import java.awt.*;
 import java.awt.event.*;

 public class FlowExample implements WindowListener{
   private Frame f;
   private Button b1, b2, b3;

   public FlowExample(){
     f = new Frame(”FlowLayout”);
     b1 = new Button(”Button 1”);
     b2 = new Button(”Button 2”);
     b3 = new Button(”Button 3”);
   }

   public void launchFrame(){
     f.setLayout(new FlowLayout());
     // f.setLayout(new FlowLayout(FlowLayout.LEFT));
     // f.setLayout(new FlowLayout(FlowLayout.RIGHT));
     // f.setLayout(new FlowLayout(FlowLayout.CENTER));
     // f.setLayout(new FlowLayout(FlowLayout.RIGHT,20,30));
     f.add(b1);
     f.add(b2);
     f.add(b3);
     f.addWindowListener(this);
     f.setSize(250, 150);
     f.setBackground(Color.red);
     f.setVisible(true);
   }

   public void windowClosing(WindowEvent e){
     System.exit(0);
   }

   public void windowOpened(WindowEvent e){}
   public void windowIconified (WindowEvent e){}
   public void windowDeiconified(WindowEvent e){}
   public void windowClosed(WindowEvent e){}
   public void windowActivated(WindowEvent e){}
   public void windowDeactivated(WindowEvent e){}

   public static void main(String[]args){
     FlowExamplefe = new FlowExample();
     fe.launchFrame();
   }
 }

The BorderLayout manager contains five distinct areas: NORTH, SOUTH, EAST, WEST, and CENTER, indicated by BorderLayout.NORTH, and so on:

 import java.awt.*;
 import java.awt.event.*;

 public c lass BorderExample implements WindowListener{
   private Frame f;
   private Button b1, b2, b3, b4, b5;

   public BorderExample(){
     f = new Frame(”FlowLayout”);
     b1 = new Button(”Button 1”);
     b2 = new Button(”Button 2”);
     b3 = new Button(”Button 3”);
     b4 = new Button(”Button 4”);
     b5 = new Button(”Button 5”);
   }

   public void launchFrame(){
     f.add(b1, BorderLayout.NORTH);
     f.add(b2, BorderLayout.SOUTH);
     f.add(b3, BorderLayout.WEST);
     f.add(b4, BorderLayout.EAST);
     f.add( b5,BorderLayout.CENTER);
     f.addWindowListener(this);
     f.setSize(250, 250);
     f.setBackground(Color.red);
     f.setVisible(true);
   }

   public void windowClosing(WindowEvent e){
     System.exit(0);
   }

   public void windowOpened(WindowEvent e){}
   public void windowIconified(WindowEvent e){}
   public void windowDeiconified(WindowEvent e){}
   public void windowClosed(WindowEvent e){}
   public void windowActivated(WindowEvent e){}
   public void windowDeactivated(WindowEvent e){}

   public static void main(String[]args){
     BorderExample be = new BorderExample();
     be.launchFrame();
   }
 }

The GridLayout manager placing components with a number of rows and columns. The following constructor creates a GridLayout with the specified equal size. new GridLayout(int rows, int cols);

 import java.awt.*;
 import java.awt.event.*;

 public class GridExample implements WindowListener{
   private Frame f;
   private Button b1, b2, b3, b4, b5, b6;

   public GridExample(){
     f = new Frame(”FlowLayout”);
     b1 = new Button(”Button 1”);
     b2 = new Button(”Button 2”);
     b3 = new Button(”Button 3”);
     b4 = new Button(”Button 4”);
     b5 = new Button(”Button 5”);
     b6 = new Button(”Button 6”);
   }

   public void launchFrame(){
     f.setLayout(new GridLayout(3,2));
     f.add(b1);
     f.add(b2);
     f.add(b3);
     f.add(b4);
     f.add(b5);
     f.add(b6);
     f.addWindowListener(this);
     f.setSize(300, 300);
     f.setBackground(Color.red);
     f.setVisible(true);
   }

   public void windowClosing(WindowEvent e){
     System.exit(0);
   }

   public void windowOpened(WindowEvent e){}
   public void windowIconified(WindowEvent e){}
   public void windowDeiconified (WindowEvent e){}
   public void windowClosed(WindowEvent e){}
   public void windowActivated(WindowEvent e){}
   public void windowDeactivated(WindowEvent e){}

   public static void main(String[]args){
     GridExample ge = new GridExample() ;
     ge.launchFrame();
   }
 }

About Java: Colors in Java Selector

Description:

The java.awt.Color class is used to create new colors, and predefines a few color constants (see below). Java allows the creation of up to 24 million different colors.

Because our eyes have three kinds of neurons that respond primarily to red, green, and blue, it's possible for computer monitors (and TVs) to create all colors using the RGB system. The RGB system Java uses combines red, green, and blue in amounts represented by a number from 0 to 255. For example, red is (255, 0, 0) -- 255 units of red, no green, and no blue. White is (255, 255, 255) and black is (0,0,0).

Color Constants:

Java originally defined a few color constant names in lowercase, which violated the naming rule of using uppercase for constants. These are best to use since they are available in all versions of Java: Color.black, Color.darkGray, Color.gray, Color.lightGray, Color.white, Color.magenta, Color.red, Color.pink, Color.orange, Color.yellow, Color.green, Color.cyan, Color.blue

Java 1.4 added the proper uppercase names for constants: Color.BLACK, Color.DARK_GRAY, Color.GRAY, Color.LIGHT_GRAY, Color.WHITE, Color.MAGENTA, Color.RED, Color.PINK, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.CYAN, Color.BLUE

Constructor:

Color c = new Color(int red, int green, int blue)

This creates a new color object that is a combination of red, green, and blue. The values of each color must be in the range 0-255.

Don't do anything to a Color:

A Color object is created only to be passed as a parameter. You will never call any Color methods.

Example:

Color c = new Color(255, 255, 240);
this.setBackground(c);

Advanced:

Additional constructors use single packed ints or floating point values. In addition, there is support for the HSB (Hue, Saturation, Brightness) color model and transparency. There is a Color Chooser in Java 2 that lets the user choose a color.   

Colors in Java:

In Java, we can control the colors used for the foreground using setForeground() method and the background using setBackground() method of AWT components. The setForeground() and setBackground() methods take an arguments that is an instance of of java.awt.Color class. We can use the constant colors referred to as Color.red, Color.blue, Color.green, Color.yellow, and so on. We can also construct a specific Color object by specifying the color by a combination of three byte-sized integers (0-255), one for each primary color: red, green, and blue.

Colors in Java Program:

 import java.awt.*;
 import java.awt.event.*;

 public class TestColors implements WindowListener, ActionListener{
private Frame f;
private Button b;

public TestColors(){
f = new Frame(”Frame Title”);
b = new Button(”Change Color”);
b.setActionCommand(”button press”);
}

public void launchFrame(){
b.addActionListener(this);
b.setForeground(Color.red);
b.setBackground(Color.yellow);
f.add(b);
f.addWindowListener(this);
f.setSize(300, 300);
f.setBackground(Color.green);
f.setLayout(new FlowLayout());
f.setVisible(true);
}

public void actionPer formed(ActionEvent e){
int x, y, z;
if(e.getActionCommand()==”button press”){
x = (int) (Math.random()*100);
y = (int) (Math.random()*100);
z = (int) (Math.random()*100);
Color c = new Color(x, y, z);
f.setBackground(c);
}
}

public void windowClosing(WindowEvent e){
System.exit(0);
}

public void windowOpened(WindowEvent e){}
public void windowIconified (WindowEvent e){}
public void windowDeiconified (WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}

public static void main(String[]args){
TestColors tc = new TestColors();
tc.launchFrame();
}
}

Colliding Using Mouse Example

This section covers tasks associated with mouse input:

1. Tracking the Mouse Cursor

2. Drawing Lines with the Mouse

3. Processing a Double Click Message

4. Selecting a Line of Text

5. Using a Mouse Wheel in a Document with Embedded Objects

6. Retrieving the Number of Mouse Wheel Scroll Lines

Mouse Class Definition:

The mouse class inherits from QGraphicsItem. The QGraphicsItem class is the base class for all graphical items in the Graphics View framework, and provides a light-weight foundation for writing your own custom items.

class Mouse : public QGraphicsItem
 {
 public:
     Mouse();

     QRectF boundingRect() const;
     QPainterPath shape() const;
     void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
                QWidget *widget);

 protected:
     void advance(int step);

 private:
     qreal angle;
     qreal speed;
     qreal mouseEyeDirection;
     QColor color;
 };

When writing a custom graphics item, you must implement QGraphicsItem's two pure virtual public functions: boundingRect(), which returns an estimate of the area painted by the item, and paint(), which implements the actual painting. In addition, we reimplement the shape() and advance(). We reimplement shape() to return an accurate shape of our mouse item; the default implementation simply returns the item's bounding rectangle. We reimplement advance() to handle the animation so it all happens on one update.

Mouse Example:

import java.awt.*;
 import java.awt.event.*;

 public class MouseExample implements WindowListener, MouseMotionListene
   private Frame f;
   private TextField tf;

   public MouseExample(){
     f = new Frame(”Mouse Example”);
     tf = new TextField(30);
   }

   public void launchFrame(){
     Label label = new Label(”Click and drag the mouse”);
     f.add(label, BorderLayout.NORTH);
     f.add(tf, BorderLayout.SOUTH);
     f.addMouseMotionListener(this);
     f.addMouseListener(this);
     f.addWindowListener(this);
     f.setSize(300, 200);
     f.setVisible(true);
   }

   public void mouseDragged (MouseEvent e){
     String s = ”Mouse dragged : X= ”+e . getX()+” Y=”+e.getY();
     tf.setText(s);
   }

   public void mouseEntered(MouseEvent e){
     String s = ”The mouse entered”;
     tf.setText(s);
   }

   public void mouseExited (MouseEvent e){
     String s = ”The mouse has left the building”;
     tf.setText(s);
   }

   public void mousePressed(MouseEvent e){}
   public void mouseReleased(MouseEvent e){}
   public void mouseMoved(MouseEvent e){}
   public void mouseClicked(MouseEvent e){}

   public void windowClosing(WindowEvent e){
     System.exit(0);
   }

   public void windowOpened(WindowEvent e){}
   public void windowIconified(WindowEvent e){}
   public void windowDeiconified(WindowEvent e){}
   public void windowClosed(WindowEvent e){}
   public void windowActivated(WindowEvent e){}
   public void windowDeactivated(WindowEvent e){}

   public static void main(String[]args){
     MouseExample me = new MouseExample();
     me.launchFrame();
   }
 }

Java Program: J2SE Event Model in Java

J2SE Event Model:

An event is issued, when the user performs and action at the user interface level like: clicks a mouse or presses a key.

J2SE Event Model Program:

 import java.awt.*;
 import java.awt.event.*;

 public class EventHandle implements WindowListener, ActionListener{
   private Frame f;
   private Button b1, b2, b3;
   private TextField tf;

   public EventHandle(){
     f = new Frame(”Button Handling”);
     b1 = new Button(”YES”);
     b1.setActionCommand(”yes button”);
     b2 = new Button(”NO”);
     b2.setActionCommand (”no button”);
     b3 = new Button (”Clear”);
     b3.setActionCommand (”clear button”);
     tf = new TextField(30);
   }

   public void launchFrame(){
     b1.addActionListener(this);
     b1.setForeground(Color.white);
     b1.setBackground(Color.blue);

     b2.addActionListener(this);
     b2.setForeground(Color.red);
     b2.setBackground(Color.green);

     b3.addActionListener(this);
     b3.setForeground(Color.blue);
     b3.setBackground(Color.yellow);

     tf.setForeground(Color.blue);
     tf.setBackground(Color.white);

     f.setLayout(new FlowLayout());
     f.add(b1);
     f.add(b2);
     f.add(b3);
     f.add(tf);
     f.addWindowListener(this);
     f.setSize(250, 150);
     f.setBackground(Color.red);
     f.setVisible(true);
   }

   public void actionPer formed(ActionEvent e){
     String str;
     if(e.getActionCommand()==” yes button”){
       str = ”You press YES button ”;
       tf.setText(str);
     }
     if(e.getActionCommand()==”no button”){
       str = ”You press NO button”;
       tf.setText(str);
     }
     if(e.getActionCommand()==” clear button”){
       str = ” ”;
       tf.setText(str);
     }
   }

   public void windowClosing(WindowEvent e){
    System.exit(0);
   }

   public void windowOpened(WindowEvent e){}
   public void windowIconified(WindowEvent e){}
   public void windowDeiconified(WindowEvent e){}
   public void windowClosed(WindowEvent e){}
   public void windowActivated(WindowEvent e){}
   public void windowDeactivated(WindowEvent e){}

   public static void main(String[]args){
     EventHandle eh = new EventHandle();
     eh.launchFrame();
   }
 }

Java-Using Abstract Windowing Toolkit (AWT) In Java Applications

Abstract Window Toolkit:

AWT is the basic GUI (Graphics User Interface) used for Java applications and applets. Every GUI component that appears on the screen is a subclass of the abstract class Component or Menu Component. The class Container is an abstract subclass of Component class, which permits other components to be nested inside it. There are two types of containers: Window and Panel. A Window is a free-standing native window on the display that is independent of other containers. There are two important types of Window containers: Frame and Dialog. A Frame is a window with a title and corners that you can resize. A Dialog is a simple window and cannot have a menu bar, you cannot resize it, but you can move it. A Panel must be contained within another Container, or inside a web browser’s window.

Abstract Window Toolkit Example_1:

 import java.awt.*;
 import java.awt.event.*;

 public class FrameWithPanel implements WindowListener{
    private Frame f;
    private Panel p;

    public FrameWithPanel(){
       f = new Frame(”Frame Title”);
       p = new Panel();
    }

    public void launchFrame(){
       f.addWindowListener(this);
       f.setSize(400, 400);
       f.setBackground(Color.red);
       f.setLayout(null);

       p.setSize(150, 150);
       p.setBackground(Color.green);
       f.add(p);
       f.setVisible(true);
   }

   public void windowClosing(WindowEvent e){
      System.exit(0);
   }

   public void windowOpened(WindowEvent e){}
   public void windowIconified(WindowEvent e){}
   public void windowDeiconified(WindowEvent e){}
   public void windowClosed(WindowEvent e){}
   public void windowActivated(WindowEvent e){}
   public void windowDeactivated(WindowEvent e){}

   public static void main(String[]args){
      FrameWithPanel fp = new FrameWithPanel();
      fp.launchFrame();
   }
 }

Example 2:

 import java.awt.*;
 import java.awt.event.*;

 public class TestMenuBar implements WindowListener, ActionListener{
    private Frame f;
    private MenuBar mb;
    private Menu m1, m2, m3;
    private MenuItem mi1, mi2, mi3, mi4;

    public TestMenuBar(){
       f = new Frame(”MenuBar Example”);
       mb = new MenuBar();
       m1 = new Menu(”File”);
       m2 = new Menu(”Edit”);
       m3 = new Menu(”Help”);
       mi1 = new MenuItem(”New”);
       mi2 = new MenuItem(”Save”);
       mi3 = new MenuItem(”Load”);
       mi4 = new MenuItem(”Quit”);
   }

   public void launchFrame(){
      mi4.addActionListener(this);
      m1.add(mi1);
      m1.add(mi2);
      m1.add(mi3);
      m1.addSeparator();
      m1.add(mi4);

      mb.add(m1);
      mb.add(m2);
      mb.setHelpMenu(m3);
      f.setMenuBar(mb);

      f.addWindowListener(this);
      f.setSize(400, 400);
      f.setBackground(Color.red);
      f.setLayout(null);
      f.setVisible(true);
   }

   public void actionPerformed(ActionEvent e){
      System.exit(0);
   }

   public void windowClosing(WindowEvent e){
      System.exit(0);
   }

   public void windowOpened(WindowEvent e){}
   public void windowIconified(WindowEvent e){}
   public void windowDeiconi fied(WindowEvent e){}
   public void windowClosed(WindowEvent e){}
   public void windowActivated(WindowEvent e){}
   public void windowDeactivated(WindowEvent e){}

   public static void main(String[]args){
      TestMenuBar tmb = new TestMenuBar();
      tmb.launchFrame();
   }
 }


References:

1. Fowler, Amy (1994). "Mixing heavy and light components". Sun Microsystems. Retrieved 17 December 2008.

2. Geertjan, Wielenga (16 December 2008). "A Farewell to Heavyweight/Lightweight Conflicts". Retrieved 17 December 2008.

3. "Bug/RFE fixed in current JDK 6u12 build". Sun Micro systems. 12 December 2008. Retrieved 17 December 2008.

4. Torre, Mario (2 March 2008). "FINAL PROPOSAL: Portable GUI backends". Retrieved 7 September 2008.

5. Kennke, Roman (18 December 2008). "Caciocavallo Architecture Overview". Retrieved 7 September 2008.

6. Kennke, Roman (3 September 2008). "Cacio Swing AWT peers". Retrieved 7 September 2008.

7. "How much has been pushed upstream?". openjdk.java.net. 20 September 2009. Retrieved 7 March 2010. "You don't need anymore those patches, with the latest FontManager push, everything is upstream now, so just use the Cacio repo, it's completely self contained."

8. a b Kennke, Roman (28 July 2011). "JDK7 and Cacio coolness". Retrieved 8 August 2011.

9. Eisserer, Clemens. "HTML5/Canvas backend for Caciocavallo (GNU-Classpath)". Archived from the original on 10 August 2011. Retrieved 8 August 2011.

Java: How to Read a Java String from the contents of a file

I have been using this idiom for some time now. And it seems to be the most wide-spread, at least in the sites I've visited.

Does anyone have a better/different way to Read a Java String from the contents of a file?

private String readFile( String file ) throws IOException {
    BufferedReader reader = new BufferedReader( new FileReader (file));
    String line = null;
    StringBuilder stringBuilder = new StringBuilder();
    String ls = System.getProperty("line.separator");

    while( ( line = reader.readLine() ) != null ) {
        stringBuilder.append( line );
        stringBuilder.append( ls );
    }

    return stringBuilder.toString();
}

Read String from a File Example:-

 import java.io.*;

 public class ReadFile{
   public static void main(String[]args){
      File file = new File(”/home/Parvez/MyJavaBook”, ”MyText.txt”);
      try{
         BufferedReader in = new BufferedReader(new FileReader(file));
         String str = in.readLine();
         while(str != null){
         System.out.println(”Read: ” +str);
         str = in.readLine();
         }
         in.close();
      }catch(FileNotFoundException e1){
         System.out.println(”File not found”);
      }catch(IOException e2){
         System.out.println(”Input/output problem”);
      }
   }
 }

Generation of Source Code:--

/*
Read File in String Using Java Buffered Input Stream Example. This example shows how to read a file content into a Sting object using available and read methods of Java Buffered Input Stream.
*/
    
    import java.io.*;
    
    public class ReadFileInToString {
    
            public static void main(String[] args) {
                  
                    //create file object
                    File file = new File("C://FileIO//ReadFile.txt");
                    BufferedInputStream bin = null;
                  
                    try
                    {
                            //create FileInputStream object
                            FileInputStream fin = new FileInputStream(file);
                          
                            //create object of BufferedInputStream
                            bin = new BufferedInputStream(fin);
                          
                            //create a byte array
                            byte[] contents = new byte[1024];
                          
                            int bytesRead=0;
                            String strFileContents;
                          
                            while( (bytesRead = bin.read(contents)) != -1){
                                  
                                    strFileContents = new String(contents, 0, bytesRead);
                                    System.out.print(strFileContents);
                            }
                          
                    }
                    catch(FileNotFoundException e)
                    {
                            System.out.println("File not found" + e);
                    }
                    catch(IOException ioe)
                    {
                            System.out.println("Exception while reading the file " + ioe);
                    }
                    finally
                    {
                            //close the BufferedInputStream using close method
                            try{
                                    if(bin != null)
                                            bin.close();
                            }catch(IOException ioe)
                            {
                                    System.out.println("Error while closing the stream :"
    + ioe);
                            }
                          
                    }
            }
          
    }
    
    
/*
Output would be This file is for demonstration of how to read a file into String using Java Buffered Input Stream.
*/

About Java | Write String to File using JavaScript Program

Write String to a File:

I am a beginner Java programmer attempting to make a simple text editor. I have the text from the text field in a String variable called "text".

How can I save the contents of the "text" variable to a text file?

String File Example 1:

import java.i o.*;

 public class WriteFile{
   public static void main(String[]args){
      File file = new File (”/home/Parvez/MyJavaBook” , ”MyText.txt”);
      try{
         InputStreamReader isr = new InputStreamReader(System.in);
         BufferedReader in = new Buf feredReader(isr);
         PrintWriter out = new PrintWriter(new FileWriter(file));
         System.out.println (”Write String: ”);
         String str = in.readLine();
         out.println(str);
         in.close();
         out.close();
      }catch(IOException e){
         e.printStackTrac e ();
      }
   }
 }

String File Example 2:

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

public class WriteToFileExample
{
  public static void main(String[] args)
  {
    try
    {
      // Here we'll write our data into a file called
      // sample.txt, this is the output.
      File file = new File("sample.txt");
      // We'll write the string below into the file
      String data = "Learning Java Programming";

      // To write a file called the writeStringToFile
      // method which require you to pass the file and
      // the data to be written.
      FileUtils.writeStringToFile(file, data);
    } catch (IOException e)
    {
      e.printStackTrace();
    }
  }
}

String File Example 3:

It's a simple example to write String to text file using Java code. Please note that you need the right to write in the target file.

package javafile;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class WriteStringToFile {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        FileWriter fileWriter = null;
        try {
            String content = "Hello! Java-Buddy :)";
            File newTextFile = new File("C:/test/test.txt");
            fileWriter = new FileWriter(newTextFile);
            fileWriter.write(content);
            fileWriter.close();
        } catch (IOException ex) {
            Logger.getLogger(WriteStringToFile.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fileWriter.close();
            } catch (IOException ex) {
                Logger.getLogger(WriteStringToFile.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

100 Java - Java Read File Line by Line in Java Program

Introduction:

This article shows how to cache files in Java in order to increase application performance. It discusses an algorithm for caching the file, a data structure for holding the cached content and a cache API for storing cached files.

File in Java:

To access a physical file we have to create a File object, which contains the address and name of the file. The FileReader class uses to read characters from a file and the FileWriter class uses to write characters to a file. The PrintWriter class is used the print() and println() methods.

Caching Files in Java:

Reading files from the disk can be slow, especially when an application reads the same file many times. Caching solves this problem by keeping frequently accessed files in memory. This allows the application to read the content of the from the fast local memory instead of the slow hard drive. Design for caching a file in Java includes three elements:

    1. An algorithm for caching the file
    2. A data structure for holding the cached content
    3. A cache API for storing cached files

Algorithm for Caching Files:-

A general algorithm for caching a file must account for file modifications and consists of the following steps:

    1. Get a value from the cache using a fully qualified file path as a key.
    2. If a key is not found, read the file content and put it to the cache.
    3. If the key is found, check if a timestamp of the cached content matches the file timestamp.
    4. If the timestamps are equal, return the cached content.
    5. If the timestamps are not equal, refresh the cache by reading the file and putting it into the cache.

Java Code for Caching Files:-

This article assumes that the file being cached is a text file. A code fragment below implements the caching algorithm for text files:

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import cacheonix.Cacheonix;
import cacheonix.cache.Cache;
import com.cacheonix.examples.cache.file.cache.data.grid.TextFile;

/**
 * An application demonstrating an application-level file cache.
 */
public class ApplicationFileCacheExample {

   /**
    * Gets a file content from the cache ant prints it in the standard output.
    *
    * @param args arguments
    * @throws IOException if an I/O error occured.
    */
   public static void main(String[] args) throws IOException {

      // Replace the file name with an actual file name
      String pathName = "test.file.txt";

      ApplicationFileCacheExample fileCacheExample = new ApplicationFileCacheExample();
      String fileFromCache = fileCacheExample.getFileFromCache(pathName);
      System.out.print("File content from cache: " + fileFromCache);
   }

   /**
    * Retrieves a file from a cache. Puts it into the cache if it's not cached yet.
    *
    * This method demonstrates a typical flow an application must follow to cache a file
    * and to get it from the cache. As you can see, the application is pretty involved
    * in maintaining the cache. It must read the file, check the the timestamps and update
    * the cache if its content is stale.
    *
    * @param pathName a file path name.
    * @return a cached file content or null if file not found
    * @throws IOException if an I/O error occurred.
    */

   public String getFileFromCache(String pathName) throws IOException {

      // Get cache
      Cacheonix cacheonix = Cacheonix.getInstance();

      Cache<String, TextFile> cache = cacheonix.getCache("application.file.cache");

      // Check if file exists
      File file = new File(pathName);
      if (!file.exists()) {

         // Invalidate cache
         cache.remove(pathName);

         // Return null (not found)
         return null;
      }

      // Get the file from the cache
      TextFile textFile = cache.get(pathName);

      // Check if the cached file exists
      if (textFile == null) {

         // Not found in the cache, put in the cache

         textFile = readFile(file);

         cache.put(pathName, textFile);
      } else {

         // Found in cache, check the modification time stamp

         if (textFile.getLastModified() != file.lastModified()) {

            // Update cache

            textFile = readFile(file);

            cache.put(pathName, textFile);
         }
      }

      return textFile.getContent();
   }

   /**
    * Reads a file into a new TextFile object.
    *
    * @param file the file to read from.
    * @return a new TextFile object.
    * @throws IOException if an I/O error occurred.
    */

   private static TextFile readFile(File file) throws IOException {

      // Read the file content into a StringBuilder
      char[] buffer = new char[1000];
      FileReader fileReader = new FileReader(file);
      StringBuilder fileContent = new StringBuilder((int) file.length());

      for (int bytesRead = fileReader.read(buffer); bytesRead != -1; ) {
         fileContent.append(buffer, 0, bytesRead);
      }

      // Close the reader
      fileReader.close();

      // Create CachedTextFile object
      TextFile textFile = new TextFile();
      textFile.setContent(fileContent.toString());
      textFile.setLastModified(file.lastModified());

      // Return the result
      return textFile;
   }
}

Related Tags for Java Read File Line by Line-Java:

java, c, string, mac, com, file, unicode, orm, data, form, utf-8, application, strings, input, io, types, format, output, streams, type, stream, system, number, read, transform, write, open, app, if, for, primitive, transformation, company, to, information, ci, ndepend, e, il, safe, it, doc, can, machine, li, mit, put, specification, use, pe, modification, im, from, in, mod, utf, rm, info, cs, m, nt, out, tr, nic, min, ca, min, nic, j, ad, es, spec, td, em, end, pen, ico, me, modi, pp, pan, cat, fs, do, sys, rel, s, sp, ee, at, any, late, is, ha, inf, iv, pre, erl, erl, ea, and, ar, cod, code, str, specific, tf, repr, sa, saf, sli, va, uses, underlying, ucs, s, s, ri, ring, th, av, st, chi, 6, ati, ap, af, hat, fe, inform, informat, ica, ica, pl, pr, mina, mi, nd, ode, on, om, o, np

Java Scan for JavaScript use Scanner - Java Solution

Scanner:-

The scanner class provides formated input functionality. It is a part of the java.util package.

Example for Scanner:-

 import java.io.*;
 import java.util.Scanner;

 public class ScannerTest{
   public static void main(String[]args){
      Scanner s = new Scanner(System.in);
      String str = s.next();
      System.out.println(str);
      int num = s.next Int();
      System. out.println(num);
      s.close();
   }
 }

Console Input: Scanner in JavaScript Program

The java.util.Scanner class (added in Java 5) allows simple console and file input. Of course, your program should eventually have a GUI user interface, but Scanner is very useful for reading data files.

  
import java.util.*;                //Note 1

public class IntroScanner {

    public static void main(String[] args) {
        //... Initialization
        String name;               // Declare a variable to hold the name.
        Scanner in = new Scanner(System.in);

        //... Prompt and read input.
        System.out.println("What's your name, Earthling?");
        name = in.nextLine();      // Read one line from the console.
        in.close();                //Note 2

        //... Display output
        System.out.println("Take me to your leader, " + name);
    }
}

Notes:

1. Altho we only need the Scanner class from the java.util package, the most common programming style is to make all classes (*) visible.

2. Closing the console isn't really necessary, but it's a good habit. If we had been reading a file, which is common with Scanner, closing it would be important.

Example uses for Scanner in a loop:-

import java.util.*;

public class ScannerLoop {

    public static void main(String[] args) {
        //... Initialization
        double n;                // Holds the next input number.
        double sum = 0;          // Sum of all input numbers.
        Scanner in = new Scanner(System.in);

        //... Prompt and read input in a loop.
        System.out.println("Will add numbers.  Non-number stops input.");
       
        while (in.hasNextDouble()) {
            n = in.nextDouble();
            sum = sum + n;
        }
        in.close();

        //... Display output
        System.out.println("The total is " + sum);
    }
}

Example for Scanner Program 2:-

This example demonstrates using Scanner to read a file containing lines of structured data. Each line is then parsed using a second Scanner and a simple delimiter character, used to separate each line into a name-value pair. The Scanner class is used only for reading, not for writing.

import java.io.*;
import java.util.Scanner;

public class ReadWithScanner {

  public static void main(String... aArgs) throws FileNotFoundException {
    ReadWithScanner parser = new ReadWithScanner("C:\\Temp\\test.txt");
    parser.processLineByLine();
    log("Done.");
  }
 
  /**
   Constructor.
   @param aFileName full name of an existing, readable file.
  */
  public ReadWithScanner(String aFileName){
    fFile = new File(aFileName); 
  }
 
  /** Template method that calls {@link #processLine(String)}.  */
  public final void processLineByLine() throws FileNotFoundException {
    //Note that FileReader is used, not File, since File is not Closeable
    Scanner scanner = new Scanner(new FileReader(fFile));
    try {
      //first use a Scanner to get each line
      while ( scanner.hasNextLine() ){
        processLine( scanner.nextLine() );
      }
    }
    finally {
      //ensure the underlying stream is always closed
      //this only has any effect if the item passed to the Scanner
      //constructor implements Closeable (which it does in this case).
      scanner.close();
    }
  }
 
  /**
   Overridable method for processing lines in different ways.
   
   <P>This simple default implementation expects simple name-value pairs, separated by an
   '=' sign. Examples of valid input :
   <tt>height = 167cm</tt>
   <tt>mass =  65kg</tt>
   <tt>disposition =  "grumpy"</tt>
   <tt>this is the name = this is the value</tt>
  */
  protected void processLine(String aLine){
    //use a second Scanner to parse the content of each line
    Scanner scanner = new Scanner(aLine);
    scanner.useDelimiter("=");
    if ( scanner.hasNext() ){
      String name = scanner.next();
      String value = scanner.next();
      log("Name is : " + quote(name.trim()) + ", and Value is : " + quote(value.trim()) );
    }
    else {
      log("Empty or invalid line. Unable to process.");
    }
    //no need to call scanner.close(), since the source is a String
  }
 
  // PRIVATE
  private final File fFile;
 
  private static void log(Object aObject){
    System.out.println(String.valueOf(aObject));
  }
 
  private String quote(String aText){
    String QUOTE = "'";
    return QUOTE + aText + QUOTE;
  }
}

Java Solution: Console Input/Output Program in Java

Console Output:

System.out.print("Hello ");
System.out.println("world");

Console Input:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String text = in.readLine();

Console Input/Output:-

Java 2 SDK support console I/O with three public variables in the java.lang.Syste class:

1. System.out (System.out is a PrintStream object)
2. System.in (System.in is a InputStream object)
3. System.err (System.err is a PrintStream onject)

Following code provides an example of keybord input, which import the java.io.*; package. In line 6, InputStreamReader reads characters and converts the row bytes into Unicode characters. In line 7, BufferedReader provides the readLine() method (in line 10), which enables the program to read from standard input (keyboard) one line at a time. Line 12, close the buffered reader. The readLine() method can throw an I/O exception, so this code is in a try-catch block.

Console Input/Output Program:-

 import java.io.*;

 public class ConsoleInput{
   public static void main(String[]args){
     String s;
     InputStreamReader isr = new InputStreamReader(System.in);
     BufferedReader in = new BufferedReader(isr);
     try{
        System.out.println(”Write something: ”);
        s = in.readLine();
        System.out.println(”Read: ” +s);
        in.close();
     }catch(IOException e){
        e.printStackTrac e();
     }
   }
 }

Console Input-Output Program:-

import java.util.*;

public class IntroScanner {

    public static void main(String[] args) {
        //... Initialization
        String name;                // Declare a variable to hold the name.
        Scanner in = new Scanner(System.in);

        //... Prompt and read input.
        System.out.println("What's your name, Earthling?");
        name = in.nextLine();      // Read one line from the console.

        //... Display output
        System.out.println("Take me to your leader, " + name);
    }
}

Related Tags for Console Input-Output:-

java, c, class, console, ole, scanner, if, ie, e, il, can, li, im, as, m, scan, ca, j, cl, s, so, ha, mpl, ann, cons, sim, util, va, uti, sca, s, s, av, lif, pl, on, ol, o

Java Program - Command Line Arguments in JavaScript Program

Command-Line Arguments:

In Java programming, we can provide zero or more command line arguments of  String type from a terminal window. The sequence of arguments follows the name of the program class and is stored in an array of String objects passed to the public static void main(String[] args) method.

Command-Line Arguments Example:-

 public class CommandLine{
   public static void main(String[]args){
      for(int i=0; i<args.length; i++)
        System.out.println(”Value of args in”+i+” index is : ”+args[i]);
  }
 }

[farid@local host MyJavaBook] \ $ javac CommandLine.java
[farid@local host MyJavaBook] \ $ java CommandLine 13 15 17

Value of args in 0 index is : 13
Value of args in 1 index is : 15
Value of args in 2 index is : 17


##Java application can accept any number of arguments directly from the command line.

Command Line Arguments in JavaScript:

Java application can accept any number of arguments directly from the command line. The user can enter command-line arguments when invoking the application. When running the java program from java command, the arguments are provided after the name of the class separated by space. For example, suppose a program named CmndLineArguments that accept command line arguments as a string array and echo them on standard output device.

java CmndLineArguments Mahendra zero one two three

CmndLineArguments.java

/**
   * How to use command line arguments in java program.
   */
   class CmndLineArguments {

  public static void main(String[] args) {
    int length = args.length;
    if (length <= 0) {
    System.out.println("You need to enter some arguments.");
    }
   for (int i = 0; i < length; i++) {
    System.out.println(args[i]);
   }
   }


Output of the program:

Run program with some command line arguments like:

java CmndLineArguments Mahendra zero one two three

OUTPUT:

Command line arguments were passed :
Mahendra
zero
one
two
three

Related Tags for Command Line Arguments in Java Program:

java, c, string, com, ide, command-line, array, class, application, io, user, output, arguments, command, vi, number, name, line, id, app, echo, device, for, example, program, standard, ram, exam, pos, run, argument, ear, e, space, comma, can, linear, li, put, use, man, dev, from, ce, enter, in, as, sta, m, nt, out, par, tr, separate, os, ca, os, j, nda, after, ace, cl, running, em, dir, named, me, pro, pp, rate, accept, cat, ctl, xa, when, xamp, s, rect, su, sp, direct, at, any, pac, k, ir, ha, ice, mpl, ray, ea, and, ar, cc, str, va, s, s, ri, ring, rd, th, cm, av, st, ati, ap, af, hat, invoking, ica, ica, ple, pl, pr, nd, on, om, ogr, o

Java Coding: Creating and Throwing User Defined Exception in Java

Creating and Throwing User Defined Exception:-

By extending Exception class we can cerate our own Exception class.

general format for Exception Handling:-

    try
    {
        // Code blocks
    }
    catch(Exception1 e)
    {
        //Code to execute if exception of type 1 occured
    }
    ...
    catch(Exceptionn e)
    {
        //Code to execute if exception of type n occured
    }
    catch
    {
        //Code to execute if exception which not handled above occured
    }
    finally
    {
        //Code that must be executed
    }

If you provide empty catch and Exception catch then empty catch will never come in action as Exception catch will handle all the exceptions.

    private int Divide(int a, int b)
    {
        return (a / b); //it will create exception.
    }
    public void checkException()
    {
        try
        {
        int a = Divide(5, 0);
        //other exception causing statements.
        }
        catch (DivideByZeroException UE)
        {
        MessageBox.Show(UE.Message);
        }
        catch (Exception UE)
        {
        MessageBox.Show(UE.Message);
        }
        catch
        {
        //This will never execute.
        MessageBox.Show("Exception Occured.");
        }
        finally
        {
        MessageBox.Show("Finally");
        }
    }


In the above example we have defined empty catch and Exception catch as well but empty catch will never get attention. Also note that whenever an exception occurs it traverses back the call trace until it finds a try block after which the application terminates if none try block is occured. After getting exception created in statement reading “return(a/b)” it traverses to stack trace and reaches check Exception method where it get handles as there is a try block. If try catch block would be missing from there then application will terminate as it is the default implementation in Button Click. Please also note that there must be at least one catch statement for every try block.

Program:-

 public class MyException extends Exception{
   public MyException(String massage){
      super(massage);
   }

 public static void main(String[]args){
    try{
       throw new MyException(”User defined exception”);
    }catch(MyException e){
       System.out.println(e);
    }
   }
 }

Though Java provides an extensive set of in-built exceptions, there are cases in which we may need to define our own exceptions in order to handle the various application specific errors that we might encounter.

While defining an user defined exception, we need to take care of the following aspects:

1.  The user defined exception class should extend from Exception class.

2. The toString() method should be overridden in the user defined exception class in order to display meaningful information about the exception.

Let us see a simple example to learn how to define and make use of user defined exceptions.


public class CustomExceptionTest {

    public static void main(String[] args) throws Exception{

        int age = getAge();

        if (age < 0){
            throw new NegativeAgeException(age);
        }else{
            System.out.println("Age entered is " + age);
        }
    }

    static int getAge(){
        return -10;
    }
}

In the Custom Exception Test class, the age is expected to be a positive number. It would throw the user defined exception Negative Age Exception if the age is assigned a negative number.

At run time, we get the following exception since the age is a negative number. Exception in thread "main" Age cannot be negative -10
at tips.basics.exception.CustomExceptionTest.main(CustomExceptionTest.java:10)

About Java - Handle Exceptions and Overriding Methods in Java

Method Overriding and Exception:-

The overriding method can declare only exceptions that are either the same class or a subclass of the exception. For example, if the superclass method throws an IOException, then the overriding method of superclass method can throw an IOException, a FileNotFoundException, which is the subclass of IOException, but not Exception, which is the superclass of IOException.

Method Overriding and Exception Example:-

 public class A{
   public void methodA()throws IOException{}
 }

 class B extends A{
   public void methodA() throws EOFException{
     // Legal, because EOFException is the sub class of IOException;
   }
 }

 class C extends A{
   public void methodA() throws Exception{
     // Illegal, because Exception is the super class of IOException;
   }
 }

f a method throws an checked exception , then the overriding method cannot throws new or boarder checked exceptions. if a method throws FileNotFoundExcepti

on , its overriding method cannot throw IOException or Exception , but the overriding method need not throw any exception or can throw unchecked exceptions like RuntimeException.

The overriding method should not reduce the visibility of overridden method. if method is declared as protected , the overriding method must have protected or public access modifier but it cannot be default or private.

The return type of overridden and overriding method must be the same or must be of covariant type

if A is the return type of overridden method. the B is the return type of overriding method then "B is-a A" must be true else it results in a complier error.

class A{

}

interface Inter{

}

class B extends A implements inter {

}

class Base {

public Inter getObject() {

}

public A getResult() {

}

public Inter getX() {

}

public Object toString() {

}

}


class Child extends Base {

public B getObject() {}//ok B is-a inter

public B getResult() {}//ok B is-a A

public A getX() {}//complier error as A is-a Inter is false ie A is not a Inter

public String toString() {}//ok String is-a Object
}


Now let me say why we have to use Same or sub type of Exception in sub class test method declaration.

super1.test() is going to call subclass method in runtime because we are using polymorphic assignment in creating super1 instance.

if sub class method is allowed to throw any super type of exceptions declared in Super class method. that is if we are allowed to throw Exception instead IOException( or its subtype). it will not fit into catch statement since catch is using exception declared in super class method that is IOException.

That is the reason we have to use same exception or its subtype.

Complete Code is Given Below:

public class Overriding {
   public static void main(String[] args) {
     Super super1 = new Sub();
     try {
       super1.test();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
}
class Super{
   public void test() throws IOException{
     System.out.println(”Super.test()”);
   }
}
class Sub extends Super{
   public void test(){
    System.out.println(”Sub.test()”);
   }
}