Sei sulla pagina 1di 29

Unit 5 : Arrays in Java

5.1. Objective 5.2. Introduction: 5.3. The one-dimensional array 5.4. Multidimensional arrays 5.5. Working with Characters and strings 5.5.1 Important string methods 5.6. Formatting data for output 5.7. Swing 5.7.1. Layout managers
5.7.1.1 Flow layout 5.7.1.2 Box layout 5.7.1.3 Grid layout 5.7.1.4 Border layout 5.3.1 5.3.2 Array Declaration Array Instantiation

5.7.2Advanced layout managers 5.7.2.1 CardLayout 5.7.2.2 GridBagLayout 5.8.Advanced swing components 5.9.Solution of self learning exercise 5.10. Exercise 5.11. Summary 5.12. Glossary 5.13. References
The objective of this unit is to make student familiar with storing data in a static memory location. Array is one among the many beautiful things you have in a programming language. Easy to iterate, easy to store and retrieve using their integer index. After learning this they also know Swing which is a part of JFC, Java Foundation Classes. It is a collection of packages for creating full featured desktop applications. Array is the most important thing in any programming language. An array is a group of variables that share the same name and are ordered sequentially from zero to one less than the number of variables in the array. The number of variables that can be stored in an array is called the array's dimension. Each variable in the array is called an element of the array. By definition, array is the static memory allocation. It allocates the memory for the same data type in sequence. It contains multiple values of same types. It also store the

5.1.Objective:

5.2. Introduction:

values in memory at the fixed size. Multiple types of arrays are used in any programming language such as: one - dimensional, two - dimensional or can say multi - dimensional.

Though you view the array as cells of values, internally they are cells of variables. A java array is a group of variables referenced by a common name. Those variables are just references to a address and will not have a name. These are called the components of a java array. All the components must be of same type and that is called as component type of that java array. As we know that a n array is a group of variables that share the same name . The number of variables that can be stored in an array is called the arrays dimension. Using and array in your program is a following steps are required 5.3.1 Declaring Array An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

5.3. One dimensional array :

An array of ten elements Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8. 2

int [ ]marks; or int marks[ ]; 5.3.2 Initializing Array Inside the square bracket says that you are going to store number of values and is the size of the array n. When you refer the array values, the index starts from 0 zero to n1 . An array index is always a whole number and it can be a int, short, byte, or char. Once an array is instantiated, it size cannot be changed. Using the length field like can access its size. We can declare and allocate an array at the same time like this: int[] k = new int[3]; float[] yt = new float[7]; String[] names = new String[50]; We can even declare, allocate, and initialize an array at the same time providing a list of the initial values inside brackets like so: int[] k = {1, 2, 3}; float[] yt = {0.0f, 1.2f, 3.4f, -9.87f, 65.4f, 0.0f, 567.9f}; Java array initialization and instantiation together int marks[] = {98, 95, 91, 93, 97}: An example to sort a Java array-java api Arrays contains static methods for sorting. It is a best practice to use them always to sort an array. import java.util.Arrays; public class ArraySort { public static void main(String args[]) { int marks[] = { 98, 95, 91, 93, 97 }; System.out.println("Before sorting: " + Arrays.toString(marks)); Arrays.sort(marks); System.out.println("After sorting: " + Arrays.toString(marks)); } } Output look like //Before sorting: [98, 95, 91, 93, 97] //After sorting: [91, 93, 95, 97, 98] The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to standard output. class ArrayDemo { public static void main(String[] args) {

int[] anArray;

// declares an array of integers

