Canvas for Drawing (Java AWT)

A Canvas in Java (specifically AWT class) is a black rectangular / rectangle area where the application itself can draw or trap an input events from the user. The canvas inherits Component class.

AWT Canvas Syntax

public class Canvas extends Component implements Accessible  

No more chit-chatting, here’s an example of what you can do in AWT Canvas :

//1st import
  import java.awt.*;

 //2nd creates the method

 import javax.swing.JFrame;
public class CanvasExmpl extends JFrame
{
public CanvasExmpl()
{
JFrame f= new JFrame(“Canvas Example”);
f.add(new MyCanvas());
f.setLayout(null);
f.setSize(300, 300);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}



//3rd call and run it!     

public static void main(String args[]) {
new CanvasExmpl();
}
}
class MyCanvases extends Canvas
{
public MyCanvases() {
setBackground (Color.BLACK);
setSize(300, 200);
}
public void paint(Graphics g)
{
g.setColor(Color.WHITE);
g.fillOval(75, 75, 150, 75);
}
}

 

Watch my Youtube video on the same topic : https://www.youtube.com/watch?v=risnqJoa8uI

Simple Panely Panel Class

Panel in java.. probably is the simplest container class there is. It provides a space, which in that space the application can attach any other components. Panel inherits Container class.

Class Declaration :
public class Panel extends Container implements Accessible 

Done…
now It’s Exmpl time! :


// 1st it imports
    import java.awt.*;
// 2nd create the methods and constructor 
    public class PanelExample { 
         PanelExample() 
            { 
            Frame f= new Frame(“Panel Example”);   
            Panel panel=new Panel(); 
            panel.setBounds(40,80,200,200);   
            panel.setBackground(Color.blue); 
            Button b1=new Button(“Button 1”);    
            b1.setBounds(50,100,80,30);   
            b1.setBackground(Color.green);  
            Button b2=new Button(“Button 2”);  
            b2.setBounds(100,100,80,30);   
            b2.setBackground(Color.green);  
            panel.add(b1); panel.add(b2);
// 3rd sets the Frame condition.
            f.add(panel); 
            f.setSize(400,400);   
            f.setLayout(null);   
            f.setVisible(true);   
            }
// 4th call and run the methods and constructor / Application / Program
            public static void main(String args[]) 
            { 
            new PanelExample(); 
            } 
    } 

This’ll output :

Program… listen to Mouse! (MouseListener)

Yes… You can listen to your mouse, I mean not literally but.. you can make your program act as when you do something with you mouse, for example : make your program print out something when you click your mouse. Java MouseListener acts whenever the state of the mouse is changed. The MouseListener is notified agains MouseEvent. You can found MouseListener interface in a java.awt.event package. It has five methods.

Check these methods out :

  • public abstract void mouseClicked(MouseEvent e);  //when you click the mouse
  • public abstract void mouseEntered(MouseEvent e);  //when you entered the mouse / move
  • public abstract void mouseExited(MouseEvent e);  //when you exited the mouse / don’t move
  • public abstract void mousePressed(MouseEvent e);  //when you press / drag the mouse 
  • public abstract void mouseReleased(MouseEvent e);  //when you release the mouse  


 Anyway, that’s that for the theory, now you know what time it is !
It’s Exmpl time! :

//1st import
   import java.awt.*; 
    import java.awt.event.*;
