Created By www.ebooktutorials.blogspot.in System.out.println(" ArrayList Elements"); System.out.print("\t" + a1); List l1 = new LinkedList(); l1.add("Beginner"); l1.add("Java"); l1.add("tutorial"); System.out.println(); System.out.println(" LinkedList Elements"); System.out.print("\t" + l1); Set s1 = new HashSet(); // or new TreeSet() will order the elements; s1.add("Beginner"); s1.add("Java"); s1.add("Java"); s1.add("tutorial"); System.out.println(); System.out.println(" Set Elements"); System.out.print("\t" + s1); Map m1 = new HashMap(); // or new TreeMap() will order based on keys m1.put("Windows", "98"); m1.put("Win", "XP"); m1.put("Beginner", "Java"); m1.put("Tutorial", "Site"); System.out.println(); System.out.println(" Map Elements"); System.out.print("\t" + m1); } }
Output ArrayList Elements [Beginner, Java, tutorial] LinkedList Elements [Beginner, Java, tutorial] Set Elements [tutorial, Beginner, Java] Map Elements {Tutorial=Site, Windows=98, Win=XP, Beginner=Java} Download CollectionsDemo.java
Java Coll ect ion s Sou r ce Code Ex am pl es On the following pages in this tutorial I have described how elements can be manipulated by different collections namely; Java Java Java Java Java Java Java
ArrayList LinkedList TreeSet HashMap Vect or HashTable HashSet
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in Sorted LinkedList linkedListA –> [0, 1, 2, 3, 4] Reversed LinkedList linkedListA –> [4, 3, 2, 1, 0] Is linkedListA empty? false linkedListA.equals(LinkedListC)? true LinkedList linkedListA after shuffling its elements–> 3 , 2 , 4 , 0 , 1 , Array Array Array Array Array
Element Element Element Element Element
[0] [1] [2] [3] [4]
= = = = =
3 2 4 0 1
linkedListA after clearing : [] Download LinkedListExample.java
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Jav a Tr eeSet public class TreeSet
extends AbstractSet implements SortedSet, Cloneable, Serializable This class implements the Set interface and guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements or by the comparator provided at set creation time, depending on which constructor is used. This implementation not synchronized provides guaranteed log(n) time cost for the basic operations (add, remove and contains). To prevent unsynchronized access to the Set.: SortedSet s = Collections.synchronizedSortedSet(new TreeSet(..)); Below is a TreeSet Example showing how collections are manipulated using a TreeSet import java.util.Set; import java.util.TreeSet; import java.util.Iterator; public class TreeSetExample { public static void doTreeSetExample() { } public static void main(String[] args) { Set treeSet = new TreeSet(); // the treeset stores Integer objects into the TreeSet for (int i = 0; i < 5; i++) { treeSet.add(new Integer(i)); } // Since its a Integer Object Set adding any other elements in the Same // set will produce a // ClassCastException exception at runtime. // treeSet.add("a string"); System.out.print("The elements of the TreeSet are : "); Iterator i = treeSet.iterator(); while (i.hasNext()) { System.out.print(i.next() + "\t"); } } }
Output The elements of the TreeSet are : 0 1 2 3 4 Download TreeSetExample.java
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java HashMap The j av a Hash Ma p class does not guarantee that the order will remain constant over time. This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. The HashMap implementation is not synchronized. If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. To prevent unsynchronized access to the Map: Map m = Collections.synchronizedMap(new HashMap(…)); Below is a HashMap Example used to store the number of words that begin with a given letter /* * Using a HashMap to store the number of words that begin with a given letter. */ import java.util.HashMap; public class HashMapExample { static String[] names = { "heman", "bob", "hhh", "shawn", "scot","shan", "keeth" }; private static HashMap counter = new HashMap(); private static Integer cnt = null; public static void main(String args[]) { for (int i = 0; i < names.length; i++) { cnt = (Integer) (counter.get(new Character(names[i].charAt(0)))); if (cnt == null) { counter.put(new Character(names[i].charAt(0)),new Integer("1")); } else { counter.put(new Character(names[i].charAt(0)), new Integer(cnt.intValue() + 1)); } } System.out.println("\nnumber of words beginning with each letter is shown below "); System.out.println(counter.toString()); } }
Output number of words beginning with each letter is shown below {s=3, b=1, k=1, h=2} Download HashMapExample.java
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java Vect or public class Vector extends AbstractList implements List, RandomAccess, Cloneable, Serializable The Vector class implements a growable array of objects where the size of the vector can grow or shrink as needed dynamically. Like an array, it contains components that can be accessed using an integer index. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation. Below is a Vector Example show ing how collecti ons are manipulated u sing a Vector import import import import import import import import import import import import import import
java.awt.Container; java.awt.FlowLayout; java.awt.event.ActionEvent; java.awt.event.ActionListener; java.awt.event.WindowAdapter; java.awt.event.WindowEvent; java.util.Enumeration; java.util.NoSuchElementException; java.util.Vector; javax.swing.JButton; javax.swing.JFrame; javax.swing.JLabel; javax.swing.JOptionPane; javax.swing.JTextField;
public class VectorDemo extends JFrame { private JLabel jlbString = new JLabel("Enter a string"); public VectorDemo() { super("Vector class demo"); // Made final as it can be accessed by inner classes final JLabel jlbStatus = new JLabel(); Container contentPane = getContentPane(); final Vector vector = new Vector(1); contentPane.setLayout(new FlowLayout()); contentPane.add(jlbString); final JTextField jtfInput = new JTextField(10); contentPane.add(jtfInput); JButton jbnAdd = new JButton("Add"); jbnAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { vector.addElement(jtfInput.getText().trim()); jlbStatus.setText("Appended to end: " + jtfInput.getText().trim()); jtfInput.setText(""); } }); contentPane.add(jbnAdd); JButton jbnRemove = new JButton("Remove"); jbnRemove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Returns true if element in vector if (vector.removeElement(jtfInput.getText().trim())) jlbStatus.setText("Removed: " + jtfInput.getText()); else jlbStatus.setText(jtfInput.getText().trim() + " not in vector"); } }); contentPane.add(jbnRemove); JButton jbnFirst = new JButton("First"); jbnFirst.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { jlbStatus.setText("First element: " + vector.firstElement()); } catch (NoSuchElementException exception) { jlbStatus.setText(exception.toString()); } } }); contentPane.add(jbnFirst); JButton jbnLast = new JButton("Last"); jbnLast.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { jlbStatus.setText("Last element: " + vector.lastElement()); } catch (NoSuchElementException exception) { jlbStatus.setText(exception.toString()); } } }); contentPane.add(jbnLast); JButton jbnEmpty = new JButton("Is Empty?"); jbnEmpty.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jlbStatus.setText(vector.isEmpty() ? "Vector is empty" : "Vector is not empty"); } }); contentPane.add(jbnEmpty); JButton jbnContains = new JButton("Contains"); jbnContains.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String searchKey = jtfInput.getText().trim(); if (vector.contains(searchKey)) { jlbStatus.setText("Vector contains " + searchKey); } else { jlbStatus.setText("Vector does not contain " + searchKey); }
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in } }); contentPane.add(jbnContains); JButton jbnFindElement = new JButton("Find"); jbnFindElement.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jlbStatus.setText("Element found at location " + vector.indexOf(jtfInput.getText().trim())); } }); contentPane.add(jbnFindElement); JButton jbnTrim = new JButton("Trim"); jbnTrim.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { vector.trimToSize(); jlbStatus.setText("Vector trimmed to size"); } }); contentPane.add(jbnTrim); JButton jbnSize = new JButton("Size/Capacity"); jbnSize.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jlbStatus.setText("Size = " + vector.size() + "; Capacity = " + vector.capacity()); } }); contentPane.add(jbnSize); JButton jbnDisplay = new JButton("Display"); jbnDisplay.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Enumeration enum1 = vector.elements(); StringBuffer buf = new StringBuffer(); while (enum1.hasMoreElements()) buf.append(enum1.nextElement()).append(" "); JOptionPane.showMessageDialog(null, buf.toString(), "Contents of Vector", JOptionPane.PLAIN_MESSAGE); } }); contentPane.add(jbnDisplay); contentPane.add(jlbStatus); setSize(300, 200); setVisible(true); } public static void main(String args[]) { VectorDemo vectorDemo = new VectorDemo(); vectorDemo.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
Output
Download VectorExample.java
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java HashTable HashTable is synchronized. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t. Hashtable doesn’t allow nulls Below is a HashTable Example showing how collections are manipulated using a HashTable Please Note that It must be Compiled in Java 1.4. // Demonstrates the Hashtable class of the java.util package. public class HashTableDemo extends JFrame { public HashTableDemo() { super(" Hashtable Sourcecode Example"); final JLabel jlbStatus = new JLabel(); final Hashtable hashTable = new Hashtable(); final JTextArea display = new JTextArea(4, 20); display.setEditable(false); JPanel jplNorth = new JPanel(); jplNorth.setLayout(new BorderLayout()); JPanel jplNorthSub = new JPanel(); jplNorthSub.add(new JLabel("Name (Key)")); final JTextField jtfFirstName = new JTextField(8); jplNorthSub.add(jtfFirstName); jplNorthSub.add(new JLabel("Phone No")); final JTextField jtfPhone = new JTextField(8); jplNorthSub.add(jtfPhone); jplNorth.add(jplNorthSub, BorderLayout.NORTH); jplNorth.add(jlbStatus, BorderLayout.SOUTH); JPanel jplSouth = new JPanel(); jplSouth.setLayout(new GridLayout(2, 5)); JButton jbnAdd = new JButton("Add"); jbnAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String strNum = jtfPhone.getText().trim(); String strName = jtfFirstName.getText().trim(); if ((strNum != null && strNum.equals("")) || (strName != null && strName.equals(""))) { JOptionPane.showMessageDialog(HashTableDemo.this, "Please enter both Name and Phone No"); return; } int num = 0; try { num = Integer.parseInt(strNum); } catch (NumberFormatException ne) { ne.printStackTrace(); } EmployeeDetails emp = new EmployeeDetails(strName, num); Object val = hashTable.put(strName, emp); if (val == null) jlbStatus.setText("Added: " + emp.toString()); else jlbStatus.setText("Added: " + emp.toString() + "; Replaced: " + val.toString()); } }); jplSouth.add(jbnAdd); JButton jbnGet = new JButton("Get"); jbnGet.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object val = hashTable.get(jtfFirstName.getText().trim()); if (val != null) jlbStatus.setText("Get: " + val.toString()); else jlbStatus.setText("Get: " + jtfFirstName.getText()+ " not in table"); } }); jplSouth.add(jbnGet); JButton jbnRemove = new JButton("Remove Name"); jbnRemove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object val = hashTable.remove(jtfFirstName.getText() .trim()); if (val != null) jlbStatus.setText("Remove: " + val.toString()); else jlbStatus.setText("Remove: " + jtfFirstName.getText()+ " not in table"); } }); jplSouth.add(jbnRemove); JButton jbnIsEmpty = new JButton("Empty ?"); jbnIsEmpty.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jlbStatus.setText("Empty: " + hashTable.isEmpty()); } }); jplSouth.add(jbnIsEmpty); JButton jbnContains = new JButton("Contains key"); jbnContains.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jlbStatus.setText("Contains key: "+ hashTable.containsKey(jtfFirstName.getText().trim())); } }); jplSouth.add(jbnContains); JButton jbnClear = new JButton("Clear table"); jbnClear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hashTable.clear();
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in jlbStatus.setText("HashTable Emptied"); } }); jplSouth.add(jbnClear); JButton jbnDisplay = new JButton("List objects"); jbnDisplay.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { StringBuffer buf = new StringBuffer(); for (Enumeration enum = hashTable.elements(); enum.hasMoreElements();) buf.append(enum.nextElement()).append('\n'); display.setText(buf.toString()); } }); jplSouth.add(jbnDisplay); JButton jbnKeys = new JButton("List keys"); jbnKeys.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { StringBuffer buf = new StringBuffer(); for (Enumeration enum = hashTable.keys(); enum.hasMoreElements();) buf.append(enum.nextElement()).append('\n'); JOptionPane.showMessageDialog(null, buf.toString(), "Display Keys of HashTable ",JOptionPane.PLAIN_MESSAGE); } }); jplSouth.add(jbnKeys); Container c = getContentPane(); c.add(jplNorth, BorderLayout.NORTH); c.add(new JScrollPane(display), BorderLayout.CENTER); c.add(jplSouth, BorderLayout.SOUTH); setSize(540, 300); setVisible(true); } public static void main(String args[]) { HashTableDemo hashTableDemo = new HashTableDemo(); hashTableDemo.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } } class EmployeeDetails { private String name; private int phoneNp; public EmployeeDetails(String fName, int phNo) { name = fName; phoneNp = phNo; } public String toString() { return name + " " + phoneNp; } }
Output
Download HashTableDemo.java
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Jav a HashSet The HashSet class implements the Set interface. It makes no guarantee that the order of elements will remain constant over time. This class is not synchronized and permits a null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. To prevent unsynchronized access to the Set: Set s = Collections.synchronizedSet(new HashSet(…)); Below is a HashSet Example showing how collections are manipulated using a HashSet import java.util.*; public class HashSetExample { private static String names[] = { "bob", "hemanth", "hhh", "hero", "shawn", "bob", "mike", "Rick", "rock", "hemanth", "mike", "undertaker" }; public static void main(String args[]) { ArrayList aList; aList = new ArrayList(Arrays.asList(names)); System.out.println("The names elements " + aList); HashSet ref = new HashSet(aList); // create a HashSet Iterator i = ref.iterator(); System.out.println(); System.out.print("Unique names are: "); while (i.hasNext()) System.out.print(i.next() + " "); System.out.println(); } }
Output The names elements [bob, hemanth, hhh, hero, shawn, bob, mike, Rick, rock, hemanth, mike, undertaker] Unique names are: hhh hero bob Rick shawn hemanth rock mike undertaker
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java Arr ayList public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, Serializable Resizable-array implementation of the List interface. A j av a Ar r ay List is used to store an “ordered” group of elements where duplicates are allowed. Implements all optional list operations, and permits all elements, including null. This class is similar to Vector, except that it is unsynchronized. The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. ArrayList’s give great performance on get() and set() methods, but do not perform well on add() and remove() methods when compared to a LinkedList. An ArrayList capacity is the size of the array used to store the elements in the list. As elements are added to an ArrayList, its capacity grows automatically. It is an Array based implementation where elements of the List can be accessed directly through get() method. To prevent unsynchronized access to the list: List list = Collections.synchronizedList(new ArrayList(…)); Below is an ArrayList Example showing how collections are manipulated using an ArrayList import import import import import import
java.util.List; java.util.ArrayList; java.util.Iterator; java.util.ListIterator; java.util.Collections; java.util.Random;
public class ArrayListExample { public static void main(String[] args) { // ArrayList Creation List arraylistA = new ArrayList(); List arraylistB = new ArrayList(); // Adding elements to the ArrayList for (int i = 0; i < 5; i++) { arraylistA.add(new Integer(i)); } arraylistB.add("beginner"); arraylistB.add("java"); arraylistB.add("tutorial"); arraylistB.add("."); arraylistB.add("com"); arraylistB.add("java"); arraylistB.add("site"); // Iterating through the ArrayList to display the Contents. Iterator i1 = arraylistA.iterator(); System.out.print("ArrayList arraylistA --> "); while (i1.hasNext()) { System.out.print(i1.next() + " , "); } System.out.println(); System.out.print("ArrayList arraylistA --> "); for (int j = 0; j < arraylistA.size(); j++) { System.out.print(arraylistA.get(j) + " , "); } System.out.println(); Iterator i2 = arraylistB.iterator(); System.out.println("ArrayList arraylistB --> "); while (i2.hasNext()) { System.out.print(i2.next() + " , "); } System.out.println(); System.out.println(); System.out .println("Using ListIterator to retrieve ArrayList Elements"); System.out.println(); ListIterator li1 = arraylistA.listIterator(); // next(), hasPrevious(), hasNext(), hasNext() nextIndex() can be used with a // ListIterator interface implementation System.out.println("ArrayList arraylistA --> "); while (li1.hasNext()) { System.out.print(li1.next() + " , "); } System.out.println(); // Searching for an element in the ArrayList int index = arraylistB.indexOf("java"); System.out.println("'java' was found at : " + index); int lastIndex = arraylistB.lastIndexOf("java"); System.out.println("'java' was found at : " + lastIndex + " from the last"); System.out.println(); // Getting the subList from the original List List subList = arraylistA.subList(3, arraylistA.size()); System.out.println("New Sub-List(arraylistA) from index 3 to " + arraylistA.size() + ": " + subList); System.out.println(); // Sort an ArrayList System.out.print("Sorted ArrayList arraylistA --> "); Collections.sort(arraylistA); System.out.print(arraylistA); System.out.println(); // Reversing an ArrayList System.out.print("Reversed ArrayList arraylistA --> "); Collections.reverse(arraylistA); System.out.println(arraylistA); System.out.println(); // Checking emptyness of an ArrayList System.out.println("Is arraylistA empty? " + arraylistA.isEmpty()); System.out.println(); // Checking for Equality of ArrayLists ArrayList arraylistC = new ArrayList(arraylistA); System.out.println("arraylistA.equals(arraylistC)? "
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in + arraylistA.equals(arraylistC)); System.out.println(); // Shuffling the elements of an ArrayList in Random Order Collections.shuffle(arraylistA, new Random()); System.out .print("ArrayList arraylistA after shuffling its elements--> "); i1 = arraylistA.iterator(); while (i1.hasNext()) { System.out.print(i1.next() + " , "); } System.out.println(); System.out.println(); // Converting an ArrayList to an Array Object[] array = arraylistA.toArray(); for (int i = 0; i < array.length; i++) { System.out.println("Array Element [" + i + "] = " + array[i]); } System.out.println(); // Clearing ArrayList Elements arraylistA.clear(); System.out.println("arraylistA after clearing : " + arraylistA); System.out.println(); } }
Output ArrayList ArrayList ArrayList beginner
arraylistA –> 0 , 1 , 2 , 3 , 4 , arraylistA –> 0 , 1 , 2 , 3 , 4 , arraylistB –> , java , tutorial , . , com , java , site ,
Using ListIterator to retrieve ArrayList Elements ArrayList arraylistA –> 0,1,2,3,4, ‘java’ was found at : 1 ‘java’ was found at : 5 from the last New Sub-List(arraylistA) from index 3 to 5: [3, 4] Sorted ArrayList arraylistA –> [0, 1, 2, 3, 4] Reversed ArrayList arraylistA –> [4, 3, 2, 1, 0] Is arraylistA empty? false arraylistA.equals(arraylistC)? true ArrayList arraylistA after shuffling its elements–> 3 , 2 , 1 , 0 , 4 , Array Array Array Array Array
Element Element Element Element Element
[0] [1] [2] [3] [4]
= = = = =
3 2 1 0 4
arraylistA after clearing : [] Download ArrayListExample.java
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java Dat e Ut ilit y Java Dat e API java.util. Class Date java.lang.Object extended by java.util.Date All I mplemented I nterfaces: Cloneable, Comparable, Serializable Direct Known Subclasses: Date, Time, Timestamp public class Date extends Object implements Serializable, Cloneable, Comparable The class Date represents a specific instant in time, with millisecond precision.
Java Dat e Sou rce Code import import import import import
java.text.DateFormat; java.text.ParseException; java.text.SimpleDateFormat; java.util.Calendar; java.util.Date;
public class DateUtility { /* Add Day/Month/Year to a Date add() is used to add values to a Calendar object. You specify which Calendar field is to be affected by the operation (Calendar.YEAR, Calendar.MONTH, Calendar.DATE). */ public static final String DATE_FORMAT = "dd-MM-yyyy"; //See Java DOCS for different date formats // public static final String DATE_FORMAT = "yyyy-MM-dd"; public static void addToDate() { System.out.println("1. Add to a Date Operation\n"); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); //Gets a calendar using the default time zone and locale. Calendar c1 = Calendar.getInstance(); Date d1 = new Date(); // System.out.println("Todays date in Calendar Format : "+c1); System.out.println("c1.getTime() : " + c1.getTime()); System.out.println("c1.get(Calendar.YEAR): "+ c1.get(Calendar.YEAR)); System.out.println("Todays date in Date Format : " + d1); c1.set(1999, 0, 20); //(year,month,date) System.out.println("c1.set(1999,0 ,20) : " + c1.getTime()); c1.add(Calendar.DATE, 20); System.out.println("Date + 20 days is : "+ sdf.format(c1.getTime())); System.out.println(); System.out.println("-------------------------------------"); } /*Substract Day/Month/Year to a Date roll() is used to substract values to a Calendar object. You specify which Calendar field is to be affected by the operation (Calendar.YEAR, Calendar.MONTH, Calendar.DATE). Note: To substract, simply use a negative argument. roll() does the same thing except you specify if you want to roll up (add 1) or roll down (substract 1) to the specified Calendar field. The operation only affects the specified field while add() adjusts other Calendar fields. See the following example, roll() makes january rolls to december in the same year while add() substract the YEAR field for the correct result. Hence add() is preferred even for subtraction by using a negative element. */ public static void subToDate() { System.out.println("2. Subtract to a date Operation\n"); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); Calendar c1 = Calendar.getInstance(); c1.set(1999, 0, 20); System.out.println("Date is : " + sdf.format(c1.getTime())); // roll down, substract 1 month c1.roll(Calendar.MONTH, false); System.out.println("Date roll down 1 month : "+ sdf.format(c1.getTime())); c1.set(1999, 0, 20); System.out.println("Date is : " + sdf.format(c1.getTime())); c1.add(Calendar.MONTH, -1); // substract 1 month System.out.println("Date minus 1 month : "+ sdf.format(c1.getTime())); System.out.println(); System.out.println("-------------------------------------"); } public static void daysBetween2Dates() { System.out.println("3. No of Days between 2 dates\n"); Calendar c1 = Calendar.getInstance(); //new GregorianCalendar(); Calendar c2 = Calendar.getInstance(); //new GregorianCalendar(); c1.set(1999, 0, 20); c2.set(1999, 0, 22); System.out.println("Days Between " + c1.getTime() + " and "
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java HashTable HashTable is synchronized. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t. Hashtable doesn’t allow nulls Below is a HashTable Example showing how collections are manipulated using a HashTable Please Note that It must be Compiled in Java 1.4. // Demonstrates the Hashtable class of the java.util package. public class HashTableDemo extends JFrame { public HashTableDemo() { super(" Hashtable Sourcecode Example"); final JLabel jlbStatus = new JLabel(); final Hashtable hashTable = new Hashtable(); final JTextArea display = new JTextArea(4, 20); display.setEditable(false); JPanel jplNorth = new JPanel(); jplNorth.setLayout(new BorderLayout()); JPanel jplNorthSub = new JPanel(); jplNorthSub.add(new JLabel("Name (Key)")); final JTextField jtfFirstName = new JTextField(8); jplNorthSub.add(jtfFirstName); jplNorthSub.add(new JLabel("Phone No")); final JTextField jtfPhone = new JTextField(8); jplNorthSub.add(jtfPhone); jplNorth.add(jplNorthSub, BorderLayout.NORTH); jplNorth.add(jlbStatus, BorderLayout.SOUTH); JPanel jplSouth = new JPanel(); jplSouth.setLayout(new GridLayout(2, 5)); JButton jbnAdd = new JButton("Add"); jbnAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String strNum = jtfPhone.getText().trim(); String strName = jtfFirstName.getText().trim(); if ((strNum != null && strNum.equals("")) || (strName != null && strName.equals(""))) { JOptionPane.showMessageDialog(HashTableDemo.this, "Please enter both Name and Phone No"); return; } int num = 0; try { num = Integer.parseInt(strNum); } catch (NumberFormatException ne) { ne.printStackTrace(); } EmployeeDetails emp = new EmployeeDetails(strName, num); Object val = hashTable.put(strName, emp); if (val == null) jlbStatus.setText("Added: " + emp.toString()); else jlbStatus.setText("Added: " + emp.toString() + "; Replaced: " + val.toString()); } }); jplSouth.add(jbnAdd); JButton jbnGet = new JButton("Get"); jbnGet.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object val = hashTable.get(jtfFirstName.getText().trim()); if (val != null) jlbStatus.setText("Get: " + val.toString()); else jlbStatus.setText("Get: " + jtfFirstName.getText()+ " not in table"); } }); jplSouth.add(jbnGet); JButton jbnRemove = new JButton("Remove Name"); jbnRemove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object val = hashTable.remove(jtfFirstName.getText() .trim()); if (val != null) jlbStatus.setText("Remove: " + val.toString()); else jlbStatus.setText("Remove: " + jtfFirstName.getText()+ " not in table"); } }); jplSouth.add(jbnRemove); JButton jbnIsEmpty = new JButton("Empty ?"); jbnIsEmpty.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jlbStatus.setText("Empty: " + hashTable.isEmpty()); } }); jplSouth.add(jbnIsEmpty); JButton jbnContains = new JButton("Contains key"); jbnContains.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jlbStatus.setText("Contains key: "+ hashTable.containsKey(jtfFirstName.getText().trim())); } }); jplSouth.add(jbnContains); JButton jbnClear = new JButton("Clear table"); jbnClear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hashTable.clear();
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in + c2.getTime() + " is"); System.out.println((c2.getTime().getTime() - c1.getTime() .getTime()) / (24 * 3600 * 1000)); System.out.println(); System.out.println("-------------------------------------"); } public static void daysInMonth() { System.out.println("4. No of Days in a month for a given date\n"); Calendar c1 = Calendar.getInstance(); // new GregorianCalendar(); c1.set(1999, 6, 20); int year = c1.get(Calendar.YEAR); int month = c1.get(Calendar.MONTH); // int days = c1.get(Calendar.DATE); int[] daysInMonths = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,31 }; daysInMonths[1] += DateUtility.isLeapYear(year) ? 1 : 0; System.out.println("Days in " + month + "th month for year" + year + "is " + daysInMonths[c1.get(Calendar.MONTH)]); System.out.println(); System.out.println("-------------------------------------"); } public static void validateAGivenDate() { System.out.println("5. Validate a given date\n"); String dt = "20011223"; String invalidDt = "20031315"; String dateformat = "yyyyMMdd"; Date dt1 = null, dt2 = null; try { SimpleDateFormat sdf = new SimpleDateFormat(dateformat); sdf.setLenient(false); dt1 = sdf.parse(dt); dt2 = sdf.parse(invalidDt); System.out.println("Date is ok = " + dt1 + "(" + dt + ")"); } catch (ParseException e) { System.out.println(e.getMessage()); } catch (IllegalArgumentException e) { System.out.println("Invalid date"); } System.out.println(); System.out.println("-------------------------------------"); } public static void compare2Dates() { System.out.println("6. Comparision of 2 dates\n"); SimpleDateFormat fm = new SimpleDateFormat("dd-MM-yyyy"); Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.set(2000, 02, 15); c2.set(2001, 02, 15); System.out.print(fm.format(c1.getTime()) + " is "); if (c1.before(c2)) { System.out.println("less than " + fm.format(c2.getTime())); } else if (c1.after(c2)) { System.out.println("greater than " + fm.format(c2.getTime())); } else if (c1.equals(c2)) { System.out.println("is equal to " + fm.format(c2.getTime())); } System.out.println(); System.out.println("-------------------------------------"); } public static void getDayofTheDate() { System.out.println("7. Get the day for a given date\n"); Date d1 = new Date(); String day = null; DateFormat f = new SimpleDateFormat("EEEE"); try { day = f.format(d1); } catch (Exception e) { e.printStackTrace(); } System.out.println("The day for " + d1 + " is " + day); System.out.println(); System.out.println("-------------------------------------"); } //Utility Method to find whether an Year is a Leap year or Not public static boolean isLeapYear(int year) { if ((year % 100 != 0) || (year % 400 == 0)) { return true; } return false; } public static void main(String args[]) { addToDate(); //Add day, month or year to a date field. subToDate(); //Subtract day, month or year to a date field. daysBetween2Dates(); //The "right" way would be to compute the Julian day number of //both dates and then do the subtraction. daysInMonth();//Find the number of days in a month for a date validateAGivenDate();//Check whether the date format is proper compare2Dates(); //Compare 2 dates getDayofTheDate(); } }
Output 1. Add to a Date Operation c1.getTime() : Sat Mar 31 10:47:54 IST 2007 c1.get(Calendar.YEAR): 2007 Todays date in Date Format : Sat Mar 31 10:47:54 IST 2007 c1.set(1999,0 ,20) : Wed Jan 20 10:47:54 IST 1999 Date + 20 days is : 09-02-1999 ——————————————————2. Subtract to a date Operation Date is : 20-01-1999
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in Date roll down 1 month : 20-12-1999 Date is : 20-01-1999 Date minus 1 month : 20-12-1998 ——————————————————3. No of Days between 2 dates Days Between Wed Jan 20 10:47:54 IST 1999 and Fri Jan 22 10:47:54 IST 1999 is 2 ——————————————————4. No of Days in a month for a given date Days in 6th month for year 1999 is 31 ——————————————————5. Validate a given date Unparseable date: “20031315″
——————————————————6. Comparision of 2 dates 15-03-2000 is less than 15-03-2001 ——————————————————7. Get the day for a given date The day for Sat Mar 31 10:47:54 IST 2007 is Saturday ——————————————————Download Date Utility Source Code What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars. What is t he SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar.
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java Sw ing Tut orial This site contains brief tutorials for java swing programming along with java swing examples and source code. Java Swings Tutorial
What is Sw ings in j ava ? A part of The JFC Sw ing Java consists of Look and feel Accessibility Java 2D Drag and Drop, etc Compiling & running programs ‘javac ’ && ‘java ’ Or JCreator / IDE if you do not explicitly add a GUI component to a container, the GUI component will not be displayed when the container appears on the screen. Swing, which is an extension library to the AWT, includes new and improved components that enhance the look and functionality of GUIs. Swing can be used to build Standalone swing gui Apps as well as Servlets and Applets. It employs a model/view design architecture. Swing is more portable and more flexible than AWT. Swing Model/view design: The “view part” of the MV design is implemented with a component object and the UI object. The “model part” of the MV design is implemented by a model object and a change listener object. Swing is built on top of AWT and is entirely written in Java, using AWT’s lightweight component support. In particular, unlike AWT, t he architecture of Swing components makes it easy to customize both their appearance and behavior. Components from AWT and Swing can be mixed, allowing you to add Swing support to existing AWT-based programs. For example, swing components such as JSlider, JButton and JCheckbox could be used in the same program with standard AWT labels, textfields and scrollbars. You could subclass the existing Swing UI, model, or change listener classes without having to reinvent the entire implementation. Swing also has the ability to replace these objects onthe-fly. 100% Java implementation of components Pluggable Look & Feel Lightweight components Uses MVC Archit ectur e Model represents the data View as a visual representation of the data Controller takes input and translates it to changes in data Three part s Component set (subclasses of JComponent) Support classes Interfaces
In Swing, classes that represent GUI components have names beginning with the letter J. Some examples are JButton, JLabel, and JSlider. Altogether there are more than 250 new classes and 75 interfaces in Swing — twice as many as in AWT. Java Swing class hierarchy The class JComponent, descended directly from Container, is the root class for most of Swing’s user interface components.
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Swing contains components that you’ll use to build a GUI. I am listing you some of the commonly used Swing components. To learn and understand these swing programs, AWT Programming knowledge is not required. Java Swing Examples
Below is a java swing code for the traditional Hello World program. Basically, the idea behind this Hello World program is to learn how to create a java program, compile and run it. To create your java source code you can use any editor( Text pad/Edit plus are my favorites) or you can use an IDE like Eclipse. import javax.swing.JFrame; import javax.swing.JLabel; //import statements //Check if window closes automatically. Otherwise add suitable code public class HelloWorldFrame extends JFrame { public static void main(String args[]) { new HelloWorldFrame(); } HelloWorldFrame() { JLabel jlbHelloWorld = new JLabel("Hello World"); add(jlbHelloWorld); this.setSize(100, 100); // pack(); setVisible(true); } }
Output
Note: Below are some links to java swing tutorials that forms a helping hand to get started with java programming swing.
JPanel is Swing’s version of the AWT class Panel and uses the same default layout, FlowLayout. JPanel is descended directly from JComponent. JFrame is Swing’s version of Frame and is descended directly from that class. The components added to the frame are referred to as its contents; these are managed by the contentPane. To add a component to a JFrame, we must use its contentPane instead. JI nternalFrame is confined to a visible area of a container it is placed in. It can be iconified , maximized and layered. JWindow is Swing’s version of Window and is descended directly from that class. Like Window, it uses BorderLayout by default. JDialog is Swing’s version of Dialog and is descended directly from that class. Like Dialog, it uses BorderLayout by default. Like JFrame and JWindow, JDialog contains a rootPane hierarchy including a contentPane, and it allows layered and glass panes. All dialogs are modal, which means the current thread is blocked until user interaction with it has been completed. JDialog class is intended as the basis for creating custom dialogs; however, some of the most common dialogs are provided through static methods in the class JOptionPane. JLabel , descended from JComponent, is used to create text labels. The abstract class AbstractButton extends class JComponent and provides a foundation for a family of button classes, including
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in JButton . JTextField allows editing of a single line of text. New features include the ability to justify the text left, right, or center, and to set the text’s font. JPasswordField (a direct subclass of JTextField) you can suppress the display of input. Each character entered can be replaced by an echo character. This allows confidential input for passwords, for example. By default, the echo character is the asterisk, *. JTextArea allows editing of multiple lines of text. JTextArea can be used in conjunction with class JScrollPane to achieve scrolling. The underlying JScrollPane can be forced to always or never have either the vertical or horizontal scrollbar; JButton is a component the user clicks to trigger a specific action. JRadioButton is similar to JCheckbox, except for the default icon for each class. A set of radio buttons can be associated as a group in which only one button at a time can be selected. JCheckBox is not a member of a checkbox group. A checkbox can be selected and deselected, and it also displays its current state. JComboBox is like a drop down box. You can click a drop-down arrow and select an option from a list. For example, when the component has focus, pressing a key that corresponds to the first character in some entry’s name selects that entry. A vertical scrollbar is used for longer lists. JList provides a scrollable set of items from which one or more may be selected. JList can be populated from an Array or Vector. JList does not support scrolling directly, instead, the list must be associated with a scrollpane. The view port used by the scroll pane can also have a user-defined border. JList actions are handled using ListSelectionListener. JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text and an image. JToolbar contains a number of components whose type is usually some kind of button which can also include separators to group related components within the toolbar. FlowLayout when used arranges swing components from left to right until there’s no more space available. Then it begins a new row below it and moves from left to right again. Each component in a FlowLayout gets as much space as it needs and no more. BorderLayout places swing components in the North, South, East, West and center of a container. You can add horizontal and vertical gaps between the areas. GridLayout is a layout manager that lays out a container’s components in a rectangular grid. The container is divided into equal-sized rectangles, and one component is placed in each rectangle. GridBagLayout is a layout manager that lays out a container’s components in a grid of cells with each component occupying one or more cells, called its display area. The display area aligns components vertically and horizontally, without requiring that the components be of the same size. JMenubar can contain several JMenu’s. Each of the JMenu’s can contain a series of JMenuItem ‘s that you can select. Swing provides support for pull-down and popup menus. Scroll able JPopupMenu is a scrollable popup menu that can be used whenever we have so many items in a popup menu that exceeds the screen visible height.
Java Sw ing Proj ect s Java Swing Calculator developed using Java Swing. It is a basic four-function calculator java program source code. Java Swing Address Book demonstrates how to create a simple free address book program using java swing and jdbc. Also you will learn to use the following swing components like Jbuttons, JFrames, JTextFields and Layout Manager (GridBagLayout).
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java JFr am e class exam pl e JFrame Java Swing Tutorial Explaining the JFrame class. The components added to the frame are referred to as its contents; these are managed by the contentPane. To add a component to a JFrame, we must use its contentPane instead.JFrame is a Window with border, title and buttons. When JFrame is set visible, an event dispatching thread is started. JFrame objects store several objects including a Container object known as the content pane. To add a component to a JFrame, add it to the content pane. JFrame Features It’s a window with title, border, (optional) menu bar and user-specified components. It can be moved, resized, iconified. It is not a subclass of JComponent. Delegates responsibility of managing user-specified components to a content pane, an instance of JPanel. Centering JFrame’s By default, a Jframe is displayed in the upper-left corner of the screen. To display a frame at a specified location, you can use the setLocation(x, y) method in the JFrame class. This method places the upper-left corner of a frame at location (x, y). The Swing API keeps improving with abstractions such as the setDefaultCloseOperation method for the JFrame Crating a JFrame Window Step 1: Construct an object of the JFrame class. Step 2: Set the size of the Jframe. Step 3: Set the title of the Jframe to appear in the title bar (title bar will be blank if no title is set). Step 4: Set the default close operation. When the user clicks the close button, the program stops running. Step 5: Make the Jframe visible. How to position JFrame on Screen? frame.setLocationRelativeTo( null );
JFr am e Sou r ce Code import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JFrameDemo { public static void main(String s[]) { JFrame frame = new JFrame("JFrame Source Demo"); // Add a window listner for close button frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); // This is an empty content area in the frame JLabel jlbempty = new JLabel(""); jlbempty.setPreferredSize(new Dimension(175, 100)); frame.getContentPane().add(jlbempty, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } }
Output
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in Download jFrame Source Code
Java JFram e Hierar chy javax.swing Class JFrame java.lang.Object java.awt.Component java.awt.Container java.awt.Window java.awt.Frame javax.swing.JFrame All Implemented Interfaces: Accessible, ImageObserver, MenuContainer, RootPaneContainer, Serializable, WindowConstants
JFram e Const ru cto r JFrame() Constructs a new frame that is initially invisible. JFrame(GraphicsConfiguration gc) Creates a Frame in the specified GraphicsConfiguration of a screen device and a blank title. JFrame(String title) Creates a new, initially invisible Frame with the specified title. JFrame(String title, GraphicsConfiguration gc) Creates a JFrame with the specified title and the specified GraphicsConfiguration of a screen device.
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java JI nt ernalFram e class exam ple JI nt ernalFrame Java Swing Tutorial Explaining the JInternalFrame class. A JInternalFrame is confined to a visible area of a container it is placed in. JInternalFrame a top level swing component that has a contentpane. It It It It
can can can can
be be be be
iconified — in this case the icon remains in the main application container. maximized — Frame consumes the main application closed using standard popup window controls layered
JI nt ernalFram e Sour ce Code import import import import import import import import
javax.swing.JInternalFrame; javax.swing.JDesktopPane; javax.swing.JMenu; javax.swing.JMenuItem; javax.swing.JMenuBar; javax.swing.JFrame; java.awt.event.*; java.awt.*;
public class JInternalFrameDemo extends JFrame { JDesktopPane jdpDesktop; static int openFrameCount = 0; public JInternalFrameDemo() { super("JInternalFrame Usage Demo"); // Make the main window positioned as 50 pixels from each edge of the // screen. int inset = 50; Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setBounds(inset, inset, screenSize.width - inset * 2, screenSize.height - inset * 2); // Add a Window Exit Listener addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); // Create and Set up the GUI. jdpDesktop = new JDesktopPane(); // A specialized layered pane to be used with JInternalFrames createFrame(); // Create first window setContentPane(jdpDesktop); setJMenuBar(createMenuBar()); // Make dragging faster by setting drag mode to Outline jdpDesktop.putClientProperty("JDesktopPane.dragMode", "outline"); } protected JMenuBar createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("Frame"); menu.setMnemonic(KeyEvent.VK_N); JMenuItem menuItem = new JMenuItem("New IFrame"); menuItem.setMnemonic(KeyEvent.VK_N); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createFrame(); } }); menu.add(menuItem); menuBar.add(menu); return menuBar; } protected void createFrame() { MyInternalFrame frame = new MyInternalFrame(); frame.setVisible(true); // Every JInternalFrame must be added to content pane using JDesktopPane jdpDesktop.add(frame); try { frame.setSelected(true); } catch (java.beans.PropertyVetoException e) { } } public static void main(String[] args) { JInternalFrameDemo frame = new JInternalFrameDemo(); frame.setVisible(true); } class MyInternalFrame extends JInternalFrame { static final int xPosition = 30, yPosition = 30; public MyInternalFrame() { super("IFrame #" + (++openFrameCount), true, // resizable true, // closable true, // maximizable true);// iconifiable setSize(300, 300); // Set the window's location. setLocation(xPosition * openFrameCount, yPosition * openFrameCount); } } }
Output
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Download JInternalFrame Source Code
Java JI nt ernalFrame Hierarchy javax.swing Class JInternalFrame java.lang.Object | +–java.awt.Component | +–java.awt.Container | +–javax.swing.JComponent | +–javax.swing.JInternalFrame All I mplemented I nterfaces: Accessible, ImageObserver, MenuContainer, RootPaneContainer, Serializable, WindowConstants
JI nt ernalFrame Const ruct or JInternalFrame() Creates a non-resizable, non-closable, non-maximizable, non-iconifiable JInternalFrame with no title. JInternalFrame(String title) Creates a non-resizable, non-closable, non-maximizable, non-iconifiable JInternalFrame with the specified title. JInternalFrame(String title, boolean resizable) Creates a non-closable, non-maximizable, non-iconifiable JInternalFrame with the specified title and resizability. JInternalFrame(String title, boolean resizable, boolean closable) Creates a non-maximizable, non-iconifiable JInternalFrame with the specified title, resizability, and closability. JInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable) Creates a non-iconifiable JInternalFrame with the specified title, resizability, closability, and maximizability. JInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable, boolean iconifiable) Creates a JInternalFrame with the specified title, resizability, closability, maximizability
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in JButton . JTextField allows editing of a single line of text. New features include the ability to justify the text left, right, or center, and to set the text’s font. JPasswordField (a direct subclass of JTextField) you can suppress the display of input. Each character entered can be replaced by an echo character. This allows confidential input for passwords, for example. By default, the echo character is the asterisk, *. JTextArea allows editing of multiple lines of text. JTextArea can be used in conjunction with class JScrollPane to achieve scrolling. The underlying JScrollPane can be forced to always or never have either the vertical or horizontal scrollbar; JButton is a component the user clicks to trigger a specific action. JRadioButton is similar to JCheckbox, except for the default icon for each class. A set of radio buttons can be associated as a group in which only one button at a time can be selected. JCheckBox is not a member of a checkbox group. A checkbox can be selected and deselected, and it also displays its current state. JComboBox is like a drop down box. You can click a drop-down arrow and select an option from a list. For example, when the component has focus, pressing a key that corresponds to the first character in some entry’s name selects that entry. A vertical scrollbar is used for longer lists. JList provides a scrollable set of items from which one or more may be selected. JList can be populated from an Array or Vector. JList does not support scrolling directly, instead, the list must be associated with a scrollpane. The view port used by the scroll pane can also have a user-defined border. JList actions are handled using ListSelectionListener. JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text and an image. JToolbar contains a number of components whose type is usually some kind of button which can also include separators to group related components within the toolbar. FlowLayout when used arranges swing components from left to right until there’s no more space available. Then it begins a new row below it and moves from left to right again. Each component in a FlowLayout gets as much space as it needs and no more. BorderLayout places swing components in the North, South, East, West and center of a container. You can add horizontal and vertical gaps between the areas. GridLayout is a layout manager that lays out a container’s components in a rectangular grid. The container is divided into equal-sized rectangles, and one component is placed in each rectangle. GridBagLayout is a layout manager that lays out a container’s components in a grid of cells with each component occupying one or more cells, called its display area. The display area aligns components vertically and horizontally, without requiring that the components be of the same size. JMenubar can contain several JMenu’s. Each of the JMenu’s can contain a series of JMenuItem ‘s that you can select. Swing provides support for pull-down and popup menus. Scroll able JPopupMenu is a scrollable popup menu that can be used whenever we have so many items in a popup menu that exceeds the screen visible height.
Java Sw ing Proj ect s Java Swing Calculator developed using Java Swing. It is a basic four-function calculator java program source code. Java Swing Address Book demonstrates how to create a simple free address book program using java swing and jdbc. Also you will learn to use the following swing components like Jbuttons, JFrames, JTextFields and Layout Manager (GridBagLayout).
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in device.
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java JLabel class exam pl e JLabels Java Swing Tutorial Explaining the JLabel Component. JLabel, descended from JComponent, is used to create text labels. A JLabel object provides text instructions or information on a GUI — display a single line of read-only text, an image or both text and image. We use a Swing JLabel when we need a user interface component that displays a message or an image. JØLabels Provide text instructions on a GUI lRead-only text lPrograms rarely change a label’s contents lClass JLabel (subclass of JComponent )
JLabel Sour ce Code import import import import import import import
java.awt.GridLayout; java.awt.event.WindowAdapter; java.awt.event.WindowEvent; javax.swing.JLabel; javax.swing.JPanel; javax.swing.JFrame; javax.swing.ImageIcon;
public class JlabelDemo extends JPanel { JLabel jlbLabel1, jlbLabel2, jlbLabel3; public JlabelDemo() { ImageIcon icon = new ImageIcon("java-swing-tutorial.JPG", "My Website"); // Creating an Icon setLayout(new GridLayout(3, 1)); // 3 rows, 1 column Panel having Grid Layout jlbLabel1 = new JLabel("Image with Text", icon, JLabel.CENTER); // We can position of the text, relative to the icon: jlbLabel1.setVerticalTextPosition(JLabel.BOTTOM); jlbLabel1.setHorizontalTextPosition(JLabel.CENTER); jlbLabel2 = new JLabel("Text Only Label"); jlbLabel3 = new JLabel(icon); // Label of Icon Only // Add labels to the Panel add(jlbLabel1); add(jlbLabel2); add(jlbLabel3); } public static void main(String[] args) { JFrame frame = new JFrame("jLabel Usage Demo"); frame.addWindowListener(new WindowAdapter() { // Shows code to Add Window Listener public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setContentPane(new JlabelDemo()); frame.pack(); frame.setVisible(true); } }
Output
Download jLabel Source Code
Java JLabel Hier archy javax.swing Class JLabel java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.JLabel All I mplemented I nterfaces: Accessible, ImageObserver, MenuContainer, Serializable, SwingConstants Direct Known Subclasses: BasicComboBoxRenderer, DefaultListCellRenderer, DefaultTableCellRenderer, DefaultTreeCellRenderer
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
JLabel Const ru ct or JLabel() Creates a JLabel instance with no image and with an empty string for the title. JLabel(I con image) Creates a JLabel instance with the specified image. JLabel(I con image, int horizontalAlignment) Creates a JLabel instance with the specified image and horizontal alignment. JLabel(String text) Creates a JLabel instance with the specified text. JLabel(Str ing t ext, I con icon, int horizontalAlignment) Creates a JLabel instance with the specified text, image, and horizontal alignment. JLabel(Str ing text , int horizontalAlignment) Creates a JLabel instance with the specified text and horizontal alignment.
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Download JInternalFrame Source Code
Java JI nt ernalFrame Hierarchy javax.swing Class JInternalFrame java.lang.Object | +–java.awt.Component | +–java.awt.Container | +–javax.swing.JComponent | +–javax.swing.JInternalFrame All I mplemented I nterfaces: Accessible, ImageObserver, MenuContainer, RootPaneContainer, Serializable, WindowConstants
JI nt ernalFrame Const ruct or JInternalFrame() Creates a non-resizable, non-closable, non-maximizable, non-iconifiable JInternalFrame with no title. JInternalFrame(String title) Creates a non-resizable, non-closable, non-maximizable, non-iconifiable JInternalFrame with the specified title. JInternalFrame(String title, boolean resizable) Creates a non-closable, non-maximizable, non-iconifiable JInternalFrame with the specified title and resizability. JInternalFrame(String title, boolean resizable, boolean closable) Creates a non-maximizable, non-iconifiable JInternalFrame with the specified title, resizability, and closability. JInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable) Creates a non-iconifiable JInternalFrame with the specified title, resizability, closability, and maximizability. JInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable, boolean iconifiable) Creates a JInternalFrame with the specified title, resizability, closability, maximizability
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in contentPane.add(scrollPane, gridCons2); } public void actionPerformed(ActionEvent evt) { String text = jtfInput.getText(); jtAreaOutput.append(text + newline); jtfInput.selectAll(); } public static void main(String[] args) { JTextFieldDemo2 jtfTfDemo = new JTextFieldDemo2(); jtfTfDemo.pack(); jtfTfDemo.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); jtfTfDemo.setVisible(true); } }
Output
Download jTextField Source Code
Java JText Field Hier archy javax.swing java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.text.JTextComponent javax.swing.JTextField All I mplemented I nterfaces: Accessible, ImageObserver, MenuContainer, Scrollable, Serializable, SwingConstants Direct Known Subclasses: DefaultTreeCellEditor.DefaultTextField, JFormattedTextField, JPasswordField
JText Field Const ru cto r JTextField() Constructs a new TextField. JTextField(Document doc, String text, int columns) Constructs a new JTextField that uses the given text storage model and the given number of columns. JTextField(int columns) Constructs a new empty TextField with the specified n umber of columns. JTextField(String text) Constructs a new TextField initialized with the specified text. JTextField(String text, int columns) Constructs a new TextField initialized with the specified text and columns.
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in device.
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in JPasswordField(int columns) Constructs a new empty JPasswordField with the specified number of columns. JPasswordField(String text) Constructs a new JPasswordField initialized with the specified text. JPasswordField(String text, int columns) Constructs a new JPasswordField initialized with the specified text and columns.
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java JText Area class ex am ple JTextArea
Java Swing Tutorial Explaining the JTextArea Component. JTextArea allows editing of multiple lines of text. JTextArea can be used in conjunction with class JScrollPane to achieve scrolling. The underlying JScrollPane can be forced to always or never have either the vertical or horizontal scrollbar.
JText Area Source Code import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JTextAreaDemo extends JFrame implements ActionListener { JTextField jtfInput; JTextArea jtAreaOutput; String newline = "\n"; public JTextAreaDemo() { createGui(); } public void createGui() { jtfInput = new JTextField(20); jtfInput.addActionListener(this); jtAreaOutput = new JTextArea(5, 20); jtAreaOutput.setCaretPosition(jtAreaOutput.getDocument() .getLength()); jtAreaOutput.setEditable(false); JScrollPane scrollPane = new JScrollPane(jtAreaOutput, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); GridBagLayout gridBag = new GridBagLayout(); Container contentPane = getContentPane(); contentPane.setLayout(gridBag); GridBagConstraints gridCons1 = new GridBagConstraints(); gridCons1.gridwidth = GridBagConstraints.REMAINDER; gridCons1.fill = GridBagConstraints.HORIZONTAL; contentPane.add(jtfInput, gridCons1); GridBagConstraints gridCons2 = new GridBagConstraints(); gridCons2.weightx = 1.0; gridCons2.weighty = 1.0; contentPane.add(scrollPane, gridCons2); } public void actionPerformed(ActionEvent evt) { String text = jtfInput.getText(); jtAreaOutput.append(text + newline); jtfInput.selectAll(); } public static void main(String[] args) { JTextAreaDemo jtfTfDemo = new JTextAreaDemo(); jtfTfDemo.pack(); jtfTfDemo.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); jtfTfDemo.setVisible(true); } }
Output
Download JTextArea Source Code
Java JText Area Hierarchy javax.swing Class JTextArea java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.text.JTextComponent javax.swing.JTextField All I mplemented I nterfaces: Accessible, ImageObserver, MenuContainer, Scrollable, Serializable, SwingConstants Direct Known Subclasses: DefaultTreeCellEditor.DefaultTextField, JFormattedTextField, JPasswordField
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java JText Field class exam ple JTextField Java Swing Tutorial Explaining the JTextField Component. JTextField allows editing/displaying of a single line of text. New features include the ability to justify the text left, right, or center, and to set the text’s font. When the user types data into them and presses the Enter key, an action event occurs. If the program registers an event listener, the listener processes the event and can use the data in the text field at the time of the event in the program. JTextField is an input area where the user can type in characters. If you want to let the user enter multiple lines of text, you cannot use Jtextfield’s unless you create several of them. The solution is to use JTextArea, which enables the user to enter multiple lines of text.
JTextField Source Code // A program to demonstrate the use of JTextFields's //Import Statements import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JTextFieldDemo extends JFrame { //Class Declarations JTextField jtfText1, jtfUneditableText; String disp = ""; TextHandler handler = null; //Constructor public JTextFieldDemo() { super("TextField Test Demo"); Container container = getContentPane(); container.setLayout(new FlowLayout()); jtfText1 = new JTextField(10); jtfUneditableText = new JTextField("Uneditable text field", 20); jtfUneditableText.setEditable(false); container.add(jtfText1); container.add(jtfUneditableText); handler = new TextHandler(); jtfText1.addActionListener(handler); jtfUneditableText.addActionListener(handler); setSize(325, 100); setVisible(true); } //Inner Class TextHandler private class TextHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getSource() == jtfText1) { disp = "text1 : " + e.getActionCommand(); } else if (e.getSource() == jtfUneditableText) { disp = "text3 : " + e.getActionCommand(); } JOptionPane.showMessageDialog(null, disp); } } //Main Program that starts Execution public static void main(String args[]) { JTextFieldDemo test = new JTextFieldDemo(); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }// End of class TextFieldTest
Output
Download jTextField Source Code
Anot her Ex am ple: JText Field Sour ce Code public class JTextFieldDemo2 extends JFrame implements ActionListener { JTextField jtfInput; JTextArea jtAreaOutput; String newline = "\n"; public JTextFieldDemo2() { createGui(); } public void createGui() { jtfInput = new JTextField(20); jtfInput.addActionListener(this); jtAreaOutput = new JTextArea(5, 20); jtAreaOutput.setEditable(false); JScrollPane scrollPane = new JScrollPane(jtAreaOutput, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); GridBagLayout gridBag = new GridBagLayout(); Container contentPane = getContentPane(); contentPane.setLayout(gridBag); GridBagConstraints gridCons1 = new GridBagConstraints(); gridCons1.gridwidth = GridBagConstraints.REMAINDER; gridCons1.fill = GridBagConstraints.HORIZONTAL; contentPane.add(jtfInput, gridCons1); GridBagConstraints gridCons2 = new GridBagConstraints(); gridCons2.weightx = 1.0; gridCons2.weighty = 1.0;
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
JText Area Constr uct or JTextArea() Constructs a new TextArea. JTextArea(Document doc) Constructs a new JTextArea with the given document model, and defaults for all of the other arguments (null, 0, 0). JTextArea(Document doc, String text, int rows, int columns) Constructs a new JTextArea with the specified number of rows and columns, and the given model. JTextArea(int row s, int columns) Constructs a new empty TextArea with the specified number of rows and columns. JTextArea(String text ) Constructs a new TextArea with the specified text displayed. JTextArea(String t ext, int row s, int columns) Constructs a new TextArea with the specified text and number of rows and columns.
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java JBut t on class ex am ple JButton Java Swing Tutorial Explaining the JButton Component. The abstract class AbstractButton extends class JComponent and provides a foundation for a family of button classes, including JButton. A button is a component the user clicks to trigger a specific action. There are several types of buttons in Java, all are subclasses of AbstractButton. command buttons: is created with class JButton. It generates ActionEvent. toggle buttons: have on/off or true/false values. check boxes: a group of buttons. It generates ItemEvent. radio buttons: a group of buttons in which only one can be selected. It generates ItemEvent.
JBut t on Sour ce Code import import import import import import import import import
java.awt.event.ActionEvent; java.awt.event.ActionListener; java.awt.event.KeyEvent; java.net.URL; javax.swing.AbstractButton; javax.swing.ImageIcon; javax.swing.JButton; javax.swing.JFrame; javax.swing.JPanel;
public class JButtonDemo extends JPanel implements ActionListener { protected static JButton jbnLeft, jbnMiddle, jbnRight; public JButtonDemo() { // Create Icons that can be used with the jButtons ImageIcon leftButtonIcon = createImageIcon("rightarrow.JPG"); ImageIcon middleButtonIcon = createImageIcon("java-swing-tutorial.JPG"); ImageIcon rightButtonIcon = createImageIcon("leftarrow.JPG"); jbnLeft = new JButton("Disable centre button", leftButtonIcon); jbnLeft.setVerticalTextPosition(AbstractButton.CENTER); jbnLeft.setHorizontalTextPosition(AbstractButton.LEADING); jbnLeft.setMnemonic(KeyEvent.VK_D); // Alt- D clicks the button jbnLeft.setActionCommand("disable"); jbnLeft.setToolTipText("disable the Centre button."); // Adding Tool // tips jbnMiddle = new JButton("Centre button", middleButtonIcon); jbnMiddle.setVerticalTextPosition(AbstractButton.BOTTOM); jbnMiddle.setHorizontalTextPosition(AbstractButton.CENTER); jbnMiddle.setMnemonic(KeyEvent.VK_M); // Alt- M clicks the button jbnMiddle.setToolTipText("Centre button"); jbnRight = new JButton("Enable centre button", rightButtonIcon); // Use the default text position of CENTER, TRAILING (RIGHT). jbnRight.setMnemonic(KeyEvent.VK_E); // Alt- E clicks the button jbnRight.setActionCommand("enable"); jbnRight.setEnabled(false); // Disable the Button at creation time // Listen for actions on Left and Roght Buttons jbnLeft.addActionListener(this); jbnRight.addActionListener(this); jbnRight.setToolTipText("Enable the Centre button."); // Add Components to the frame, using the default FlowLayout. add(jbnLeft); add(jbnMiddle); add(jbnRight); } public void actionPerformed(ActionEvent e) { if ("disable".equals(e.getActionCommand())) { jbnMiddle.setEnabled(false); jbnLeft.setEnabled(false); jbnRight.setEnabled(true); } else { jbnMiddle.setEnabled(true); jbnLeft.setEnabled(true); jbnRight.setEnabled(false); } } // Returns an ImageIcon, or null if the path was invalid. protected static ImageIcon createImageIcon(String path) { URL imgURL = JButtonDemo.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("Couldn't find image in system: " + path); return null; } } // Create the GUI and show it. private static void createGUI() { JFrame.setDefaultLookAndFeelDecorated(true); // Create and set up the frame. JFrame frame = new JFrame("jButton usage demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create and set up the content pane. JButtonDemo buttonContentPane = new JButtonDemo(); buttonContentPane.setOpaque(true); // content panes must be opaque frame.getRootPane().setDefaultButton(jbnLeft); frame.setContentPane(buttonContentPane); // Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createGUI(); } }); } }
Output
Download jButton Source Code
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Anot her Ex amp le: JBut t on Sour ce Code import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JButtonDemo2 { JFrame jtfMainFrame; JButton jbnButton1, jbnButton2; JTextField jtfInput; JPanel jplPanel; public JButtonDemo2() { jtfMainFrame = new JFrame("Which Button Demo"); jtfMainFrame.setSize(50, 50); jbnButton1 = new JButton("Button 1"); jbnButton2 = new JButton("Button 2"); jtfInput = new JTextField(20); jplPanel = new JPanel(); jbnButton1.setMnemonic(KeyEvent.VK_I); //Set ShortCut Keys jbnButton1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jtfInput.setText("Button 1!"); } }); jbnButton2.setMnemonic(KeyEvent.VK_I); jbnButton2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jtfInput.setText("Button 2!"); } }); jplPanel.setLayout(new FlowLayout()); jplPanel.add(jtfInput); jplPanel.add(jbnButton1); jplPanel.add(jbnButton2); jtfMainFrame.getContentPane().add(jplPanel, BorderLayout.CENTER); jtfMainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jtfMainFrame.pack(); jtfMainFrame.setVisible(true); } public static void main(String[] args) { // Set the look and feel to Java Swing Look try { UIManager.setLookAndFeel(UIManager .getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } JButtonDemo2 application = new JButtonDemo2(); } }
Output
Download jButton Source Code
Java JButt on Hierarchy javax.swing Class JBut t on java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.AbstractButton javax.swing.JButton All I mplemented I nterfaces: Accessible, ImageObserver, ItemSelectable, MenuContainer, Serializable, SwingConstants Direct Known Subclasses: BasicArrowButton, MetalComboBoxButton
JBut t on Const ruct or JButton() Creates a button with no set text or icon. JButton(Action a) Creates a button where properties are taken from the Action supplied. JButton(Icon icon) Creates a button with an icon. JButton(String text) Creates a button with text. JButton(String text, Icon icon)
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in Creates a button with initial text and an icon.
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java JCheckBox class exam pl e JCheckBox Java Swing Tutorial Explaining the JCheckBox Component. JCheckBox is not a member of a checkbox group. A checkbox can be selected and deselected, and it also displays its current state. JCheckBox Source Code Note: Help for getting the below source code is taken from Java Sun Website import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JCheckBoxDemo extends JPanel { //Four accessory choices provide for 16 different combinations JCheckBox jcbChin; JCheckBox jcbGlasses; JCheckBox jcbHair; JCheckBox jcbTeeth; /* The image for each combination is contained in a separate image file whose name indicates the accessories. The filenames are "geek-XXXX.gif" where XXXX can be one * of the following 16 choices. */ StringBuffer choices; JLabel jlbPicture; CheckBoxListener myListener = null; public JCheckBoxDemo() { // Add an item listener for each of the check boxes. // This is the listener class which contains business logic myListener = new CheckBoxListener(); // Create check boxes with default selection true jcbChin = new JCheckBox("Chin"); jcbChin.setMnemonic(KeyEvent.VK_C); //Alt+C Checks/Unchecks the check Box jcbChin.setSelected(true); jcbChin.addItemListener(myListener); jcbGlasses = new JCheckBox("Glasses"); jcbGlasses.setMnemonic(KeyEvent.VK_G); //Alt+G Checks/Unchecks the check Box jcbGlasses.setSelected(true); jcbGlasses.addItemListener(myListener); jcbHair = new JCheckBox("Hair"); jcbHair.setMnemonic(KeyEvent.VK_H); //Alt+H Checks/Unchecks the check Box jcbHair.setSelected(true); jcbHair.addItemListener(myListener); jcbTeeth = new JCheckBox("Teeth"); jcbTeeth.setMnemonic(KeyEvent.VK_T); //Alt+T Checks/Unchecks the check Box jcbTeeth.setSelected(true); jcbTeeth.addItemListener(myListener); // Indicates what's on the geek. choices = new StringBuffer("cght");//Default Image has all the parts. // Set up the picture label jlbPicture = new JLabel(new ImageIcon("geek-" + choices.toString().trim() + ".gif")); jlbPicture.setToolTipText(choices.toString().trim()); // Put the check boxes in a column in a panel JPanel jplCheckBox = new JPanel(); jplCheckBox.setLayout(new GridLayout(0, 1)); jplCheckBox.add(jcbChin); jplCheckBox.add(jcbGlasses); jplCheckBox.add(jcbHair); jplCheckBox.add(jcbTeeth);
//0 rows, 1 Column
setLayout(new BorderLayout()); add(jplCheckBox, BorderLayout.WEST); add(jlbPicture, BorderLayout.CENTER); setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); } //Listens to the check boxes events class CheckBoxListener implements ItemListener { public void itemStateChanged(ItemEvent e) { int index = 0; char c = '-'; Object source = e.getSource(); if (source == jcbChin) { index = 0; c = 'c'; } else if (source == jcbGlasses) { index = 1; c = 'g'; } else if (source == jcbHair) { index = 2; c = 'h'; } else if (source == jcbTeeth) { index = 3; c = 't'; } if (e.getStateChange() == ItemEvent.DESELECTED) c = '-'; choices.setCharAt(index, c); jlbPicture.setIcon(new ImageIcon("geek- " + choices.toString().trim() + ".gif")); jlbPicture.setToolTipText(choices.toString()); } } public static void main(String s[]) { JFrame frame = new JFrame("JCheckBox Usage Demo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setContentPane(new JCheckBoxDemo()); frame.pack(); frame.setVisible(true); } }
Output
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Download jCheckBox Source Code
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java JCom boBox class exam ple JComboBox Java Swing Tutorial Explaining the JComboBox Component. JComboBox is like a drop down box — you can click a drop-down arrow and select an option from a list. It generates ItemEvent. For example, when the component has focus, pressing a key that corresponds to the first character in some entry’s name selects that entry. A vertical scrollbar is used for longer lists.
JCom boBox Sou rce Code import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JComboBoxDemo extends JPanel { JLabel jlbPicture; public JComboBoxDemo() { String[] comboTypes = { "Numbers", "Alphabets", "Symbols" }; // Create the combo box, and set 2nd item as Default JComboBox comboTypesList = new JComboBox(comboTypes); comboTypesList.setSelectedIndex(2); comboTypesList.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox jcmbType = (JComboBox) e.getSource(); String cmbType = (String) jcmbType.getSelectedItem(); jlbPicture.setIcon(new ImageIcon("" + cmbType.trim().toLowerCase() + ".jpg")); } }); // Set up the picture jlbPicture = new JLabel(new ImageIcon("" + comboTypes[comboTypesList.getSelectedIndex()] + ".jpg")); jlbPicture.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0)); jlbPicture.setPreferredSize(new Dimension(177, 122 + 10)); // Layout the demo setLayout(new BorderLayout()); add(comboTypesList, BorderLayout.NORTH); add(jlbPicture, BorderLayout.SOUTH); setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); } public static void main(String s[]) { JFrame frame = new JFrame("JComboBox Usage Demo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setContentPane(new frame.pack(); frame.setVisible(true);
JComboBoxDemo());
} }
Output
Download JComboBox Source Code
Anot her Ex am ple: JCom boBox Sour ce Code import import import import import import
java.awt.*; java.awt.event.*; javax.swing.*; javax.swing.border.*; java.util.*; java.text.*;
public class DateComboBoxDemo extends JPanel { static JLabel String public
JFrame frame; jlbResult; datePattern_Current; DateComboBoxDemo() { String[] datePatterns = { "dd MMMMM yyyy", "dd.MM.yy", "MM/dd/yy", "yyyy.MM.dd G 'at' hh:mm:ss z", "EEE, MMM d, ''yy", "h:mm a", "H:mm:ss:SSS", "K:mm a,z", "yyyy.MMMMM.dd GGG hh:mm aaa" }; datePattern_Current = datePatterns[0]; // Set up the UI for selecting a pattern.
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in JLabel jlbHeading = new JLabel( "Enter Date pattern /Select from list:"); JComboBox patternList = new JComboBox(datePatterns); patternList.setEditable(true); patternList.setAlignmentX(Component.LEFT_ALIGNMENT); patternList.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox jcmbDates = (JComboBox) e.getSource(); String seletedDate = (String) jcmbDates.getSelectedItem(); datePattern_Current = seletedDate; showDateinLabel(); } }); // Create the UI for displaying result JLabel jlbResultHeading = new JLabel("Current Date/Time", JLabel.LEFT); jlbResult = new JLabel(" "); jlbResult.setForeground(Color.black); jlbResult.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(Color.black), BorderFactory .createEmptyBorder(5, 5, 5, 5))); // Lay out everything JPanel jpnDate = new JPanel(); jpnDate.setLayout(new BoxLayout(jpnDate, BoxLayout.Y_AXIS)); jpnDate.add(jlbHeading); jpnDate.add(patternList); JPanel jpnResults = new JPanel(); jpnResults.setLayout(new GridLayout(0, 1)); jpnResults.add(jlbResultHeading); jpnResults.add(jlbResult); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); jpnDate.setAlignmentX(Component.LEFT_ALIGNMENT); jpnResults.setAlignmentX(Component.LEFT_ALIGNMENT); add(jpnDate); add(Box.createRigidArea(new Dimension(0, 10))); add(jpnResults); setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); showDateinLabel(); } // constructor /** Formats and displays today's date. */ public void showDateinLabel() { Date today = new Date(); SimpleDateFormat formatter = new SimpleDateFormat( datePattern_Current); try { String dateString = formatter.format(today); jlbResult.setForeground(Color.black); jlbResult.setText(dateString); } catch (IllegalArgumentException e) { jlbResult.setForeground(Color.red); jlbResult.setText("Error: " + e.getMessage()); } } public static void main(String s[]) { frame = new JFrame("JComboBox Usage Demo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setContentPane(new frame.pack(); frame.setVisible(true);
DateComboBoxDemo());
} }
Output Download JComboBox Source Code
Java JComb oBox Hier archy javax.swing Class JComboBox java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.JComboBox All I mplemented I nterfaces: Accessible, ActionListener, EventListener, ImageObserver, ItemSelectable, L istDataListener, MenuContainer, Serializable
JComboBox Constructor JComboBox() Creates a JComboBox with a default data model. JComboBox(ComboBoxModel aModel) Creates a JComboBox that takes it’s items from an existing ComboBoxModel. JComboBox(Object[ ] items) Creates a JComboBox that contains the elements in the specified array. JComboBox( Vect or it ems) Creates a JComboBox that contains the elements in the specified Vector.
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Editable JComboBox Java Swing Tutorial Explaining the Edit able JCom boBox Component. JComboBox is like a drop down box — you can click a drop-down arrow and select an option from a list. It generates ItemEvent. For example, when the component has focus, pressing a key that corresponds to the first character in some entry’s name selects that entry. A vertical scrollbar is used for longer lists.
Edi t abl e JCom bo Box Sour ce Code Oct 30, 2006 by Hemanth JComboBox’s getSelectedItem() is used to get what is entered into the control. However when a user types something into the JCombBox rather than selecting an item from the list and does not hit “enter” after entering the text, the getSelectedItem() does not return what is currently entered in the field (it instead gets the last selected item). The users often do not know to hit enter when they change the value in the JComboBox so they just click an “OK” button on the panel (signifying a save) and the value in the JComboBox is not properly saved. But the below program overcomes this probelm by simulating an enter key in the JComboBox or get the value that has been manually entered when the user does not hot “enter” in the JComboBox. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JComboBoxEditable extends JFrame { JComboBox jcmbNames; public JComboBoxEditable() { String[] names = { "hemanth", "Shawn", "Hunter", "Undertaker", "Big Show" }; jcmbNames = new JComboBox( names ); jcmbNames.setEditable( true ); getContentPane().add(jcmbNames, BorderLayout.NORTH); JButton jbnOk = new JButton("Ok"); getContentPane().add(jbnOk, BorderLayout.SOUTH); //
Print Name of the Selected Combo Box Item to Console when OK button is pressed jbnOk.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println( jcmbNames.getSelectedItem() ); } });
//
Print Name of the Selected Combo Box Item to Console when Enter is pressed jcmbNames.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println( jcmbNames.getSelectedItem() ); } }); } public static void main(String[] args) { JComboBoxEditable frame = new JComboBoxEditable(); frame.setDefaultCloseOperation( EXIT_ON_CLOSE ); frame.pack(); frame.setLocationRelativeTo( null ); frame.setVisible( true ); }
}
Output
Download Editable JComboBox Source Code
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java JList class ex am pl e JList Java Swing Tutorial Explaining the JList Component. JList provides a scrollable set of items from which one or more may be selected. JList can be populated from an Array or Vector. JList does not support scrolling directly—instead, the list must be associated with a scrollpane. The view port used by the scrollpane can also have a user-defined border. JList actions are handled using ListSelectionListener.
JList Sour ce Code import import import import import
javax.swing.*; javax.swing.event.ListSelectionEvent; javax.swing.event.ListSelectionListener; java.awt.*; java.awt.event.*;
public class JListDemo extends JFrame { JList list; String[] listColorNames = { "black", "blue", "green", "yellow", "white" }; Color[] listColorValues = { Color.BLACK, Color.BLUE, Color.GREEN, Color.YELLOW, Color.WHITE }; Container contentpane; public JListDemo() { super("List Source Demo"); contentpane = getContentPane(); contentpane.setLayout(new FlowLayout()); list = new JList(listColorNames); list.setSelectedIndex(0); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); contentpane.add(new JScrollPane(list)); list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { contentpane.setBackground(listColorValues[list .getSelectedIndex()]); } }); setSize(200, 200); setVisible(true); } public static void main(String[] args) { JListDemo test = new JListDemo(); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
Output
Download JList Source Code
Java JList Class javax.swing Class Class JList java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.JList All Implemented Interfaces: Accessible, ImageObserver, MenuContainer, Scrollable, Serializable
JList Constructor JList() Constructs a JList with an empty model. JList(ListModel dataModel) Constructs a JList that displays the elements in the specified, non-null model. JList(Object[] listData) Constructs a JList that displays the elements in the specified array. JList(Vector listData)
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java JCom boBox class exam ple JComboBox Java Swing Tutorial Explaining the JComboBox Component. JComboBox is like a drop down box — you can click a drop-down arrow and select an option from a list. It generates ItemEvent. For example, when the component has focus, pressing a key that corresponds to the first character in some entry’s name selects that entry. A vertical scrollbar is used for longer lists.
JCom boBox Sou rce Code import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JComboBoxDemo extends JPanel { JLabel jlbPicture; public JComboBoxDemo() { String[] comboTypes = { "Numbers", "Alphabets", "Symbols" }; // Create the combo box, and set 2nd item as Default JComboBox comboTypesList = new JComboBox(comboTypes); comboTypesList.setSelectedIndex(2); comboTypesList.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox jcmbType = (JComboBox) e.getSource(); String cmbType = (String) jcmbType.getSelectedItem(); jlbPicture.setIcon(new ImageIcon("" + cmbType.trim().toLowerCase() + ".jpg")); } }); // Set up the picture jlbPicture = new JLabel(new ImageIcon("" + comboTypes[comboTypesList.getSelectedIndex()] + ".jpg")); jlbPicture.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0)); jlbPicture.setPreferredSize(new Dimension(177, 122 + 10)); // Layout the demo setLayout(new BorderLayout()); add(comboTypesList, BorderLayout.NORTH); add(jlbPicture, BorderLayout.SOUTH); setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); } public static void main(String s[]) { JFrame frame = new JFrame("JComboBox Usage Demo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setContentPane(new frame.pack(); frame.setVisible(true);
JComboBoxDemo());
} }
Output
Download JComboBox Source Code
Anot her Ex am ple: JCom boBox Sour ce Code import import import import import import
java.awt.*; java.awt.event.*; javax.swing.*; javax.swing.border.*; java.util.*; java.text.*;
public class DateComboBoxDemo extends JPanel { static JLabel String public
JFrame frame; jlbResult; datePattern_Current; DateComboBoxDemo() { String[] datePatterns = { "dd MMMMM yyyy", "dd.MM.yy", "MM/dd/yy", "yyyy.MM.dd G 'at' hh:mm:ss z", "EEE, MMM d, ''yy", "h:mm a", "H:mm:ss:SSS", "K:mm a,z", "yyyy.MMMMM.dd GGG hh:mm aaa" }; datePattern_Current = datePatterns[0]; // Set up the UI for selecting a pattern.
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in Constructs a JList that displays the elements in the specified Vector.
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in All Implemented Interfaces: Accessible, ImageObserver, MenuContainer, Serializable, SwingConstants
JTabbedPane Const ru cto r JTabbedPane() Creates an empty TabbedPane with a default tab placement of JTabbedPane.TOP. JTabbedPane(int tabPlacement) Creates an empty TabbedPane with the specified tab placement of either: JTabbedPane.TOP, JTabbedPane.BOTTOM, JTabbedPane.LEFT, or JTabbedPane.RIGHT. JTabbedPane(int tabPlacement, int tabLayoutPolicy) Creates an empty TabbedPane with the specified tab placement and tab layout policy.
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java JList class ex am pl e JList Java Swing Tutorial Explaining the JList Component. JList provides a scrollable set of items from which one or more may be selected. JList can be populated from an Array or Vector. JList does not support scrolling directly—instead, the list must be associated with a scrollpane. The view port used by the scrollpane can also have a user-defined border. JList actions are handled using ListSelectionListener.
JList Sour ce Code import import import import import
javax.swing.*; javax.swing.event.ListSelectionEvent; javax.swing.event.ListSelectionListener; java.awt.*; java.awt.event.*;
public class JListDemo extends JFrame { JList list; String[] listColorNames = { "black", "blue", "green", "yellow", "white" }; Color[] listColorValues = { Color.BLACK, Color.BLUE, Color.GREEN, Color.YELLOW, Color.WHITE }; Container contentpane; public JListDemo() { super("List Source Demo"); contentpane = getContentPane(); contentpane.setLayout(new FlowLayout()); list = new JList(listColorNames); list.setSelectedIndex(0); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); contentpane.add(new JScrollPane(list)); list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { contentpane.setBackground(listColorValues[list .getSelectedIndex()]); } }); setSize(200, 200); setVisible(true); } public static void main(String[] args) { JListDemo test = new JListDemo(); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
Output
Download JList Source Code
Java JList Class javax.swing Class Class JList java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.JList All Implemented Interfaces: Accessible, ImageObserver, MenuContainer, Scrollable, Serializable
JList Constructor JList() Constructs a JList with an empty model. JList(ListModel dataModel) Constructs a JList that displays the elements in the specified, non-null model. JList(Object[] listData) Constructs a JList that displays the elements in the specified array. JList(Vector listData)
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in jtfButton.setEditable(false); jtfButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { displayInTextArea("TextField component can also be placed"); } }); jtbToolBar.add(jtfButton); } protected void displayInTextArea(String actionDescription) { textArea.append(actionDescription + newline); } public static void main(String[] args) { JToolBarDemo jtfToolbar = new JToolBarDemo(); // Extends Frame. jtfToolbar.pack(); jtfToolbar.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); jtfToolbar.setVisible(true); } }
Output
Download JToolbar Source Code
Java JToolBar Hierar chy javax.swing Class JToolBar java.lang.Object java.awt.BorderLayout All Implemented Interfaces: LayoutManager, LayoutManager2, Serializable
JToolBar Const ru ct or JToolBar() Creates a new tool bar; orientation defaults to HORIZONTAL. JToolBar(int orientation) Creates a new tool bar with the specified orientation. JToolBar(String name) Creates a new tool bar with the specified name. JToolBar(String name, int orientation) Creates a new tool bar with a specified name and orientation.
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java JTabbedPane class ex am pl e JTabbedPane Java Swing Tutorial Explaining the JTabbedPane Component. A JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text and an image. The shape of a t ab and t he w ay in w hich t he selected t ab is displayed varies by Look and Feel.
JTabb edPane Sour ce Code import import import import import import import
javax.swing.JTabbedPane; javax.swing.ImageIcon; javax.swing.JLabel; javax.swing.JPanel; javax.swing.JFrame; java.awt.*; java.awt.event.*;
public class JTabbedPaneDemo extends JPanel { public JTabbedPaneDemo() { ImageIcon icon = new ImageIcon("java-swing-tutorial.JPG"); JTabbedPane jtbExample = new JTabbedPane(); JPanel jplInnerPanel1 = createInnerPanel("Tab 1 Contains Tooltip and Icon"); jtbExample.addTab("One", icon, jplInnerPanel1, "Tab 1"); jtbExample.setSelectedIndex(0); JPanel jplInnerPanel2 = createInnerPanel("Tab 2 Contains Icon only"); jtbExample.addTab("Two", icon, jplInnerPanel2); JPanel jplInnerPanel3 = createInnerPanel("Tab 3 Contains Tooltip and Icon"); jtbExample.addTab("Three", icon, jplInnerPanel3, "Tab 3"); JPanel jplInnerPanel4 = createInnerPanel("Tab 4 Contains Text only"); jtbExample.addTab("Four", jplInnerPanel4); // Add the tabbed pane to this panel. setLayout(new GridLayout(1, 1)); add(jtbExample); } protected JPanel createInnerPanel(String text) { JPanel jplPanel = new JPanel(); JLabel jlbDisplay = new JLabel(text); jlbDisplay.setHorizontalAlignment(JLabel.CENTER); jplPanel.setLayout(new GridLayout(1, 1)); jplPanel.add(jlbDisplay); return jplPanel; } public static void main(String[] args) { JFrame frame = new JFrame("TabbedPane Source Demo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.getContentPane().add(new JTabbedPaneDemo(), BorderLayout.CENTER); frame.setSize(400, 125); frame.setVisible(true); } }
Output
Download JTabbedPane Source Code JTabbedPane question When I use a JTabbedPane and want to listen to which tab is being clicked, which listerner should I use? Answer: ChangeListener
Java JTabbedPane Hierarchy javax.swing Class JTabbedPane java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.JTabbedPane
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java BorderLayout class ex amp le BorderLayout Java Swing Tutorial Explaining the BorderLayout . BorderLayout places swing components in the North, South, East, West and center of a container. All extra space is placed in the center area. You can add horizontal and vertical gaps between the areas. Every content pane is initialized to use a BorderLayout. Components are added to a BorderLayout by using the add method. JFrame’s content pane default layout manager: BorderLayout. In BorderLayout, a component’s position is specified by a second argument to add.
Bor derLayout Sour ce Code /* * BorderLayoutDemo.java is a 1.4 application that requires no other files. */ import import import import import import
java.awt.BorderLayout; java.awt.Container; java.awt.Dimension; javax.swing.JButton; javax.swing.JFrame; javax.swing.JLabel;
public class BorderLayoutDemo { public static boolean RIGHT_TO_LEFT = false; // //
public static void addComponentsToPane(Container contentPane) { Use BorderLayout. Default empty constructor with no horizontal and vertical gaps contentPane.setLayout(new BorderLayout(5,5)); if (!(contentPane.getLayout() instanceof BorderLayout)) { contentPane.add(new JLabel("Container doesn't use BorderLayout!")); return; } if (RIGHT_TO_LEFT) { contentPane.setComponentOrientation( java.awt.ComponentOrientation.RIGHT_TO_LEFT); } JButton jbnSampleButtons = new JButton("Button 1 (PAGE_START)"); contentPane.add(jbnSampleButtons, BorderLayout.PAGE_START); jbnSampleButtons = new JButton("Button 2 (CENTER)"); jbnSampleButtons.setPreferredSize(new Dimension(200, 100)); contentPane.add(jbnSampleButtons, BorderLayout.CENTER); jbnSampleButtons = new JButton("Button 3 (LINE_START)"); contentPane.add(jbnSampleButtons, BorderLayout.LINE_START); jbnSampleButtons = new JButton("Long-Named Button 4 (PAGE_END)"); contentPane.add(jbnSampleButtons, BorderLayout.PAGE_END); jbnSampleButtons = new JButton("5 (LINE_END)"); contentPane.add(jbnSampleButtons, BorderLayout.LINE_END); } private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("BorderLayout Source Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Set up the content pane and add swing components to it addComponentsToPane(frame.getContentPane()); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }
}
output
Download BorderLayout Source Code
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java JTool Bar class exam pl e JToolbar Java Swing Tutorial Explaining the JToolBar Component. A JToolbar contains a number of components whose type is usually some kind of button which can also include separators to group related components within the toolbar. The toolbar can be docked against any of the four edges of a container (panel or a frame). A toolbar can also be made to float. Toolbars uses BoxLayout, which arranges components in one horizontal row/ vertical column. This layout manager does not force each component to have the same height or width; instead, it uses their preferred height or width, and attempts to align them. You can adjust the resulting alignment by calling class Component’s methods setAlignmentX() and/or setAlignmentY() on each component.
JTool bar Sour ce Code import import import import import import import import import import
javax.swing.JToolBar; javax.swing.JButton; javax.swing.ImageIcon; javax.swing.JFrame; javax.swing.JTextArea; javax.swing.JScrollPane; javax.swing.JPanel; javax.swing.JTextField; java.awt.*; java.awt.event.*;
public class JToolBarDemo extends JFrame { protected JTextArea textArea; protected String newline = "\n"; public JToolBarDemo() { super("ToolBarDemo"); // Create the toolbar. JToolBar jtbMainToolbar = new JToolBar(); // setFloatable(false) to make the toolbar non movable addButtons(jtbMainToolbar); // Create the text area textArea = new JTextArea(5, 30); JScrollPane jsPane = new JScrollPane(textArea); // Lay out the content pane. JPanel jplContentPane = new JPanel(); jplContentPane.setLayout(new BorderLayout()); jplContentPane.setPreferredSize(new Dimension(400, 100)); jplContentPane.add(jtbMainToolbar, BorderLayout.NORTH); jplContentPane.add(jsPane, BorderLayout.CENTER); setContentPane(jplContentPane); } public void addButtons(JToolBar jtbToolBar) { JButton jbnToolbarButtons = null; // first button jbnToolbarButtons = new JButton(new ImageIcon("left.gif")); jbnToolbarButtons.setToolTipText("left"); jbnToolbarButtons.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { displayInTextArea("This is Left Toolbar Button Reporting"); } }); jtbToolBar.add(jbnToolbarButtons); // 2nd button jbnToolbarButtons = new JButton(new ImageIcon("right.gif")); jbnToolbarButtons.setToolTipText("right"); jbnToolbarButtons.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { displayInTextArea("This is right Toolbar Button Reporting"); } }); jtbToolBar.add(jbnToolbarButtons); jtbToolBar.addSeparator(); // 3rd button jbnToolbarButtons = new JButton(new ImageIcon("open.gif")); jbnToolbarButtons.setToolTipText("open"); jbnToolbarButtons.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { displayInTextArea("This is open Toolbar Button Reporting"); } }); jtbToolBar.add(jbnToolbarButtons); // 4th button jbnToolbarButtons = new JButton(new ImageIcon("save.gif")); jbnToolbarButtons.setToolTipText("save"); jbnToolbarButtons.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { displayInTextArea("This is save Toolbar Button Reporting"); } }); jtbToolBar.add(jbnToolbarButtons); // We can add separators to group similar components jtbToolBar.addSeparator(); // fourth button jbnToolbarButtons = new JButton("Text button"); jbnToolbarButtons.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { displayInTextArea("Text button"); } }); jtbToolBar.add(jbnToolbarButtons); // fifth component is NOT a button! JTextField jtfButton = new JTextField("Text field");
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java Gr id BagLayout class exam ple GridBagLayout Java Swing Tutorial Explaining the GridBagLayout. GridBagLayout is a layout manager that lays out a container’s components in a grid of cells with each component occupying one or more cells, called its display area. The display area aligns components vertically and horizontally, without requiring that the components be of the same size.
Gr id BagLayou t Source Code import import import import import
java.awt.*; javax.swing.JButton; javax.swing.JComboBox; javax.swing.JFrame; javax.swing.JTextField;
public class GridBagLayoutDemo { public static void addComponentsToPane(Container pane) { JButton jbnButton; pane.setLayout(new GridBagLayout()); GridBagConstraints gBC = new GridBagConstraints(); gBC.fill = GridBagConstraints.HORIZONTAL; jbnButton = new JButton("Button 1"); gBC.weightx = 0.5; gBC.gridx = 0; gBC.gridy = 0; pane.add(jbnButton, gBC); JTextField jtf = new JTextField("TextField 1"); gBC.gridx = 2; gBC.gridy = 0; jtf.setEditable(false); pane.add(jtf, gBC); jbnButton = new JButton("Button 3"); gBC.gridx = 2; gBC.gridy = 0; pane.add(jbnButton, gBC); jbnButton = new JButton("Button 4"); gBC.ipady = 40; //This component has more breadth compared to other buttons gBC.weightx = 0.0; gBC.gridwidth = 3; gBC.gridx = 0; gBC.gridy = 1; pane.add(jbnButton, gBC); JComboBox jcmbSample = new JComboBox(new String[]{"ComboBox 1", "hi", "hello"}); gBC.ipady = 0; gBC.weighty = 1.0; gBC.anchor = GridBagConstraints.PAGE_END; gBC.insets = new Insets(10,0,0,0); //Padding gBC.gridx = 1; gBC.gridwidth = 2; gBC.gridy = 2; pane.add(jcmbSample, gBC); } private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("GridBagLayout Source Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Set up the content pane. addComponentsToPane(frame.getContentPane()); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }
Output
After Expanding the Frame
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Download GridBagLayout Source Code GridBagLayout Class
javax.swing Class GridBagLayout java.lang.Object java.awt.GridBagLayout All Implemented Interfaces: LayoutManager, LayoutManager2, Serializable
Grid BagLayout Constr uct or GridBagLayout() Creates a grid bag layout manager..
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java BorderLayout class ex amp le BorderLayout Java Swing Tutorial Explaining the BorderLayout . BorderLayout places swing components in the North, South, East, West and center of a container. All extra space is placed in the center area. You can add horizontal and vertical gaps between the areas. Every content pane is initialized to use a BorderLayout. Components are added to a BorderLayout by using the add method. JFrame’s content pane default layout manager: BorderLayout. In BorderLayout, a component’s position is specified by a second argument to add.
Bor derLayout Sour ce Code /* * BorderLayoutDemo.java is a 1.4 application that requires no other files. */ import import import import import import
java.awt.BorderLayout; java.awt.Container; java.awt.Dimension; javax.swing.JButton; javax.swing.JFrame; javax.swing.JLabel;
public class BorderLayoutDemo { public static boolean RIGHT_TO_LEFT = false; // //
public static void addComponentsToPane(Container contentPane) { Use BorderLayout. Default empty constructor with no horizontal and vertical gaps contentPane.setLayout(new BorderLayout(5,5)); if (!(contentPane.getLayout() instanceof BorderLayout)) { contentPane.add(new JLabel("Container doesn't use BorderLayout!")); return; } if (RIGHT_TO_LEFT) { contentPane.setComponentOrientation( java.awt.ComponentOrientation.RIGHT_TO_LEFT); } JButton jbnSampleButtons = new JButton("Button 1 (PAGE_START)"); contentPane.add(jbnSampleButtons, BorderLayout.PAGE_START); jbnSampleButtons = new JButton("Button 2 (CENTER)"); jbnSampleButtons.setPreferredSize(new Dimension(200, 100)); contentPane.add(jbnSampleButtons, BorderLayout.CENTER); jbnSampleButtons = new JButton("Button 3 (LINE_START)"); contentPane.add(jbnSampleButtons, BorderLayout.LINE_START); jbnSampleButtons = new JButton("Long-Named Button 4 (PAGE_END)"); contentPane.add(jbnSampleButtons, BorderLayout.PAGE_END); jbnSampleButtons = new JButton("5 (LINE_END)"); contentPane.add(jbnSampleButtons, BorderLayout.LINE_END); } private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("BorderLayout Source Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Set up the content pane and add swing components to it addComponentsToPane(frame.getContentPane()); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }
}
output
Download BorderLayout Source Code
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java JMenu class exam ple JMenu Java Swing Tutorial Explaining the JMenuBar Component. Swing provides support for pull-down and popup menus. A JMenubar can contain several JMenu ‘s. Each of the JMenu ‘s can contain a series of JMenuItem ‘s that you can select. How Menu’s Are Created? 1. First, A JMenubar is created 2. Then, we attach all of the menus to this JMenubar. 3. Then we add JMenuItem ‘s to the JMenu ‘s. 4. The JMenubar is then added to the frame. By default, each JMenuItem added to a JMenu is enabled—that is, it can be selected. In certain situations, we may need to disable a JMenuItem. This is done by calling setEnabled(). The setEnabled() method also allows components to be enabled.
JMenu Sou r ce Code import import import import import import import import import import import import import import
java.awt.*; java.awt.event.*; javax.swing.JMenu; javax.swing.JMenuItem; javax.swing.JCheckBoxMenuItem; javax.swing.JRadioButtonMenuItem; javax.swing.ButtonGroup; javax.swing.JMenuBar; javax.swing.KeyStroke; javax.swing.ImageIcon; javax.swing.JPanel; javax.swing.JTextArea; javax.swing.JScrollPane; javax.swing.JFrame;
//Used Action Listner for JMenuItem & JRadioButtonMenuItem //Used Item Listner for JCheckBoxMenuItem public class JMenuDemo implements ActionListener, ItemListener { JTextArea jtAreaOutput; JScrollPane jspPane; public JMenuBar createJMenuBar() { JMenuBar mainMenuBar; JMenu menu1, menu2, submenu; JMenuItem plainTextMenuItem, textIconMenuItem, iconMenuItem, subMenuItem; JRadioButtonMenuItem rbMenuItem; JCheckBoxMenuItem cbMenuItem; ImageIcon icon = createImageIcon("jmenu.jpg"); mainMenuBar = new JMenuBar(); menu1 = new JMenu("Menu 1"); menu1.setMnemonic(KeyEvent.VK_M); mainMenuBar.add(menu1); // Creating the MenuItems plainTextMenuItem = new JMenuItem("Menu item with Plain Text", KeyEvent.VK_T); // can be done either way for assigning shortcuts // menuItem.setMnemonic(KeyEvent.VK_T); // Accelerators, offer keyboard shortcuts to bypass navigating the menu // hierarchy. plainTextMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_1, ActionEvent.ALT_MASK)); plainTextMenuItem.addActionListener(this); menu1.add(plainTextMenuItem); textIconMenuItem = new JMenuItem("Menu Item with Text & Image", icon); textIconMenuItem.setMnemonic(KeyEvent.VK_B); textIconMenuItem.addActionListener(this); menu1.add(textIconMenuItem); // Menu Item with just an Image iconMenuItem = new JMenuItem(icon); iconMenuItem.setMnemonic(KeyEvent.VK_D); iconMenuItem.addActionListener(this); menu1.add(iconMenuItem); menu1.addSeparator(); // Radio Button Menu items follow a seperator ButtonGroup itemGroup = new ButtonGroup(); rbMenuItem = new JRadioButtonMenuItem( "Menu Item with Radio Button"); rbMenuItem.setSelected(true); rbMenuItem.setMnemonic(KeyEvent.VK_R); itemGroup.add(rbMenuItem); rbMenuItem.addActionListener(this); menu1.add(rbMenuItem); rbMenuItem = new JRadioButtonMenuItem( "Menu Item 2 with Radio Button"); itemGroup.add(rbMenuItem); rbMenuItem.addActionListener(this); menu1.add(rbMenuItem); menu1.addSeparator(); // Radio Button Menu items follow a seperator cbMenuItem = new JCheckBoxMenuItem("Menu Item with check box"); cbMenuItem.setMnemonic(KeyEvent.VK_C); cbMenuItem.addItemListener(this); menu1.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Menu Item 2 with check box"); cbMenuItem.addItemListener(this); menu1.add(cbMenuItem); menu1.addSeparator(); // Sub Menu follows a seperator submenu = new JMenu("Sub Menu"); submenu.setMnemonic(KeyEvent.VK_S); subMenuItem = new JMenuItem("Sub MenuItem 1"); subMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2,
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java Scrollabl e Popu p Menu Scrollable JPopupMenu Java Swing Tutorial Explaining the Scrollable Popup Menu Component. Scrollable JPopupMenu can be used in any of the Java Applications. I developed this as the popup menu can have so many menuitems that, they exceed the screen visible area and would not be visible. I needed a way to scroll through the menu items of the pop up menu to avoid this visibility problem.
Scrol lab le Popu pMenu Sour ce Code Custom JButtons are placed on a JPanel. This JPanel is placed on JScrollPane which has a scrollbar. These custom JButtons are nothing but menuitems. These menuitems can be checked and unchecked similar to JCheckBoxMenuItems. My scrollable jpopupmenu source code contains 5 files. 1. JFramePopupMenu.java (Mainframe containing the button to invoke Scrollable popup menu) 2. XCheckedButton.java (Custom JButton which acts like a JCheckBoxMenuItem for the pop up menu. This class provides a JCheckBoxMenuItrem Functionality, optionally working like a JMenuItem, primarily used with XJPopupMenu. Rationale for development of this component was the inability of a JMenuItem to work in a Scrollable Popup menu as in XJPopupMenu) 3. XJPopupMenu.java (This is the heart of Scrollable JPopupMenu code) 4. XConstant.java (Interface containing commonly used constants) 5. check.gif 6. menu_spacer.gif Here is a source code showing, how to create a java swing JPopupMenu with a vertical scrollbar: 1. JFramePopupMenu.java import java.awt.Component; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; public class JFramePopupMenu extends JFrame
{
private JPanel jContentPane = null; private JButton jbnPopup = null; private JTextField jtfNumOfMenus = null; private JLabel lblNumElem = null; private XJPopupMenu scrollablePopupMenu = new XJPopupMenu(this); private JButton getBtnPopup() { if (jbnPopup == null) { jbnPopup = new JButton(); jbnPopup.setText("View Scrollable popup menu "); int n = Integer.parseInt(getTxtNumElem().getText()); for (int i=0;i
" + (i+1));
xx.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { System.out.println( e ); scrollablePopupMenu.hidemenu(); } }); // Add Custom JSeperator after 2nd and 7th MenuItem. if(i == 2 || i == 7){ scrollablePopupMenu.addSeparator(); }
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in scrollablePopupMenu.add(xx); } jbnPopup.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { Component source = (Component) e.getSource(); scrollablePopupMenu.show(source, e.getX(), e.getY()); } }); } return jbnPopup; } private JTextField getTxtNumElem() { if (jtfNumOfMenus == null) { jtfNumOfMenus = new JTextField(); jtfNumOfMenus.setColumns(3); jtfNumOfMenus.setText("60"); } return jtfNumOfMenus; } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { JFramePopupMenu thisClass = new JFramePopupMenu(); thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); thisClass.setVisible(true); } }); } public JFramePopupMenu() { super(); initialize(); } private void initialize() { this.setSize(274, 109); this.setContentPane(getJContentPane()); this.setTitle(" Scrollable JPopupMenu "); } private JPanel getJContentPane() { if (jContentPane == null) { lblNumElem = new JLabel(); FlowLayout flowLayout = new FlowLayout(); flowLayout.setHgap(8); flowLayout.setVgap(8); jContentPane = new JPanel(); jContentPane.setLayout(flowLayout); jContentPane.add(getBtnPopup(), null); jContentPane.add(lblNumElem, null); jContentPane.add(getTxtNumElem(), null); } return jContentPane; } }
2. XCheckedButton.java import java.awt.Color; import java.awt.event.ItemEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JToggleButton; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicButtonUI; /** * @author balajihe * */ public class XCheckedButton extends JButton { //
Icon to be used to for the Checked Icon of the Button
private static ImageIcon
checkedIcon;
/** * These colors are required in order to simulate the JMenuItem's L&F */ public static final Color MENU_HIGHLIGHT_BG_COLOR = UIManager.getColor ("MenuItem.selectionBackground"); public static final Color MENU_HIGHLIGHT_FG_COLOR = UIManager.getColor ("MenuItem.selectionForeground"); public static final Color MENUITEM_BG_COLOR = UIManager.getColor ("MenuItem.background");
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in public static final Color MENUITEM_FG_COLOR = UIManager.getColor ("MenuItem.foreground"); //
This property if set to false, will result in the checked Icon not being
displayed // when the button is selected private boolean
displayCheck
= true;
public XCheckedButton() { super(); init(); } public XCheckedButton(Action a) { super(a); init(); } public XCheckedButton(Icon icon) { super(icon); init(); } public XCheckedButton(String text, Icon icon) { super(text, icon); init(); } public XCheckedButton(String text) { super(text); init(); } /** * Initialize component LAF and add Listeners */ private void init() { MouseAdapter mouseAdapter = getMouseAdapter(); // Basically JGoodies LAF UI for JButton does not allow Background color to be set. // So we need to set the default UI, ComponentUI ui = BasicButtonUI.createUI(this); this.setUI(ui); setBorder(BorderFactory.createEmptyBorder(3, 0, 3, 2)); setMenuItemDefaultColors(); //
setContentAreaFilled(false);
setHorizontalTextPosition(SwingConstants.RIGHT); setHorizontalAlignment(SwingConstants.LEFT); //
setModel(new JToggleButton.ToggleButtonModel());
setModel(new XCheckedButtonModel()); setSelected(false); this.addMouseListener(mouseAdapter); } private void setMenuItemDefaultColors() { XCheckedButton.this.setBackground(MENUITEM_BG_COLOR); XCheckedButton.this.setForeground(MENUITEM_FG_COLOR); } /** * @return */ private MouseAdapter getMouseAdapter() { return new MouseAdapter() { // For static menuitems, the background color remains the highlighted color, if this is not overridden public void mousePressed(MouseEvent e) { setMenuItemDefaultColors(); } public void mouseEntered(MouseEvent e) { XCheckedButton.this.setBackground(MENU_HIGHLIGHT_BG_COLOR); XCheckedButton.this.setForeground(MENU_HIGHLIGHT_FG_COLOR); } public void mouseExited(MouseEvent e) { setMenuItemDefaultColors(); } }; } /** * @param checkedFlag */ public void displayIcon(boolean checkedFlag) { if (checkedFlag && isDisplayCheck()) { if (checkedIcon == null) { checkedIcon = new ImageIcon("check.gif"); } this.setIcon(checkedIcon); } else { this.setIcon(XConstant.EMPTY_IMAGE_ICON); } this.repaint(); } private class XCheckedButtonModel extends JToggleButton.ToggleButtonModel { /* * Need to Override keeping the super code, else the check mark won't come */
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in public void setSelected(boolean b) { ButtonGroup group = getGroup(); if (group != null) { // use the group model instead group.setSelected(this, b); b = group.isSelected(this); } if (isSelected() == b) { return; } if (b) { stateMask |= SELECTED; } else { stateMask &= ~SELECTED; } //
Send ChangeEvent
fireStateChanged(); // Send ItemEvent fireItemStateChanged(new ItemEvent(this, ItemEvent.ITEM_STATE_ CHANGED, this, this.isSelected() ? ItemEvent.SELECTED : ItemEvent.DESELECTED)); XCheckedButton.this.displayIcon(b); } } // Returns true if Button will display Checked Icon on Click. Default Behaviour is to display a Checked Icon
public boolean isDisplayCheck() { return displayCheck; } /** * Sets the property which determines whether a checked Icon should be displayed or not * Setting to false, makes this button display like a normal button * @param displayCheck */ public void setDisplayCheck(boolean displayCheck) { this.displayCheck = displayCheck; } }
3. XJPopupMenu.java this.getToolkit().getScreenSize().height - this.getToolkit().getScreenInsets(jframe.getGraphicsConfiguration()).top - this.getToolkit().getScreenInsets(jframe.getGraphicsConfiguration()).bottom - 4)); super.add(scroll, BorderLayout.CENTER); //
super.add(scroll);
} public void show(Component invoker, int x, int y) { init(jframe); //
this.pack();
panelMenus.validate(); int maxsize = scroll.getMaximumSize().height; int realsize = panelMenus.getPreferredSize().height; int sizescroll = 0; if (maxsize < realsize) { sizescroll = scroll.getVerticalScrollBar().getPreferredSize().width; } Scroll.setPreferredSize(new Dimension(scroll.getPreferredSize().width + sizescroll + 20, scroll.getPreferredSize().height)); this.pack(); this.setInvoker(invoker); if (sizescroll != 0) { //Set popup size only if scrollbar is visible this.setPopupSize(new Dimension(scroll.getPreferredSize().width + 20, scroll.getMaximumSize().height - 20)); } //
this.setMaximumSize(scroll.getMaximumSize());
Point invokerOrigin = invoker.getLocationOnScreen(); this.setLocation((int) invokerOrigin.getX() + x, (int) invokerOrigin.getY() + y); this.setVisible(true); } public void hidemenu() { if (this.isVisible()) { this.setVisible(false); } } public void add(AbstractButton menuItem) { //
menuItem.setMargin(new Insets(0, 20, 0 , 0));
if (menuItem == null) { return; }
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in panelMenus.add(menuItem); menuItem.removeActionListener(this); menuItem.addActionListener(this); if (menuItem.getIcon() == null) { menuItem.setIcon(EMPTY_IMAGE_ICON); } if (!(menuItem instanceof XCheckedButton)) { System.out.println(menuItem.getName()); } } public void addSeparator() { panelMenus.add(new XSeperator()); } public void actionPerformed(ActionEvent e) { this.hidemenu(); } public Component[] getComponents() { return panelMenus.getComponents(); } private static class XSeperator extends JSeparator { XSeperator() { ComponentUI ui = XBasicSeparatorUI.createUI(this); XSeperator.this.setUI(ui); } private static class XBasicSeparatorUI extends BasicSeparatorUI { public static ComponentUI createUI(JComponent c) { return new XBasicSeparatorUI(); } public void paint(Graphics g, JComponent c) { Dimension s = c.getSize(); if (((JSeparator) c).getOrientation() == JSeparator.VERTICAL) { g.setColor(c.getForeground()); g.drawLine(0, 0, 0, s.height); g.setColor(c.getBackground()); g.drawLine(1, 0, 1, s.height); } else // HORIZONTAL { g.setColor(c.getForeground()); g.drawLine(0, 7, s.width, 7); g.setColor(c.getBackground()); g.drawLine(0, 8, s.width, 8); } } } } }
4. XConstant.java import javax.swing.Icon; import javax.swing.ImageIcon; public interface XConstant { public static final Icon EMPTY_IMAGE_ICON = new ImageIcon("menu_spacer.gif"); }
Note: Please use the 2 jgoodies jars present in the zip file for the jgoodies look and feel Download Scrollable JPopupMenu Source Code
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java Sw in g Calculat or This is a free Java calculator tutorial developed using Java Swing. Below you will find the java code for calculator along with the screenshot. It is a basic four-function calculator java program source code. The calculator that we build will look like:
Java simple calculator 1. A four-function calculator with the following functions: * Addition – adds two numbers: n1 + n2. * Subtraction – subtracts number two from number one: n1 – n2. * Multiplication – Multiplies two numbers: n1 * n2. * Division – divides number two into number one: n1 / n2. 2. Used JButton for the numbers and functions. 3. Used Jmenu for File and help. 4. Created a class to respond to the events caused by numbers, functions, exit, help and about functionality. 5. Used BorderLayout to layout various components in the Calculator Frame. A BorderLayout lays out a container, arranging and resizing its components to fit in five regions: north, south, east, west, and center.
Java Calcul at or Sour ce Code Oct 15, 2006 by Hemanth /* Name: Hemanth. B Website: wwww.java-swing-tutorial.html Topic: A basic Java Swing Calculator Conventions Used in Source code --------------------------------1. All JLabel components start with jlb* 2. All JPanel components start with jpl* 3. All JMenu components start with jmenu* 4. All JMenuItem components start with jmenuItem* 5. All JDialog components start with jdlg* 6. All JButton components start with jbn* */ import import import import import import import import import import import import import import import import import import import import import import
java.awt.BorderLayout; java.awt.Color; java.awt.Container; java.awt.FlowLayout; java.awt.Font; java.awt.GridLayout; java.awt.Window; java.awt.event.ActionEvent; java.awt.event.ActionListener; java.awt.event.KeyEvent; java.awt.event.WindowAdapter; java.awt.event.WindowEvent; javax.swing.JButton; javax.swing.JDialog; javax.swing.JFrame; javax.swing.JLabel; javax.swing.JMenu; javax.swing.JMenuBar; javax.swing.JMenuItem; javax.swing.JPanel; javax.swing.JTextArea; javax.swing.KeyStroke;
public class Calculator extends JFrame implements ActionListener { // Variables final int MAX_INPUT_LENGTH = 20; final int INPUT_MODE = 0; final int RESULT_MODE = 1; final int ERROR_MODE = 2; int displayMode; boolean clearOnNextDigit, percent; double lastNumber; String lastOperator;
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in private private private private private /*
JMenu jmenuFile, jmenuHelp; JMenuItem jmenuitemExit, jmenuitemAbout; JLabel jlbOutput; JButton jbnButtons[]; JPanel jplMaster, jplBackSpace, jplControl;
* Font(String name, int style, int size) Creates a new Font from the specified name, style and point size. */ Font f12 = new Font("Times New Roman", 0, 12); Font f121 = new Font("Times New Roman", 1, 12); // Constructor public Calculator() { /* Set Up the JMenuBar. * Have Provided All JMenu's with Mnemonics * Have Provided some JMenuItem components with Keyboard Accelerators */ jmenuFile = new JMenu("File"); jmenuFile.setFont(f121); jmenuFile.setMnemonic(KeyEvent.VK_F); jmenuitemExit = new JMenuItem("Exit"); jmenuitemExit.setFont(f12); jmenuitemExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK)); jmenuFile.add(jmenuitemExit); jmenuHelp = new JMenu("Help"); jmenuHelp.setFont(f121); jmenuHelp.setMnemonic(KeyEvent.VK_H); jmenuitemAbout = new JMenuItem("About Calculator"); jmenuitemAbout.setFont(f12); jmenuHelp.add(jmenuitemAbout); JMenuBar mb = new JMenuBar(); mb.add(jmenuFile); mb.add(jmenuHelp); setJMenuBar(mb); //Set frame layout manager setBackground(Color.gray); jplMaster = new JPanel(); jlbOutput = new JLabel("0"); jlbOutput.setHorizontalTextPosition(JLabel.RIGHT); jlbOutput.setBackground(Color.WHITE); jlbOutput.setOpaque(true); // Add components to frame getContentPane().add(jlbOutput, BorderLayout.NORTH); jbnButtons = new JButton[23]; // GridLayout(int rows, int cols, int hgap, int vgap) JPanel jplButtons = new JPanel(); // container for Jbuttons // Create numeric Jbuttons for (int i = 0; i <= 9; i++) { // set each Jbutton label to the value of index jbnButtons[i] = new JButton(String.valueOf(i)); } // Create operator Jbuttons jbnButtons[10] = new JButton("+/-"); jbnButtons[11] = new JButton("."); jbnButtons[12] = new JButton("="); jbnButtons[13] = new JButton("/"); jbnButtons[14] = new JButton("*"); jbnButtons[15] = new JButton("-"); jbnButtons[16] = new JButton("+"); jbnButtons[17] = new JButton("sqrt"); jbnButtons[18] = new JButton("1/x"); jbnButtons[19] = new JButton("%"); jplBackSpace = new JPanel(); jplBackSpace.setLayout(new GridLayout(1, 1, 2, 2)); jbnButtons[20] = new JButton("Backspace"); jplBackSpace.add(jbnButtons[20]); jplControl = new JPanel(); jplControl.setLayout(new GridLayout(1, 2, 2, 2)); jbnButtons[21] = new JButton(" CE "); jbnButtons[22] = new JButton("C"); jplControl.add(jbnButtons[21]); jplControl.add(jbnButtons[22]); // Setting all Numbered JButton's to Blue. The rest to Red for (int i = 0; i < jbnButtons.length; i++) { jbnButtons[i].setFont(f12); if (i < 10) jbnButtons[i].setForeground(Color.blue); else jbnButtons[i].setForeground(Color.red); } // Set panel layout manager for a 4 by 5 grid jplButtons.setLayout(new GridLayout(4, 5, 2, 2)); //Add buttons to keypad panel starting at top left // First row for (int i = 7; i <= 9; i++) { jplButtons.add(jbnButtons[i]); } // add button / and sqrt jplButtons.add(jbnButtons[13]); jplButtons.add(jbnButtons[17]); // Second row for (int i = 4; i <= 6; i++) { jplButtons.add(jbnButtons[i]); } // add button * and x^2 jplButtons.add(jbnButtons[14]); jplButtons.add(jbnButtons[18]); // Third row for (int i = 1; i <= 3; i++) { jplButtons.add(jbnButtons[i]); } //adds button - and % jplButtons.add(jbnButtons[15]); jplButtons.add(jbnButtons[19]); //Fourth Row // add 0, +/-, ., +, and = jplButtons.add(jbnButtons[0]); jplButtons.add(jbnButtons[10]); jplButtons.add(jbnButtons[11]); jplButtons.add(jbnButtons[16]); jplButtons.add(jbnButtons[12]); jplMaster.setLayout(new BorderLayout()); jplMaster.add(jplBackSpace, BorderLayout.WEST); jplMaster.add(jplControl, BorderLayout.EAST); jplMaster.add(jplButtons, BorderLayout.SOUTH); // Add components to frame getContentPane().add(jplMaster, BorderLayout.SOUTH); requestFocus(); //activate ActionListener for (int i = 0; i < jbnButtons.length; i++) { jbnButtons[i].addActionListener(this); }
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in jmenuitemAbout.addActionListener(this); jmenuitemExit.addActionListener(this); clearAll(); //add WindowListener for closing frame and ending program addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent e) { System.exit(0); } }); } //End of Contructor Calculator // Perform action public void actionPerformed(ActionEvent e){ double result = 0; if(e.getSource() == jmenuitemAbout){ JDialog dlgAbout = new CustomABOUTDialog(this, "About Java Swing Calculator", true); dlgAbout.setVisible(true); }else if(e.getSource() == jmenuitemExit){ System.exit(0); } // Search for the button pressed until end of array or key found for (int i=0; i< 1) setDisplayString("0"); } break; case 21:
// CE clearExisting(); break;
case 22:
// C clearAll(); break;
} } } }
void setDisplayString(String s) { jlbOutput.setText(s);
} String getDisplayString() { return jlbOutput.getText(); } void addDigitToDisplay(int digit) { if (clearOnNextDigit) setDisplayString(""); String inputString = getDisplayString(); if (inputString.indexOf("0") == 0) { inputString = inputString.substring(1); } if ((!inputString.equals("0") || digit > 0) && inputString.length() < MAX_INPUT_LENGTH) { setDisplayString(inputString + digit); } displayMode = INPUT_MODE; clearOnNextDigit = false; } void addDecimalPoint() { displayMode = INPUT_MODE; if (clearOnNextDigit) setDisplayString(""); String inputString = getDisplayString(); // If the input string already contains a decimal point, don't // do anything to it. if (inputString.indexOf(".") < 0) setDisplayString(new String(inputString + ".")); } void processSignChange() { if (displayMode == INPUT_MODE) { String input = getDisplayString(); if (input.length() > 0 && !input.equals("0")) { if (input.indexOf("-") == 0) setDisplayString(input.substring(1)); else setDisplayString("-" + input); } } else if (displayMode == RESULT_MODE) { double numberInDisplay = getNumberInDisplay(); if (numberInDisplay != 0) displayResult(-numberInDisplay); } } void clearAll() { setDisplayString("0"); lastOperator = "0"; lastNumber = 0; displayMode = INPUT_MODE; clearOnNextDigit = true; } void clearExisting() { setDisplayString("0"); clearOnNextDigit = true; displayMode = INPUT_MODE; } double getNumberInDisplay() { String input = jlbOutput.getText(); return Double.parseDouble(input); } void processOperator(String op) { if (displayMode != ERROR_MODE) { double numberInDisplay = getNumberInDisplay(); if (!lastOperator.equals("0")) { try { double result = processLastOperator(); displayResult(result); lastNumber = result; } catch (DivideByZeroException e) { }
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in } else { lastNumber = numberInDisplay; } clearOnNextDigit = true; lastOperator = op; } } void processEquals() { double result = 0; if (displayMode != ERROR_MODE) { try { result = processLastOperator(); displayResult(result); } catch (DivideByZeroException e) { displayError("Cannot divide by zero!"); } lastOperator = "0"; } } double processLastOperator() throws DivideByZeroException { double result = 0; double numberInDisplay = getNumberInDisplay(); if (lastOperator.equals("/")) { if (numberInDisplay == 0) throw (new DivideByZeroException()); result = lastNumber / numberInDisplay; } if (lastOperator.equals("*")) result = lastNumber * numberInDisplay; if (lastOperator.equals("-")) result = lastNumber - numberInDisplay; if (lastOperator.equals("+")) result = lastNumber + numberInDisplay; return result; } void displayResult(double result) { setDisplayString(Double.toString(result)); lastNumber = result; displayMode = RESULT_MODE; clearOnNextDigit = true; } void displayError(String errorMessage) { setDisplayString(errorMessage); lastNumber = 0; displayMode = ERROR_MODE; clearOnNextDigit = true; } public static void main(String args[]) { Calculator calci = new Calculator(); Container contentPane = calci.getContentPane(); // contentPane.setLa yout(new BorderLayout()); calci.setTitle("Java Swing Calculator"); calci.setSize(241, 217); calci.pack(); calci.setLocation(400, 250); calci.setVisible(true); calci.setResizable(false); } } //End of Swing Calculator Class. class DivideByZeroException extends Exception { public DivideByZeroException() { super(); } public DivideByZeroException(String s) { super(s); } } class CustomABOUTDialog extends JDialog implements ActionListener { JButton jbnOk; CustomABOUTDialog(JFrame parent, String title, boolean modal) { super(parent, title, modal); setBackground(Color.black); JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER)); StringBuffer text = new StringBuffer(); text.append("Calculator Information\n\n"); text.append("Developer: Hemanth\n"); text.append("Version: 1.0"); JTextArea jtAreaAbout = new JTextArea(5, 21); jtAreaAbout.setText(text.toString()); jtAreaAbout.setFont(new Font("Times New Roman", 1, 13)); jtAreaAbout.setEditable(false); p1.add(jtAreaAbout); p1.setBackground(Color.red); getContentPane().add(p1, BorderLayout.CENTER); JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER)); jbnOk = new JButton(" OK "); jbnOk.addActionListener(this); p2.add(jbnOk); getContentPane().add(p2, BorderLayout.SOUTH); setLocation(408, 270); setResizable(false); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Window aboutDialog = e.getWindow(); aboutDialog.dispose(); } }); pack(); } public void actionPerformed(ActionEvent e) { if (e.getSource() == jbnOk) { this.dispose(); } } }
Download Java Calculator Source Code
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java Sw in g Calculat or This is a free Java calculator tutorial developed using Java Swing. Below you will find the java code for calculator along with the screenshot. It is a basic four-function calculator java program source code. The calculator that we build will look like:
Java simple calculator 1. A four-function calculator with the following functions: * Addition – adds two numbers: n1 + n2. * Subtraction – subtracts number two from number one: n1 – n2. * Multiplication – Multiplies two numbers: n1 * n2. * Division – divides number two into number one: n1 / n2. 2. Used JButton for the numbers and functions. 3. Used Jmenu for File and help. 4. Created a class to respond to the events caused by numbers, functions, exit, help and about functionality. 5. Used BorderLayout to layout various components in the Calculator Frame. A BorderLayout lays out a container, arranging and resizing its components to fit in five regions: north, south, east, west, and center.
Java Calcul at or Sour ce Code Oct 15, 2006 by Hemanth /* Name: Hemanth. B Website: wwww.java-swing-tutorial.html Topic: A basic Java Swing Calculator Conventions Used in Source code --------------------------------1. All JLabel components start with jlb* 2. All JPanel components start with jpl* 3. All JMenu components start with jmenu* 4. All JMenuItem components start with jmenuItem* 5. All JDialog components start with jdlg* 6. All JButton components start with jbn* */ import import import import import import import import import import import import import import import import import import import import import import
java.awt.BorderLayout; java.awt.Color; java.awt.Container; java.awt.FlowLayout; java.awt.Font; java.awt.GridLayout; java.awt.Window; java.awt.event.ActionEvent; java.awt.event.ActionListener; java.awt.event.KeyEvent; java.awt.event.WindowAdapter; java.awt.event.WindowEvent; javax.swing.JButton; javax.swing.JDialog; javax.swing.JFrame; javax.swing.JLabel; javax.swing.JMenu; javax.swing.JMenuBar; javax.swing.JMenuItem; javax.swing.JPanel; javax.swing.JTextArea; javax.swing.KeyStroke;
public class Calculator extends JFrame implements ActionListener { // Variables final int MAX_INPUT_LENGTH = 20; final int INPUT_MODE = 0; final int RESULT_MODE = 1; final int ERROR_MODE = 2; int displayMode; boolean clearOnNextDigit, percent; double lastNumber; String lastOperator;
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java Sw in g Address Book This java swing project code demonstrate’s how to create a simple free address book program using java swing and jdbc. Also you will learn to use the following swing components like Jbuttons, JFrames, JTextFields and Layout Manager (GridBagLayout). In short, this is a Simple Address Book that keeps Names, email, Address and Phone Numbers of friends or people. It makes use of the JDBC driver and SQL statements for connecting and manipulating with the database.
Java Addr ess Book Sour ce Code Oct 22, 2006 by Hemanth This Project Source code consists of 3 files: 1. 2. 3. 4.
AddressBookDemo.java PersonDao.java PersonInfo.java An sql Table (Person Table)
AddressBookDemo.java /* Name: Hemanth. B Website: java-swing-tutorial.html Topic: A basic Java Address Book Conventions Used in Source code --------------------------------1. All JLabel components start with jlb* 2. All JPanel components start with jpl* 3. All JMenu components start with jmenu* 4. All JMenuItem components start with jmenuItem* 5. All JDialog components start with jdlg* 6. All JButton components start with jbn* */ import import import import import import import import import import import import
java.awt.Container; java.awt.GridBagConstraints; java.awt.GridBagLayout; java.awt.Insets; java.awt.event.ActionEvent; java.awt.event.ActionListener; java.util.ArrayList; javax.swing.JButton; javax.swing.JFrame; javax.swing.JLabel; javax.swing.JOptionPane; javax.swing.JTextField;
public class AddressBookDemo implements ActionListener { ArrayList personsList; PersonDAO pDAO; JFrame appFrame; JLabel jlbName, jlbAddress, jlbPhone, jlbEmail; JTextField jtfName, jtfAddress, jtfPhone, jtfEmail; JButton jbbSave, jbnDelete, jbnClear, jbnUpdate, jbnSearch, jbnForward, jbnBack, jbnExit; String name, address, email; int phone; int recordNumber; // used to naviagate using >> and buttons Container cPane; public static void main(String args[]) { new AddressBookDemo(); } public AddressBookDemo() { name = ""; address = ""; email = ""; phone = -1; //Stores 0 to indicate no Phone Number recordNumber = -1; createGUI();
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in jbnUpdate.addActionListener(this); jbnSearch.addActionListener(this); jbnForward.addActionListener(this); jbnBack.addActionListener(this); jbnExit.addActionListener(this); } public void actionPerformed(ActionEvent e) { if (e.getSource() == jbbSave) { savePerson(); clear(); } else if (e.getSource() == jbnDelete) { deletePerson(); clear(); } else if (e.getSource() == jbnUpdate) { updatePerson(); clear(); } else if (e.getSource() == jbnSearch) { searchPerson(); } else if (e.getSource() == jbnForward) { displayNextRecord(); } else if (e.getSource() == jbnBack) { displayPreviousRecord(); } else if (e.getSource() == jbnClear) { clear(); } else if (e.getSource() == jbnExit) { System.exit(0); } } // Save the Person into the Address Book public void savePerson() { name = jtfName.getText(); name = name.toUpperCase(); //Save all names in Uppercase address = jtfAddress.getText(); try { phone = Integer.parseInt("" + jtfPhone.getText()); } catch (Exception e) { /*System.out.print("Input is a string"); JOptionPane.showMessageDialog(null, "Please enter Phone Number");*/ } email = jtfEmail.getText(); if (name.equals("")) { JOptionPane.showMessageDialog(null, "Please enter person name."); } else { //create a PersonInfo object and pass it to PersonDAO to save it PersonInfo person = new PersonInfo(name, address, phone, email); pDAO.savePerson(person); JOptionPane.showMessageDialog(null, "Person Saved"); } } public void deletePerson() { name = jtfName.getText(); name = name.toUpperCase(); if (name.equals("")) { JOptionPane.showMessageDialog(null, "Please enter person name to delete."); } else { //remove Person of the given name from the Address Book database int numberOfDeleted = pDAO.removePerson(name); JOptionPane.showMessageDialog(null, numberOfDeleted + " Record(s) deleted."); } } public void updatePerson() { if (recordNumber >= 0 && recordNumber < personsList.size()) { PersonInfo person = (PersonInfo) personsList.get(recordNumber); int id = person.getId(); /*get values from text fields*/ name = jtfName.getText(); address = jtfAddress.getText(); phone = Integer.parseInt(jtfPhone.getText()); email = jtfEmail.getText(); /*update data of the given person name*/ person = new PersonInfo(id, name, address, phone, email); pDAO.updatePerson(person); JOptionPane.showMessageDialog(null, "Person info record updated successfully."); } else { JOptionPane.showMessageDialog(null, "No record to Update"); } } //Perform a Case-Insensitive Search to find the Person public void searchPerson() { name = jtfName.getText(); name = name.toUpperCase(); /*clear contents of arraylist if there are any from previous search*/ personsList.clear(); recordNumber = 0; if (name.equals("")) { JOptionPane.showMessageDialog(null, "Please enter person name to search."); } else { /*get an array list of searched persons using PersonDAO*/ personsList = pDAO.searchPerson(name); if (personsList.size() == 0) { JOptionPane.showMessageDialog(null, "No records found."); //Perform a clear if no records are found. clear(); } else { /*downcast the object from array list to PersonInfo*/ PersonInfo person = (PersonInfo) personsList .get(recordNumber); // displaying search record in text fields jtfName.setText(person.getName()); jtfAddress.setText(person.getAddress()); jtfPhone.setText("" + person.getPhone()); jtfEmail.setText(person.getEmail()); } } } public void displayNextRecord() { // inc in recordNumber to display next person info, already stored in // personsList during search recordNumber++; if (recordNumber >= personsList.size()) { JOptionPane.showMessageDialog(null, "You have reached end of " + "search results"); /*if user has reached the end of results, disable forward button*/ jbnForward.setEnabled(false); jbnBack.setEnabled(true); // dec by one to counter last inc recordNumber--; } else { jbnBack.setEnabled(true); PersonInfo person = (PersonInfo) personsList.get(recordNumber); // displaying search record in text fields jtfName.setText(person.getName()); jtfAddress.setText(person. etAddress());
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in jtfPhone.setText("" + person.getPhone()); jtfEmail.setText(person.getEmail()); } } public void displayPreviousRecord() { // dec in recordNumber to display previous person info, already //stored in personsList during search recordNumber--; if (recordNumber < 0) { JOptionPane.showMessageDialog(null, "You have reached begining " + "of search results"); /*if user has reached the begining of results, disable back button*/ jbnForward.setEnabled(true); jbnBack.setEnabled(false); // inc by one to counter last dec recordNumber++; } else { jbnForward.setEnabled(true); PersonInfo person = (PersonInfo) personsList.get(recordNumber); // displaying search record in text fields jtfName.setText(person.getName()); jtfAddress.setText(person.getAddress()); jtfPhone.setText("" + person.getPhone()); jtfEmail.setText(person.getEmail()); } } public void clear() { jtfName.setText(""); jtfAddress.setText(""); jtfPhone.setText(""); jtfEmail.setText(""); /*clear contents of arraylist*/ recordNumber = -1; personsList.clear(); jbnForward.setEnabled(true); jbnBack.setEnabled(true); } }
PersonInfo.java /* Name: Hemanth. B Website: java-swing-tutorial.html Topic: A basic Java Address Book Conventions Used in Source code --------------------------------1. All JLabel components start with jlb* 2. All JPanel components start with jpl* 3. All JMenu components start with jmenu* 4. All JMenuItem components start with jmenuItem* 5. All JDialog components start with jdlg* 6. All JButton components start with jbn* */ import java.util.*; import java.sql.*; public class PersonDAO { /* Person Table needs to be created in the Oracle Database. * create table Person ( id Integer, name Varchar(30), address Varchar(30), phone Integer, email Varchar(50) );*/ private ArrayList personsList; private String userid = "scott"; private String password = "tiger"; static String url = "jdbc:odbc:bob"; private Connection con; // constructor public PersonDAO() { personsList = new ArrayList(); getConnection(); //Create Connection to the Oracle Database } public Connection getConnection() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, userid, password); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } return con; } public ArrayList searchPerson(String name) { try { String sql = "SELECT * FROM Person WHERE name like '%" + name + "%'"; // Create a prepared statement Statement s = con.createStatement(); ResultSet rs = s.executeQuery(sql); String pname = ""; String address = ""; String email = ""; int id, phone; while (rs.next()) { id = rs.getInt("id"); pname = rs.getString("name"); address = rs.getString("address"); phone = rs.getInt("phone"); email = rs.getString("email"); //Create a PersonInfo object PersonInfo person = new PersonInfo(id, pname, address, phone, email); //Add the person object to array list personsList.add(person); } } catch (Exception e) { System.out.println(e);
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in
Java Sw in g Address Book This java swing project code demonstrate’s how to create a simple free address book program using java swing and jdbc. Also you will learn to use the following swing components like Jbuttons, JFrames, JTextFields and Layout Manager (GridBagLayout). In short, this is a Simple Address Book that keeps Names, email, Address and Phone Numbers of friends or people. It makes use of the JDBC driver and SQL statements for connecting and manipulating with the database.
Java Addr ess Book Sour ce Code Oct 22, 2006 by Hemanth This Project Source code consists of 3 files: 1. 2. 3. 4.
AddressBookDemo.java PersonDao.java PersonInfo.java An sql Table (Person Table)
AddressBookDemo.java /* Name: Hemanth. B Website: java-swing-tutorial.html Topic: A basic Java Address Book Conventions Used in Source code --------------------------------1. All JLabel components start with jlb* 2. All JPanel components start with jpl* 3. All JMenu components start with jmenu* 4. All JMenuItem components start with jmenuItem* 5. All JDialog components start with jdlg* 6. All JButton components start with jbn* */ import import import import import import import import import import import import
java.awt.Container; java.awt.GridBagConstraints; java.awt.GridBagLayout; java.awt.Insets; java.awt.event.ActionEvent; java.awt.event.ActionListener; java.util.ArrayList; javax.swing.JButton; javax.swing.JFrame; javax.swing.JLabel; javax.swing.JOptionPane; javax.swing.JTextField;
public class AddressBookDemo implements ActionListener { ArrayList personsList; PersonDAO pDAO; JFrame appFrame; JLabel jlbName, jlbAddress, jlbPhone, jlbEmail; JTextField jtfName, jtfAddress, jtfPhone, jtfEmail; JButton jbbSave, jbnDelete, jbnClear, jbnUpdate, jbnSearch, jbnForward, jbnBack, jbnExit; String name, address, email; int phone; int recordNumber; // used to naviagate using >> and buttons Container cPane; public static void main(String args[]) { new AddressBookDemo(); } public AddressBookDemo() { name = ""; address = ""; email = ""; phone = -1; //Stores 0 to indicate no Phone Number recordNumber = -1; createGUI();
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in personsList = new ArrayList(); // creating PersonDAO object pDAO = new PersonDAO(); } public void createGUI(){ /*Create a frame, get its contentpane and set layout*/ appFrame = new JFrame("Address Book"); cPane = appFrame.getContentPane(); cPane.setLayout(new GridBagLayout()); //Arrange components on contentPane and set Action Listeners to each JButton arrangeComponents(); appFrame.setSize(240,300); appFrame.setResizable(false); appFrame.setVisible(true); } public void arrangeComponents() { jlbName = new JLabel("Name"); jlbAddress = new JLabel("Address"); jlbPhone = new JLabel("Phone"); jlbEmail = new JLabel("Email"); jtfName = new JTextField(20); jtfAddress = new JTextField(20); jtfPhone = new JTextField(20); jtfEmail = new JTextField(20); jbbSave = new JButton("Save"); jbnDelete = new JButton("Delete"); jbnClear = new JButton("Clear"); jbnUpdate = new JButton("Update"); jbnSearch = new JButton("Search"); jbnForward = new JButton(">>"); jbnBack = new JButton(""); jbnExit = new JButton("Exit"); /*add all initialized components to the container*/ GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints(); gridBagConstraintsx01.gridx = 0; gridBagConstraintsx01.gridy = 0; gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5); cPane.add(jlbName, gridBagConstraintsx01); GridBagConstraints gridBagConstraintsx02 = new GridBagConstraints(); gridBagConstraintsx02.gridx = 1; gridBagConstraintsx02.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx02.gridy = 0; gridBagConstraintsx02.gridwidth = 2; gridBagConstraintsx02.fill = GridBagConstraints.BOTH; cPane.add(jtfName, gridBagConstraintsx02); GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints(); gridBagConstraintsx03.gridx = 0; gridBagConstraintsx03.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx03.gridy = 1; cPane.add(jlbAddress, gridBagConstraintsx03); GridBagConstraints gridBagConstraintsx04 = new GridBagConstraints(); gridBagConstraintsx04.gridx = 1; gridBagConstraintsx04.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx04.gridy = 1; gridBagConstraintsx04.gridwidth = 2; gridBagConstraintsx04.fill = GridBagConstraints.BOTH; cPane.add(jtfAddress, gridBagConstraintsx04); GridBagConstraints gridBagConstraintsx05 = new GridBagConstraints(); gridBagConstraintsx05.gridx = 0; gridBagConstraintsx05.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx05.gridy = 2; cPane.add(jlbPhone, gridBagConstraintsx05); GridBagConstraints gridBagConstraintsx06 = new GridBagConstraints(); gridBagConstraintsx06.gridx = 1; gridBagConstraintsx06.gridy = 2; gridBagConstraintsx06.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx06.gridwidth = 2; gridBagConstraintsx06.fill = GridBagConstraints.BOTH; cPane.add(jtfPhone, gridBagConstraintsx06); GridBagConstraints gridBagConstraintsx07 = new GridBagConstraints(); gridBagConstraintsx07.gridx = 0; gridBagConstraintsx07.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx07.gridy = 3; cPane.add(jlbEmail, gridBagConstraintsx07); GridBagConstraints gridBagConstraintsx08 = new GridBagConstraints(); gridBagConstraintsx08.gridx = 1; gridBagConstraintsx08.gridy = 3; gridBagConstraintsx08.gridwidth = 2; gridBagConstraintsx08.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx08.fill = GridBagConstraints.BOTH; cPane.add(jtfEmail, gridBagConstraintsx08); GridBagConstraints gridBagConstraintsx09 = new GridBagConstraints(); gridBagConstraintsx09.gridx = 0; gridBagConstraintsx09.gridy = 4; gridBagConstraintsx09.insets = new Insets(5, 5, 5, 5); cPane.add(jbbSave, gridBagConstraintsx09); GridBagConstraints gridBagConstraintsx10 = new GridBagConstraints(); gridBagConstraintsx10.gridx = 1; gridBagConstraintsx10.gridy = 4; gridBagConstraintsx10.insets = new Insets(5, 5, 5, 5); cPane.add(jbnDelete, gridBagConstraintsx10); GridBagConstraints gridBagConstraintsx11 = new GridBagConstraints(); gridBagConstraintsx11.gridx = 2; gridBagConstraintsx11.gridy = 4; gridBagConstraintsx11.insets = new Insets(5, 5, 5, 5); cPane.add(jbnUpdate, gridBagConstraintsx11); GridBagConstraints gridBagConstraintsx12 = new GridBagConstraints(); gridBagConstraintsx12.gridx = 0; gridBagConstraintsx12.gridy = 5; gridBagConstraintsx12.insets = new Insets(5, 5, 5, 5); cPane.add(jbnBack, gridBagConstraintsx12); GridBagConstraints gridBagConstraintsx13 = new GridBagConstraints(); gridBagConstraintsx13.gridx = 1; gridBagConstraintsx13.gridy = 5; gridBagConstraintsx13.insets = new Insets(5, 5, 5, 5); cPane.add(jbnSearch, gridBagConstraintsx13); GridBagConstraints gridBagConstraintsx14 = new GridBagConstraints(); gridBagConstraintsx14.gridx = 2; gridBagConstraintsx14.gridy = 5; gridBagConstraintsx14.insets = new Insets(5, 5, 5, 5); cPane.add(jbnForward, gridBagConstraintsx14); GridBagConstraints gridBagConstraintsx15 = new GridBagConstraints(); gridBagConstraintsx15.gridx = 1; gridBagConstraintsx15.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx15.gridy = 6; cPane.add(jbnClear, gridBagConstraintsx15); GridBagConstraints gridBagConstraintsx16 = new GridBagConstraints(); gridBagConstraintsx16.gridx = 2; gridBagConstraintsx16.gridy = 6; gridBagConstraintsx16.insets = new Insets(5, 5, 5, 5); cPane.add(jbnExit, gridBagConstraintsx16); jbbSave.addActionListener(this); jbnDelete.addActionListener(this); jbnClear.addActionListener(this);
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in } else { lastNumber = numberInDisplay; } clearOnNextDigit = true; lastOperator = op; } } void processEquals() { double result = 0; if (displayMode != ERROR_MODE) { try { result = processLastOperator(); displayResult(result); } catch (DivideByZeroException e) { displayError("Cannot divide by zero!"); } lastOperator = "0"; } } double processLastOperator() throws DivideByZeroException { double result = 0; double numberInDisplay = getNumberInDisplay(); if (lastOperator.equals("/")) { if (numberInDisplay == 0) throw (new DivideByZeroException()); result = lastNumber / numberInDisplay; } if (lastOperator.equals("*")) result = lastNumber * numberInDisplay; if (lastOperator.equals("-")) result = lastNumber - numberInDisplay; if (lastOperator.equals("+")) result = lastNumber + numberInDisplay; return result; } void displayResult(double result) { setDisplayString(Double.toString(result)); lastNumber = result; displayMode = RESULT_MODE; clearOnNextDigit = true; } void displayError(String errorMessage) { setDisplayString(errorMessage); lastNumber = 0; displayMode = ERROR_MODE; clearOnNextDigit = true; } public static void main(String args[]) { Calculator calci = new Calculator(); Container contentPane = calci.getContentPane(); // contentPane.setLa yout(new BorderLayout()); calci.setTitle("Java Swing Calculator"); calci.setSize(241, 217); calci.pack(); calci.setLocation(400, 250); calci.setVisible(true); calci.setResizable(false); } } //End of Swing Calculator Class. class DivideByZeroException extends Exception { public DivideByZeroException() { super(); } public DivideByZeroException(String s) { super(s); } } class CustomABOUTDialog extends JDialog implements ActionListener { JButton jbnOk; CustomABOUTDialog(JFrame parent, String title, boolean modal) { super(parent, title, modal); setBackground(Color.black); JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER)); StringBuffer text = new StringBuffer(); text.append("Calculator Information\n\n"); text.append("Developer: Hemanth\n"); text.append("Version: 1.0"); JTextArea jtAreaAbout = new JTextArea(5, 21); jtAreaAbout.setText(text.toString()); jtAreaAbout.setFont(new Font("Times New Roman", 1, 13)); jtAreaAbout.setEditable(false); p1.add(jtAreaAbout); p1.setBackground(Color.red); getContentPane().add(p1, BorderLayout.CENTER); JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER)); jbnOk = new JButton(" OK "); jbnOk.addActionListener(this); p2.add(jbnOk); getContentPane().add(p2, BorderLayout.SOUTH); setLocation(408, 270); setResizable(false); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Window aboutDialog = e.getWindow(); aboutDialog.dispose(); } }); pack(); } public void actionPerformed(ActionEvent e) { if (e.getSource() == jbnOk) { this.dispose(); } } }
Download Java Calculator Source Code
Content Downloaded From www.javabeginner.com
Created By www.ebooktutorials.blogspot.in personsList = new ArrayList(); // creating PersonDAO object pDAO = new PersonDAO(); } public void createGUI(){ /*Create a frame, get its contentpane and set layout*/ appFrame = new JFrame("Address Book"); cPane = appFrame.getContentPane(); cPane.setLayout(new GridBagLayout()); //Arrange components on contentPane and set Action Listeners to each JButton arrangeComponents(); appFrame.setSize(240,300); appFrame.setResizable(false); appFrame.setVisible(true); } public void arrangeComponents() { jlbName = new JLabel("Name"); jlbAddress = new JLabel("Address"); jlbPhone = new JLabel("Phone"); jlbEmail = new JLabel("Email"); jtfName = new JTextField(20); jtfAddress = new JTextField(20); jtfPhone = new JTextField(20); jtfEmail = new JTextField(20); jbbSave = new JButton("Save"); jbnDelete = new JButton("Delete"); jbnClear = new JButton("Clear"); jbnUpdate = new JButton("Update"); jbnSearch = new JButton("Search"); jbnForward = new JButton(">>"); jbnBack = new JButton(""); jbnExit = new JButton("Exit"); /*add all initialized components to the container*/ GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints(); gridBagConstraintsx01.gridx = 0; gridBagConstraintsx01.gridy = 0; gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5); cPane.add(jlbName, gridBagConstraintsx01); GridBagConstraints gridBagConstraintsx02 = new GridBagConstraints(); gridBagConstraintsx02.gridx = 1; gridBagConstraintsx02.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx02.gridy = 0; gridBagConstraintsx02.gridwidth = 2; gridBagConstraintsx02.fill = GridBagConstraints.BOTH; cPane.add(jtfName, gridBagConstraintsx02); GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints(); gridBagConstraintsx03.gridx = 0; gridBagConstraintsx03.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx03.gridy = 1; cPane.add(jlbAddress, gridBagConstraintsx03); GridBagConstraints gridBagConstraintsx04 = new GridBagConstraints(); gridBagConstraintsx04.gridx = 1; gridBagConstraintsx04.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx04.gridy = 1; gridBagConstraintsx04.gridwidth = 2; gridBagConstraintsx04.fill = GridBagConstraints.BOTH; cPane.add(jtfAddress, gridBagConstraintsx04); GridBagConstraints gridBagConstraintsx05 = new GridBagConstraints(); gridBagConstraintsx05.gridx = 0; gridBagConstraintsx05.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx05.gridy = 2; cPane.add(jlbPhone, gridBagConstraintsx05); GridBagConstraints gridBagConstraintsx06 = new GridBagConstraints(); gridBagConstraintsx06.gridx = 1; gridBagConstraintsx06.gridy = 2; gridBagConstraintsx06.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx06.gridwidth = 2; gridBagConstraintsx06.fill = GridBagConstraints.BOTH; cPane.add(jtfPhone, gridBagConstraintsx06); GridBagConstraints gridBagConstraintsx07 = new GridBagConstraints(); gridBagConstraintsx07.gridx = 0; gridBagConstraintsx07.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx07.gridy = 3; cPane.add(jlbEmail, gridBagConstraintsx07); GridBagConstraints gridBagConstraintsx08 = new GridBagConstraints(); gridBagConstraintsx08.gridx = 1; gridBagConstraintsx08.gridy = 3; gridBagConstraintsx08.gridwidth = 2; gridBagConstraintsx08.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx08.fill = GridBagConstraints.BOTH; cPane.add(jtfEmail, gridBagConstraintsx08); GridBagConstraints gridBagConstraintsx09 = new GridBagConstraints(); gridBagConstraintsx09.gridx = 0; gridBagConstraintsx09.gridy = 4; gridBagConstraintsx09.insets = new Insets(5, 5, 5, 5); cPane.add(jbbSave, gridBagConstraintsx09); GridBagConstraints gridBagConstraintsx10 = new GridBagConstraints(); gridBagConstraintsx10.gridx = 1; gridBagConstraintsx10.gridy = 4; gridBagConstraintsx10.insets = new Insets(5, 5, 5, 5); cPane.add(jbnDelete, gridBagConstraintsx10); GridBagConstraints gridBagConstraintsx11 = new GridBagConstraints(); gridBagConstraintsx11.gridx = 2; gridBagConstraintsx11.gridy = 4; gridBagConstraintsx11.insets = new Insets(5, 5, 5, 5); cPane.add(jbnUpdate, gridBagConstraintsx11); GridBagConstraints gridBagConstraintsx12 = new GridBagConstraints(); gridBagConstraintsx12.gridx = 0; gridBagConstraintsx12.gridy = 5; gridBagConstraintsx12.insets = new Insets(5, 5, 5, 5); cPane.add(jbnBack, gridBagConstraintsx12); GridBagConstraints gridBagConstraintsx13 = new GridBagConstraints(); gridBagConstraintsx13.gridx = 1; gridBagConstraintsx13.gridy = 5; gridBagConstraintsx13.insets = new Insets(5, 5, 5, 5); cPane.add(jbnSearch, gridBagConstraintsx13); GridBagConstraints gridBagConstraintsx14 = new GridBagConstraints(); gridBagConstraintsx14.gridx = 2; gridBagConstraintsx14.gridy = 5; gridBagConstraintsx14.insets = new Insets(5, 5, 5, 5); cPane.add(jbnForward, gridBagConstraintsx14); GridBagConstraints gridBagConstraintsx15 = new GridBagConstraints(); gridBagConstraintsx15.gridx = 1; gridBagConstraintsx15.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx15.gridy = 6; cPane.add(jbnClear, gridBagConstraintsx15); GridBagConstraints gridBagConstraintsx16 = new GridBagConstraints(); gridBagConstraintsx16.gridx = 2; gridBagConstraintsx16.gridy = 6; gridBagConstraintsx16.insets = new Insets(5, 5, 5, 5); cPane.add(jbnExit, gridBagConstraintsx16); jbbSave.addActionListener(this); jbnDelete.addActionListener(this); jbnClear.addActionListener(this);
Content Downloaded From www.javabeginner.com