anArray = new int[10]; // allocates memory for 5 integers anArray[0] = 100; // initialize first element anArray[1] = 200; // initialize second element anArray[2] = 300; // etc. anArray[3] = 400; anArray[4] = 500; System.out.println("Element at index 0: System.out.println("Element at index 1: System.out.println("Element at index 2: " System.out.println("Element at index 3: " System.out.println("Element at index 4: " } + anArray[0]); + anArray[1]); + anArray[2]); + anArray[3]); + anArray[4]);

} The output from this program is: Element at index 0: 100 Element at index 1: 200 Element at index 2: 300 Element at index 3: 400 Element at index 4: 500 Java Array Default Values After you instantiate an array, default values are automatically assigned to it in the following manner. byte default value is zero short default value is zero int default value is zero long default value is zero, 0L. float default value is zero, 0.0f. double default value is zero, 0.0d. char default value is null, \u0000 . boolean default value is false. reference types default value is null. Notice in the above list, the primitives and reference types are treated differently. One popular cause of NullPointerException is accessing a null from a java array. Iterating a Java Array public static void main(String args[]) { int marks[] = {98, 95, 91, 93, 97}; //java array iteration using enhanced for loop for (int value : marks){ System.out.println(value); }

} In language C, array of characters is a String but this is not the case in java arrays. But the same behaviour is implemented as a StringBuffer where in the contents are mutable.

5.4. Multidimensional Arrays:

The arrays you have been using so far have only held one column of data. But you can set up an array to hold more than one column. These are called multi-dimensional arrays. Or we can say a Multidimensional arrays, are arrays of arrays. As an example, think of a spreadsheet with rows and columns. If you have 6 rows and 5 columns then your spreadsheet can hold 30 numbers. It might look like this:

A multi dimensional array is one that can hold all the values above. You set them up like this: int[ ][ ] aryNumbers = new int[6][5]; They are set up in the same way as a normal array, except you have two sets of square brackets. The first set of square brackets is for the rows and the second set of square brackets is for the columns. In the above line of code, we're telling Java to set up an array with 6 rows and 5 columns. To hold values in a multi-dimensional array you have to take care to track the rows and columns. Here's some code to fill the first rows of numbers from our spreadsheet image: aryNumbers[0][0] = 10; aryNumbers[0][1] = 12; aryNumbers[0][2] = 43; aryNumbers[0][3] = 11; aryNumbers[0][4] = 22; So the first row is row 0. The columns then go from 0 to 4, which is 5 items. To fill the second row, it would be this: aryNumbers[1][0] = 20; aryNumbers[1][1] = 45; aryNumbers[1][2] = 56; aryNumbers[1][3] = 1; aryNumbers[1][4] = 33; The column numbers are the same, but the row numbers are now all 1. To access all the items in a multi-dimensional array the technique is to use one loop inside of another. We can also use 3D array .The syntax for three dimensional arrays is a direct extension of that for two-dimensional arrays. Here's a program that declares, allocates and initializes a three-dimensional array:

class Fill3DArray { public static void main (String args[]) { int[][][] M; M = new int[4][5][3]; for (int row=0; row < 4; row++) { for (int col=0; col < 5; col++) { for (int ver=0; ver < 3; ver++) { M[row][col][ver] = row+col+ver; } } } } } Self learning Exercise : 1. Write an program to show the sum of row and column indices.