//2nd create the Method/object and constructor of MouseListener 
    public class MouseListenerExmpl extends Frame implements MouseListener{ 
        MouseListenerExmpl(){ 
            addMouseListener(this); 
             
            setSize(300,300); 
            setLayout(null); 
            setVisible(true); 
        } 
        public void mouseClicked(MouseEvent e) { 
            Graphics g=getGraphics(); 
            g.setColor(Color.GREEN); 
            g.fillOval(e.getX(),e.getY(),30,30); 
        } 
        public void mouseEntered(MouseEvent e) {} 
        public void mouseExited(MouseEvent e) {} 
        public void mousePressed(MouseEvent e) {} 
        public void mouseReleased(MouseEvent e) {}           
//3rd call and run the method and constructor
    public static void main(String[] args) { 
        new MouseListenerExmpl(); 
    } 

and it’ll output this :

Java MenuBar : MainMenu and SubMenu

Ever wonder how to create a menu, just like in Mozilla Firefox and many other softwares? Well you can, 1 way is to create a MenuBar in java, not only the main menu but you can also create a subMenu inside the Menu. The object of the Menu class itself is a pull down menu component that is displayed on the menu bar. The Menu inherits the MenuItem class.

Menu and MenuItem class declaration :

public class Menu extends MenuItem implements MenuContainer

It’s Exmpl time :

1st import :

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

2nd framework :

class MenuExmpl extends JFrame{
 MenuExmpl(){
 } 
 public static void main(String args[]){
 }
}

3rd, Fill it! :


MenuExmpl(){ 
       
JFrame f= new JFrame(“Menu and MenuItem Example”); 
            MenuBar mb=new MenuBar();  //Creates menu object
               Menu menu=new Menu(“Menu”); //creates the main menu 
               Menu submenu=new Menu(“Preferences”);  //create the subMenu
            MenuItem i1=new MenuItem(“File”);  //create the MenuItem
            MenuItem i2=new MenuItem(“New”); //create the MenuItem 
            MenuItem i3=MenuExmpl(){ 
            JFrame f= new JFrame(“Menu and MenuItem Example”); 
               new MenuItem(“Settings”);  //create the MenuItem
            MenuItem i4=new MenuItem(“View”);  //create the MenuItem
            MenuItem i5=new MenuItem(“Windows”);  //create the MenuItem
               menu.add(i1);  //add item 1 to main Menu
               menu.add(i2);  //add item 2 to main Menu
               menu.add(i3);  //add item 3 to main Menu
            submenu.add(i4);  //add item 4 to sub Menu
            submenu.add(i5);  //add item 5 to sub Menu
               menu.add(submenu);  //add Sub Menu to Main Menu
               mb.add(menu); 
             f.setMenuBar(mb); 
             f.setSize(400,400); 
             f.setLayout(null); 
             f.setVisible(true); 

             f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     }  

public static void main(String args[]) 
    { 
    new MenuExmpl();  //call and run the menu object
    }  

if you put it together it will look as below :

import javax.swing.JFrame; 
    class MenuExmpl  extends JFrame
    {        
       
        MenuExmpl(){ 
        JFrame f= new JFrame(“Menu and MenuItem Example”); 

            MenuBar mb=new MenuBar(); 
               Menu menu=new Menu(“Menu”);
               Menu submenu=new Menu(“Preferences”); 
            MenuItem i1=new MenuItem(“File”); 
            MenuItem i2=new MenuItem(“New”);  
            MenuItem i3=MenuExmpl(){ 
            JFrame f= new JFrame(“Menu and MenuItem Example”); 
               new MenuItem(“Settings”); 
            MenuItem i4=new MenuItem(“View”);
            MenuItem i5=new MenuItem(“Windows”); 
               menu.add(i1); 
               menu.add(i2); 
               menu.add(i3); 
            submenu.add(i4);
            submenu.add(i5); 
               menu.add(submenu); 
               mb.add(menu); 
             f.setMenuBar(mb); 
             f.setSize(400,400); 
             f.setLayout(null); 
             f.setVisible(true);              

             f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    } 
    public static void main(String args[]) 
    { 
    new MenuExmpl(); 
    } 
    }

The result is this :

Java Choices Menu

Today we’ll do a popup menu, called choices. Choice is a popup menu that will show 1 or more choice to the user, and when the user select one it will be shown in the top menu. Choice inherits Component class.

Class Declaration

public class Choice extends Component implements ItemSelectable 

It’s Exmpl time! :


1st import

import java.awt.*;

2nd framework 

public class ChoiceExmpl{
 ChoiceExmpl(){
  }
 public static void main(String args[]){
  }
 }

3rd, fill it !:

ChoiceExmpl(){
  Frame f= new Frame(); 
            Choice c=new Choice(); 
            c.setBounds(200,200, 80,80); 
            c.add(“Choice 1”); 
            c.add(“Choice 2”); 
            c.add(“Choice 3”); 
            c.add(“Choice 4”); 
            c.add(“Choice 5”); 
            f.add(c); 
            f.setSize(500,500); 
            f.setLayout(null); 
            f.setVisible(true); 

 }
  public static void main(String args[]){
new ChoiceExmpl();
 }

Then, put it all in.. this is all you’ve done :

    import java.awt.*; 
    public class ChoiceExmpl 
    { 
            ChoiceExmpl(){ 
            Frame f= new Frame(); 
            Choice c=new Choice(); 
            c.setBounds(200,200, 80,80); 
            c.add(“Choice 1”); 
            c.add(“Choice 2”); 
            c.add(“Choice 3”); 
            c.add(“Choice 4”); 
            c.add(“Choice 5”); 
            f.add(c); 
            f.setSize(500,500); 
            f.setLayout(null); 
            f.setVisible(true); 
         } 
    public static void main(String args[]) 
    { 
       new ChoiceExmpl(); 
    } 
    } 

The result is this :


Java TextField

Since we’re talking about textField a lot in our previous discussion so, today we’ll do textField itself. In this part I’m going to make a non-actionlistener textField Okay let’s get goin ..

textField is a class that are built for text component that will allows the user an editing of a single line text, the textField itself Inherits TextComponent Class. (public class TextField extends TextComponent).

okay now, let’s get coding :


1st Import :

import java.awt.*;

2nd framework :

class textFieldExmpl{
  public static void main(String args[]) {
 }
}

3nd, fill it! :

public static void main(String args[]){
  Frame f= new Frame(“Example of TextField”);   
  TextField t1,t2;   
   t1=new TextField(“textField textField textField”);   
   t1.setBounds(50,100200,30);   
   t2=new TextField(“TextField Java AWT”);   
   t2.setBounds(50,150200,30);   
  f.add(t1); f.add(t2);   
   f.setSize(400,400);   
  f.setLayout(null);   
  f.setVisible(true);
}

Here is what you get :

import java.awt.*;

class textFieldExmpl{
   public static void main(String args[]) {
    Frame f= new Frame(“Example of TextField”); //creates a new Frame with title  
    TextField t1,t2;   //creates a new TextField (t1, t2)
      t1=new TextField(“textField textField textField”); //set the data for t1  

      t1.setBounds(50,100200,30);   //set the position, size, bound
      t2=new TextField(“TextField Java AWT”);   //set the data for  t2
       t2.setBounds(50,150200,30);   //set the position, size, bound
    f.add(t1); f.add(t2);   //add t1 and t2 to the Frame
      f.setSize(400,400);   //set the size of the frame
      f.setLayout(null);   //set the layout to null
      f.setVisible(true); //set the visibility to true
 }
}
Here is  the result :

Java AWT TextField
TextField

Java JComboBox

Previously we have created a progress bar in java or loading bar you’re familiar with, which is build using the swing package, and today we’ll create another functionality out of swing package and specifically we’ll create a JComboBox, a JComboBox class is of course used to create a comboBox (drop-down list). In a time there are only one item you can select from the item list. The comboBox would look like this:

Creating a JComboBox in java
JComboBox


So let’s get it work from scratch, as always… Importing!!! packages :

 import javax.swing.*;  //because comboBox is created using swing package

After that public main method, constructor and public static void main method :

public class ComboBox(){
 comboBox(){
 }
  public static void main(String[] args){
 }
}

Okay, we’re now in the 1/4 process of the program, let’s continue, JFrame :

 public class ComboBox { 
    JFrame f; //creates the JFrame and instantiate it as f
    ComboBox(){ 
        f=new JFrame(“ComboBox-ing”); 

   //now invoke the JFrame with the tittle of “ComboBox-ing”     
        f.setLayout(null);  //set the layout to null
        f.setSize(400,500);  //set the size of the JFrame to be 400×500
        f.setVisible(true);  //set the visibility to true
    }  

Now that we have the frame for our program, let’s start implementing out JComboBox into the program:

comboBox(){ 
        f=new JFrame(“ComboBox-ing”); 
         
        String country[] = {“IOndonesia”, “Aus”, “U.S.A”, “Chyna”};//creates a string
        JComboBox jb = new JComboBox(country); 

   //create a JComboBox object instantiated to be jb
        jb.setBounds(50, 50, 90, 20); //set the x,y, width, height
        f.add(jb); //add jb to JFrame f
       
        f.setLayout(null); 
        f.setSize(400,500); 
        f.setVisible(true); 
         
    }  

And right that we need to run it, and where exactly? of course in the public statid void main method.

public static void main(String[] args){
new  ComboBox;
}

And all together will unite to this one code :

    import javax.swing.*; 
    public class ComboBox { 
    JFrame f; 
    ComboBox(){ 
        f=new JFrame(“ComboBox-ing”); 
         
        String country[] = {“IOndonesia”, “Aus”, “U.S.A”, “Chyna”};
        JComboBox jb = new JComboBox(country);
        jb.setBounds(50, 50, 90, 20);
        f.add(jb);
       
        f.setLayout(null); 
        f.setSize(400,500); 
        f.setVisible(true); 
         
    } 
    public static void main(String[] args) { 
        new ComboBox(); 
         
    } 
    }  

JComboBox in java
JComboBox

Java JProgressBar

Okay today we’ll create something called a JProgressBar, you probably could already know what a know what a progressBar is, well if you don’t know it’s like when you’re watching youtube and video player has a red that keeps going based on the time of the video, or when you’re playing video games and it is loading to the next part, it all has a good example of progressBar but today we’ll create something simple, which look like this :


Okay we’ll setoff by importing every package that we needs, here is the package that you should import :

    import javax.swing.*; 

yup, that’s it! because there is an asterisk (*) sign at the end of javax.swing. syntax, that means we’re importing everything from inside the swing package.
After that part is done, now we’ll create the main public method, the constructor and every method that we’re going to need in this program :

 public class progressBar extends JFrame{
  progressBar(){
  }
  public void iterate(){
  }
   public static void main(String[] args){
  }
}

Now the framework of the program is done, we’ll fill it step by step now, first we’ll create everything that’s basic, and we’ll also fill the constructor first :

public class progressBar extends JFrame{
    JProgressBar jb;  //create a new JProgressBar that is instantiated as jb
    int i=0,num=0; //create 2 variable that we’re going to need later

 progressBar(){
  jb=new JProgressBar(0,2000);  
  //create a new JProgressBar with the time length of the progress it is based on
    jb.setBounds(100,150,200,30);  //set the size and boundaries of the JProgressBar
         
    jb.setValue(0);  //set the value first to 0
    jb.setStringPainted(true);  //makes the string able to be painted

         
    add(jb);  //add jb to the JFrame
    setSize(400,400);  //set the size of the JFrame
    setLayout(null);  //set the Layout to be null

 }
}

That part is done now, we’ll fill the iterate() method and public static void main method, this 2 methods should be inside the progressBar class :

public void iterate(){ 
    while(i<=2000){  //creates a while loop, when value of i <= 2000
      jb.setValue(i);  

     //now it will change the value of the jb.setValue that we set earlier based on the progress
      i=i+20;  //keeps changing i to be incremented by 20 while value of i <= 2000
      try{Thread.sleep(150);}catch(Exception e){}  

      //try to Thread.sleep for 150 ms and if it doesn’t work catch it as an exception
    } 
    } 
    public static void main(String[] args) { 
        progressBar pb=new progressBar();  //call the object
        pb.setVisible(true);  //makes progressBar to be visible
        pb.iterate();  //run the iterate() method
    } 

 
And together it should look like this :

 import javax.swing.*; 
    public class progressBar extends JFrame{ 

        private static final long serialVersionUID = 1L;
    JProgressBar jb; 
    int i=0,num=0; 
     
    progressBar(){ 
    jb=new JProgressBar(0,200); 
    jb.setBounds(100,150,200,30); 
         
    jb.setValue(0); 
    jb.setStringPainted(true); 
         
    add(jb); 
    setSize(400,400); 
    setLayout(null); 
    } 
     
    public void iterate(){ 
    while(i<=200){ 
      jb.setValue(i); 
      i=i+2; 
      try{Thread.sleep(150);}catch(Exception e){} 
    } 
    } 
    public static void main(String[] args) { 
        progressBar pb=new progressBar(); 
        pb.setVisible(true); 
        pb.iterate(); 
    } 
    }  


 

JTextArea Application

Hola amigos! today we’ll create a Text area in java which look like this :

Example of JTextArea application
JTextArea Application

And you can also do this, so follow me step by step as I unravel the way this program works.
So JTextArea is kinda like notepad if you know, and in JTextArea you can do much like notepad like : write text, delete text, make new line,  and we can edit the text that we already entered before.


Okay let’s work now. First let’s import everything :

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

Then we’ll create the main class, constructor and main method :

public class textArea{
  textArea{
 }
 public static void main(String[] args){
 }
}

now we’ll create the JTextArea and the JFrame :

public class textArea{
 JTextArea area;
 JFrame f = new JFrame();

}

and now inside the constructor we’ll create and set everything that’s needed for JTextArea and JFrame :

  textArea(){             
        area = new JTextArea(300,300);  //set the size of the Text area
        area.setBounds(10,30,370, 360);   //set the boundaries of the Text area
        area.setBackground(Color.black);   // set the background color
        area.setForeground(Color.orange);  //set the text color
             
        f.add(area);  //adds JTextArea area to JFrame
         
        f.setSize(400,400);  //set the size of the JFrame
        f.setLayout(null);  //set the layout in JFrame to null
        f.setVisible(true);  //set the visibility of the JFrame true

}

Let’s work with the one last thing to make this happen, we need to call the textArea so when we run the application both the JFrame and the JTextArea will work :

public static void main(String[] args) { 
            new textArea(); 

Congratss you now just created a JTextArea program, and this is how it looks when its combined :

    import java.awt.Color; 
    import javax.swing.*; 
     
    public class textArea { 
        JTextArea area; 
        JFrame f = new JFrame(); ; 
        textArea(){
             
        area=new JTextArea(300,300); 
        area.setBounds(10,30,370, 360); 
         
        area.setBackground(Color.black); 
        area.setForeground(Color.orange); 
             
        f.add(area); 
         
        f.setSize(400,400); 
        f.setLayout(null); 
        f.setVisible(true); 
    } 
        public static void main(String[] args) { 
            new textArea(); 
        } 
    }  

And so, this is how the program / application looks :

Example of JTextArea Application
JTextArea Application

How to make a Slider in Java #2

Okay today will add a little furniture to JSlider App, we’ll create a ticks on it, and now we’ll create it VERTICAL ly.

first this is our original code :

 import javax.swing.*; 
     
    public class SliderExample1 extends JFrame{ 
     
    public SliderExample1() { 
    JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25); 
    JPanel panel=new JPanel(); 
    panel.add(slider); 
     
    add(panel); 
    } 
     
    public static void main(String s[]) { 
    SliderExample1 frame=new SliderExample1(); 
    frame.pack(); 
    frame.setVisible(true); 
    } 
    }  


We’ll just have to add and edit a little detail on the program, first we’ll create the minor and major ticks and associate it with the JSlider slider, and we’ll edit the slider to be Vertical :

public SliderExample1() { 
    JSlider slider = new JSlider(JSlider.VERTICAL, 0, 50, 25); 
   
    slider.setMinorTickSpacing(2);  // create the minor ticks
    slider.setMajorTickSpacing(10); 

// create the major ticks the numbers of major tick depends from the size of the slier
   
    JPanel panel=new JPanel(); 
    panel.add(slider); 
     
    add(panel); 
    } 

And we won’t be able to see it unless we make the program to paint it to the slide, and we put this into the counstructor :

    slider.setPaintTicks(true);  // makes the ticks to be visible
    slider.setPaintLabels(true); // makes the numbers to be visible


And all together will be like this :

    import javax.swing.*; 
     
    public class SliderExample1 extends JFrame{ 
     
    public SliderExample1() { 
    JSlider slider = new JSlider(JSlider.VERTICAL, 0, 50, 25); 
   
    slider.setMinorTickSpacing(2); 
    slider.setMajorTickSpacing(10); 
   
    slider.setPaintTicks(true); 
    slider.setPaintLabels(true); 
   
    JPanel panel=new JPanel(); 
    panel.add(slider); 
     
    add(panel); 
    } 
     
    public static void main(String s[]) { 
    SliderExample1 frame=new SliderExample1(); 
    frame.pack(); 
    frame.setVisible(true); 
    } 
    }