String manipulation is an important part of java programming. String can be represented as a sequence of characters array. The following way we can represent character array. Char chararray[ ] =new char [4]; chararray[0]=J; chararray[1]=A; chararray[2]=V; chararray[3]=A; Example : public class chararray { public static void main(String[] args){ char[] myName=new char [10]; myName[0]= 'r'; myName[1]= 'a'; myName[2]= 'm; System.out.println("my name is:"); for (int i=0; i< myName.length;i++){ System.out.println(" "+myName[i]); } } } Self learning Exercise : 6

5.5. Working with Characters and strings:

2. Write a program to enter string JAVA PROGRAMMING and count vowel in this string of characters. example: The following program, ArrayCopyDemo, declares an array of char elements, spelling the word "decaffeinated". It uses arraycopy to copy a subsequence of array components into a second array: class ArrayCopyDemo { public static void main(String[] args) { char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; char[] copyTo = new char[7]; System.arraycopy(copyFrom, 2, copyTo, 0, 7); System.out.println(new String(copyTo));

} The output from this program is: Caffeine Example: /*Convert String to Character Array Example This example shows how to convert a given String object to an array of character*/ public class StringToCharacterArrayExample { public static void main(String args[]){ //declare the original String object String strOrig = "Hello World"; //declare the char array char[] stringArray; //convert string into array using toCharArray() method of string class stringArray = strOrig.toCharArray(); //display the array for(int index=0; index < stringArray.length; index++) System.out.print(stringArray[index]); } } /*Output of the program would be :Hello World*/ You can place strings of text into arrays. This is done in the same way as for integers: String[ ] aryString = new String[5] ; or String arystring ; arystring =new String (string); Example: public static void main(String args[]){

String[ ] aryString = new String[5] ; aryString[0] = "This"; aryString[1] = "is"; aryString[2] = "a"; aryString[3] = "string"; aryString[4] = "array"; for ( int i=0; i < aryString.length; i++ ) { System.out.println( aryString[i] ); }} The loop goes round and round while the value in the variable called i is less than the length of the array called aryString. When the above programme is run, the Output window will look like this: This is a string array 5.5.1 Important String Methods: Following are most commonly used methods in the String class. (a) concat(): This method returns a string with the value of string passed in to the method appended to the end of String which used to invoke the method. example: public String concat(String s) String s="java"; System.out.println(s.concat("programming")); Note:-Always use assignment operator in case of concat operator otherwise concat will be unreferenced and you will get old String.example s.concat("programming"); System.out.println(s); It will present output as " java" different than what we have expected.So always be careful in using the assignment operator in String method calls. (b)charAt(): This method returns a specific character located at the String's specific index.Remember,String indexes are zero based Example: public charAt(int index) String s="java programming"; System.out.println(s.charAt(0)); The output is 'j' (c )length():This method returns the length of the String used to invoke the method. example:-

public int length() String s="name"; System.out.println(s.length()); The output is 4 (d) replace(): This method return a String whose value is that of the String to invoke the method ,updated so that any occurrence of the char in the first argument is replaced by the char in the second argument . public String replace(char old,char new) Example:String s="abc"; System.out.println(s.replace('a','A')); The output is Abc (e) equalsIgnoreCase(): This method returns a Boolean value depending on whether the value of the string in the argument is the same as the String used to invoke the method.This method will return true even when character in the string object being compared have different cases. public boolean equalsIgnoreCase(String s) Example:String s="java"; System.out.println(s.equalsIgnoreCase("JAVA")); The output is true (f) substring(): substring method is used to return a part or substring of the String used to invoke the method.The first argument represents the starting location of the substring.Remember the indexes are zero based. public String substring(int begin) / public String substring(int begin,int end) example:String s="abcdefghi"; System.out.println(s.substring(5)); System.out.println(s.substring(5,8)); The output would be " fghi " " fg " (g) toLowerCase( ): This method returns a string whose value is the String used to invoke the method,but with any uppercase converted to lowercase.:-

public String toLowerCase() String s="AbcdefghiJ"; System.out.println(s.toLowerCase()); Output is " abcdefghij " (h) trim( ): This method returns a String whose value is the String used to invoke the method ,but with any leading or trailing blank spaces removed. public String trim() Example:String s="hey here is the blank space "; System.out.println(s.trim()) The output is " heyhereistheblankspace" (i) toUpper() : This method returns a String whose value is String used to invoke the method ,but with any lowercase character converted to uppercase. public String toUpperCase() Example:String s="AAAAbbbbb"; System.out.println(s.to UpperCase()); The output is " aaaabbbbb " Above mentioned String methods are most commonly used in String class.Do remember them or otherwise I am always up for you and of course you can refer this site every time you need something.

5.6. Formatted Data output:


Java 5 implements formatted output with printf() .Earlier you saw the use of the print and println methods for printing strings to standard output (System.out). Since all numbers can be converted to strings. format(). Amazingly, there was no built-in way to right justify numbers in Java until Java 5. You had to use if or while to build the padding yoursefl. Java 5 now provides the format() method (and in some cases also the equivalent printf() method from C).. The format() method's first parameter is a string that specifies how to convert a number. For integers you would typically use a "%" followed by the number of columns you want the integer to be right justified in, followed by a decimal conversion specifier "d". The second parameter would be the number you want to convert. For example, int n = 2;

10

System.out.format("%3d", n); This would print the number in three columns that is with two blanks followed by 2. You can put other non-% characters in front or back of the conversion specification, and they will simply appear literally. For example, int n = 2; System.out.format("| %3d |", n); would print | 2| The following better show you in different way to use formatimport java.util.Calendar; public class TestFormat { public static void main(String[] args) { long n = 461012; System.out.format("%d%n", n); // --> "461012" System.out.format("%08d%n", n); // --> "00461012" System.out.format("%+8d%n", n); // --> " +461012" System.out.format("%,8d%n", n); // --> " 461,012" System.out.format("%+,8d%n%n", n); // --> "+461,012" double pi = Math.PI; System.out.format("%f%n", pi); // --> "3.141593" System.out.format("%.3f%n", pi); // --> "3.142" System.out.format("%10.3f%n", pi); // --> " 3.142" System.out.format("%-10.3f%n", pi); // --> "3.142" Calendar c = Calendar.getInstance(); System.out.format("%tB %te, %tY%n", c, c, c); // --> "May 29, 2006" System.out.format("%tl:%tM %tp%n", c, c, c); // --> "2:34 am" System.out.format("%tD%n", c); // --> "05/29/06"

Note : java.util.Calendar //Java Notesjava.util.Calendar The java.util.Calendar class is used to represent the date and time. The year, month, day, hour, minute, second, and milliseconds can all be set or obtained from a Calendar object.

5.7. Swing:

11

Swing is a part of JFC, Java Foundation Classes. It is a collection of packages for creating full featured desktop applications. JFC consists of AWT, Swing, Accessibility, Java 2D, and Drag and Drop. Swing was released in 1997 with JDK 1.2. Swing is an advanced GUI toolkit. It has a rich set of widgets . It is called SWT. The Standard widget toolkit. Swing library is an official Java GUI toolkit released by Sun Microsystems. It is used to create Graphical user interfaces with Java. From basic widgets like buttons, labels, scrollbars to advanced widgets like trees and tables. Swing itself is written in Java. The main characteristics of the Swing toolkit is that it is platform independent, customizable, extensible, configurable ,lightweight. The Swing API has 18 public packages: javax.accessibility javax.swing javax.swing.border javax.swing.colorchooser javax.swing.event javax.swing.filechooser javax.swing.plaf javax.swing.plaf.basic javax.swing.plaf.metal javax.swing.plaf.multi javax.swing.plaf.synth javax.swing.table javax.swing.text javax.swing.text.html javax.swing.text.html.parser javax.swing.text.rtf javax.swing.tree javax.swing.undo There are basically two types of widget toolkits. Lightweight and ` Heavyweight The SWT is an example of a heavyweight toolkit . 5.7.1 Layout manager: The user limited to either by command line (keyboard) input and visual display unit (VDU) output, or by file I/O. These have had limited visual appeal or impact, but are suited to simple applications and automated operations. The layout mangers and responding to user input will be discussed. Layout managers are used to arrange the components on the interface. The layout managers available are:

12

5.7.1.1 Flow layout: The flow layout is the simplest layout manager. This arranges the components in rows from left to right, in a similar way to which words in sentences are laid out,

This is the simplest layout manager in the Java Swing toolkit. It is mainly used in combination with other layout managers. When calculating its children size, a flow layout lets each component assume its natural (preferred) size. The manager puts components into a row. In the order, they were added. If they do not fit into one row, they go into the next one. The components can be added from the right to the left or vice versa. The manager allows to align the components. Implicitly, the components are centered and there is 5px space among components and components and the edges of the container. FlowLayout() FlowLayout(int align) FlowLayout(int align, int hgap, int vgap) FlowLayout() method is called without arguments, the components are aligned to the enter of the container. If the argument is FlowLayout.RIGHT , then the components are aligned to the right of the container, if the argument is FlowLayout.LEFT , then the components are aligned to the left of the container, and the argument is FlowLayout.CENTER , then the components are aligned to the enter of the container. 5.7.1.2 Box layout: The box layout is used to arrange components in a layout from top to bottom and left to

The BoxLayout class in the java.swing package is used. This is supplied with two arguments:

13

1. The name of the container it is to manage. 2. A class variable to set-up the vertical or horizontal alignment. This alignment will be one of two values: a. X_AXIS For left-to-right alignment. b. Y_AXIS For top-to-bottom alignment. 5.7.1.3 Grid layout: The grid layout is used to arrange components in a grid of rows and columns, In our first example, we will show a basic window on the screen.

The GridLayout class in the java.awt package is used. The GridLayout() constructor has four arguments (integer numbers): GridLayout(1, 2, 3, 4). where: 1. Number of rows. 2. Number of columns. 3. Horizontal gap in pixels. 4. Vertical gap in pixels. Consider the example GUI shown in figure. Here, there are four buttons and four labels placed in panel within the frame using the grid layout manager.

Figure shows the source code for this GUI. Note that that there are no actions programmed so the interface buttons do not respond to user input. Here: The GUI title is GUI 5 . 14

Four buttons are created. Four labels are created. The buttons and labels are placed within a panel. The buttons may be pressed but there are no button pressed actions programmed.# The window is closed by pressing the mouse button whilst the mouse pointer is over the cross in the title bar. // Java application to implement a simple Graphical User Interface (GUI) // using Swing. import javax.swing.*; import java.awt.*; import java.awt.event.*; //----------------------------------------------------------------------------public class Swing4 extends JFrame { JButton oneButton = new JButton("One"); JButton twoButton = new JButton("Two"); JButton threeButton = new JButton("Three"); JButton fourButton = new JButton("Quit"); JLabel oneLabel = new JLabel("LABELS"); JLabel twoLabel = new JLabel("Label 1"); JLabel threeLabel = new JLabel("Label 2"); JLabel fourLabel = new JLabel("Label 3"); //-----------------------------------------------------------------------------// Constructor Class to set up the GUI //-----------------------------------------------------------------------------public Swing4() { super("GUI 5"); setSize(500, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel1 = new JPanel(); GridLayout grid1 = new GridLayout(2, 4, 5, 10);

15

panel1.add(oneButton); panel1.add(twoButton); panel1.add(threeButton); panel1.add(fourButton); panel1.add(oneLabel); panel1.add(twoLabel); panel1.add(threeLabel); panel1.add(fourLabel); panel1.setLayout(grid1); add(panel1); } // main method public static void main(String[] args) { Swing4 sf = new Swing4(); sf.setVisible(true); } } End of File Grid example code (2) 5.7.1.4 Border layout The border layout is used to arrange components into five sections,

16

The BorderLayout class in the java.awt package is used. The components in the four outer sections use as much space as they require, and the center section gets the remaining available space. The border layout is created using one of two constructors: 1. BorderLayout() Creates a border layout without any gap between the components. 2. BorderLayour(int, int) Creates a border layout with a horizontal(first int number)and vertical gap (second int number) gap between the components.A simple user interface will place components within the frame. However, in order to manage more complex user interfaces, then smaller containers (panels) are used. Components are placed within the panels and the panels are placed within the frame. Panels use the JPanel class, by calling the JPanel() constructor. The setLayout() method is called to set the layout manager for the panel. package zetcode; import javax.swing.JFrame; import javax.swing.SwingUtilities; public class Example extends JFrame { public Example() { setTitle("Simple example"); setSize(300, 200); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); }

17

public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Example ex = new Example(); ex.setVisible(true); } }); } } While this code is very small, the application window can do quite a lot. It can be resized, maximized, minimized. All the complexity that comes with it has been hidden from the application programmer. Here is another type of the CheckboxDemo applet shown in the previous articles, such that it uses left-aligned flow layout. Code: import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="FlowLayoutTest" width=250 height=200> </applet> */ public class FlowLayoutTest extends Applet implements ItemListener { String str = ""; Checkbox Go4expert, codeitwell,mbaguys; Label l1; public void init() { // set left-aligned flow layout setLayout(new FlowLayout(FlowLayout.LEFT)); l1=new Label("Select the Best site:"); Go4expert = new Checkbox("Go4expert.com", null, true);

18

codeitwell = new Checkbox("codeitwell.com "); mbaguys = new Checkbox("mbaguys.net"); add(l1); add(Go4expert); add(codeitwell); add(mbaguys); // register to receive item events Go4expert.addItemListener(this); codeitwell.addItemListener(this); mbaguys.addItemListener(this); } // Repaint when status of a check box changes. public void itemStateChanged(ItemEvent ie) { repaint(); } // Display current state of the check boxes. public void paint(Graphics g) { str = "Go4expert.com : " + Go4expert.getState(); g.drawString(str, 6, 100); str = "codeitwell.com: " + codeitwell.getState(); g.drawString(str, 6, 120); str = "mbaguys.net : " + mbaguys.getState(); g.drawString(str, 6, 140); } }

19

Output would be as shown below:-

BorderLayout The BorderLayout class implements a common layout style for top-level windows. It has four narrow, fixed-width components at the edges and one large area in the center. The four sides are referred to as north, south, east, and west. The middle area is called the center. The constructors defined by BorderLayout are shown below: BorderLayout( ) BorderLayout(int horz, int vert) The first form creates a default border layout. The second allows you to specify the horizontal and vertical space left between components in horz and vert, respectively. BorderLayout defines the following constants that specify the regions: BorderLayout.CENTER BorderLayout.SOUTH BorderLayout.EAST BorderLayout.WEST BorderLayout.NORTH 5.7.2 Advance layout managers: 5.7.2.1 CardLayout: The CardLayout class is unique among the other layout managers in that it stores several different layouts. Each layout can be thought of as being on a separate index card in a deck that can be shuffled so that any card is on top at a given time. This can be useful for user interfaces with optional components that can be dynamically enabled and disabled 20

upon user input. We can prepare the other layouts and have them hidden, ready to be activated when needed. CardLayout provides the following two constructors: CardLayout( ) CardLayout(int horz, int vert) The first form creates a default card layout. The second form allows you to specify the horizontal and vertical space left between components in horz and vert, respectively. Use of a card layout requires a bit more work than the other layouts. The cards are typically held in an object of type Panel. This panel must have CardLayout selected as its layout manager. The cards that form the deck are also typically objects of type Panel. Thus, you must create a panel that contains the deck and a panel for each card in the deck and you add to the appropriate panel the components that form each card. You then add these panels to the panel for which CardLayout is the layout manager. Finally, you add this panel to the main applet panel. Once these steps are complete, you must provide some way for the user to select between cards. One common approach is to include one push button for each card in the deck. When card panels are added to a panel, they are usually given a name. Most of the time, you will use this form of add( ) when adding cards to a panel: void add(Component panelObj, Object name); Here, name is a string that specifies the name of the card whose panel is specified by panelObj. Example: aranges GUI components into a "deck" of cards where only the top card is visible, any card in the deck can be placed at the top (thus visable). Each card is normally a Panel which can use any layout manager. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class CardDeck extends JFrame implements ActionListener { private CardLayout cardManager; private JPanel deck; private JButton controls[]; private String names[] = { "First card", "Next card", "Previous card", "Last card" }; public CardDeck()

21

{ super( "CardLayout " ); Container c = getContentPane(); // create the JPanel with CardLayout deck = new JPanel(); cardManager = new CardLayout(); deck.setLayout( cardManager ); // set up card1 and add it to JPanel deck JLabel label1 = new JLabel( "card one", SwingConstants.CENTER ); JPanel card1 = new JPanel(); card1.add( label1 ); deck.add( card1, label1.getText() ); // add card to deck // set up card2 and add it to JPanel deck JLabel label2 = new JLabel( "card two", SwingConstants.CENTER ); JPanel card2 = new JPanel(); card2.setBackground( Color.yellow ); card2.add( label2 ); deck.add( card2, label2.getText() ); // add card to deck // set up card3 and add it to JPanel deck JLabel label3 = new JLabel( "card three" ); JPanel card3 = new JPanel(); card3.setLayout( new BorderLayout() ); card3.add( new JButton( "North" ), BorderLayout.NORTH ); card3.add( new JButton( "West" ), BorderLayout.WEST ); card3.add( new JButton( "East" ), BorderLayout.EAST ); card3.add( new JButton( "South" ), BorderLayout.SOUTH );

22

card3.add( label3, BorderLayout.CENTER ); deck.add( card3, label3.getText() ); // add card to deck // create and layout buttons that will control deck JPanel buttons = new JPanel(); buttons.setLayout( new GridLayout( 2, 2 ) ); controls = new JButton[ names.length ]; for ( int i = 0; i < controls.length; i++ ) { controls[ i ] = new JButton( names[ i ] ); controls[ i ].addActionListener( this ); buttons.add( controls[ i ] ); } // add JPanel deck and JPanel buttons to the applet c.add( buttons, BorderLayout.WEST ); c.add( deck, BorderLayout.EAST ); setSize( 450, 200 ); show(); } public void actionPerformed( ActionEvent e ) { if ( e.getSource() == controls[ 0 ] ) cardManager.first( deck ); // show first card else if ( e.getSource() == controls[ 1 ] ) cardManager.next( deck ); // show next card else if ( e.getSource() == controls[ 2 ] ) cardManager.previous( deck ); // show previous card else if ( e.getSource() == controls[ 3 ] )

23

cardManager.last( deck ); // show last card } public static void main( String args[] ) { CardDeck cardDeckDemo = new CardDeck(); cardDeckDemo.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } } 5.7.2.2 GridBagLayout: This is the most complex of the layout managers, it is the same as GridLayout but more flexible as the components can be different sizes.

5. 8. Advanced Swing Components:


Advanced swing components are 100% Swing-based components they help us to deliver Swing applications with professional and user-friendly interface. They are used by developers, who prefer to create own applications as fast as possible with the guarantee of high quality and outstanding performance. Advanced Swing Components fit all popular look and feels. Components are continually enhanced and improved upon and new versions are released frequently to ensure that you always have the most up-to-date and fully supported version available Components Animated Swing components JOutlookPanel- Microsoft Outlook-style component with custom renderers support. JSliderPanel- Component that allows to create sliding panels with various settings. JAnimatePanel- Component that allows to create user defined animated panels. 24

JXPMenu - Demonstrates the usage of JAnimatePanel, with sources. JTreeTable component JtreeTable- TreeTable Swing component that combines JTable and Jtree JSpanTable component JspanTable- JTable-based component with api to create table with cell span. Sortable and filterable Jtable SortedTableModel- TableModel with sorting support FilteredTableModel- TableModel with filtering support Components with quick search support JQuickTree- JTree with quick search capabilities and enhanced navigation. JQuickTable- JTable with quick search capabilities. JQuickList- JList with quick search capabilities JquickTextArea- JTextArea with quick search capabilities Autocomplete componentsJAutoTextField - JTextField with autocomplete support JAutoComboBox - JComboBox with autocomplete support Toolbar & Menubar MenuToolBarManager - Builds and configures toolbar and menu from XML JAscToolBar - JToolBar with advanced layout and extended controls ToolbarDockLayout - LayoutManager with different styles for dockable toolbar Hyperlink utilities HyperlinkUtil - Cross-platform utils for launching internet browser JHyperlinkLabel - Displays hyperlink and opens internet browser on mouse click Splash screen component JSplashScreen - Configurable splash screen Hyperlink utilities VM memory indicator JMemoryIndicator - Virtual machine memory indicator 25

Rotate components JVerticalButton - JButton with rotation support JVerticalToggleButton - JToggleButton with rotation support JVerticalLabel - JLabel with rotation support Font components JFontChooser - Provides a simple mechanism for the user to choose a font File components JAscFileChooser - JFileChooser that supports loading from XML FileChooserManager - Builds and configures file choosers and filters from XML AscFileFilter - Advanced FileFilter with mask support Drop down components JDropDownButton - JButton that provides popup menu with alternate actions Utility classes QuickGradientPaint - Optimized Paint for gradients WideTreeCellEditor - An editor that has tree object's width JAscFrame - JFrame that handles "Enter" and "Escape" key presses JAscDialog - JDialog that handles "Enter" and "Escape" key presses Advantages Extremely flexible and powerful Easy to use Complete documentation Partly open source Compatible with JDK 1.3, JDK 1.4, JDK 1.5, JDK 1.6 and JDK 1.7

5.9.Solution for self learning Exercise : 1. class FillArray {


public static void main (String args[]) { int[][] M; M = new int[4][5]; for (int row=0; row < 4; row++) { for (int col=0; col < 5; col++) { M[row][col] = row+col; 26

} }

} 2. public class CharArrayJava { public static void main(String [] args) { char [] subName = {'J','A','V','A','P','R','O','G','R','A','M',M,I,N,G}; int vowelCount = 0; for (int i = 0; i < subName.length; i++) { switch(subName[i]) { case('A'): vowelCount ++; break; case('E'): vowelCount ++; break; case('I'): vowelCount ++; break; case('O'): vowelCount ++; break; case('U'): vowelCount ++; break; } } System.out.println("Vowel count in subject name: " + vowelCount); } }

5.10.Exercise:
1. 2. 3. 4. 5. 6. 7.

What is an Array? Set up an array to hold the following values, and in this order: 23, 6, 47, 35, 2, 14. Write a program to get the average of all 6 numbers. Using the above values, have your program print out the highest number in the array. Set up an array to hold the following values, and in this order: 23, 6, 40, 36, 12, 4. Using the same array above, have your program print out only the odd numbers. Write a program to use multi dimension array and display output like _ Mr. Smith 27

Ms. Jones

5.11. Summary :
An array is the allocation a very common type of data structure where in all elements must be of the same data type. Once defined , the size of an array is fixed and cannot increase to accommodate more elements. The first element of an array starts with zero Arrays are data structures suitable for problems dealing with large quantities of identically typed data where similar operations need to be performed on every element. Elements of an array are accessible through their index values. Arrays using a single index are called vectors, those using indices are dimensional arrays. A two dimensional array is really an array of arrays, a 3-dim., an array of arrays of arrays, etc. Arrays have a type associated with them: the type of the elements. The index is always a nonnegative integer. Space has to be allocated explicitly for arrays. Either they are initialized with values and then the right amount of space is allocated or the keyword new is used to specify of space. Swing is a part of JFC, Java Foundation Classes. It is a collection of packages for creating full featured desktop applications. Swing is an advanced GUI toolkit. It has a rich set of widgets . It is called SWT. The Standard widget toolkit. It is used to create Graphical user interfaces with Java. From basic widgets like buttons, labels, scrollbars There are many layout managers Basic Layout Managers FlowLayout Default for java.applet.Applet, java.awt.Panel and java.swing.JPanel. Places components sequentially (left to right) in the order they were added You can specify the order. BorderLayout Default for the content panes of JFrame and JApplets. Arranges the components into five areas: North, South East, West and Center GridLayout Arranges the components into rows and columns BoxLayout Allows components to be arranged left-to-right or top-to-bottom in a container Advanced Layout Managers CardLayout GridBagLayout

5.12.Glossary :
Array Group of elements recognized by same name. GUI 28

Graphical user interfaces. JFC Java Foundation Classes. It is a collection of packages for creating full featured desktop applications. SWT Standard widget toolkit. It has a rich set of widgets ,basic widgets like buttons, labels, scrollbars

5.13. References:
1. programming with java by E Balagurusamy. Tata McGraw-Hill Publishing Company limited ,New Delhi. 2. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html.

29

Potrebbero piacerti anche