Java Reference
In-Depth Information
When you create a Random object, you have to specify a seed or use the default seed. A
seed is a number used to initialize a random number generator. The no-arg constructor creates
a Random object using the current elapsed time as its seed. If two Random objects have the
same seed, they will generate identical sequences of numbers. For example, the following
code creates two Random objects with the same seed, 3 .
Random random1 = new Random( 3 );
System.out.print( "From random1: " );
for ( int i = 0 ; i < 10 ; i++)
System.out.print(random1.nextInt( 1000 ) + " " );
Random random2 = new Random( 3 );
System.out.print( "\nFrom random2: " );
for ( int i = 0 ; i < 10 ; i++)
System.out.print(random2.nextInt( 1000 ) + " " );
The code generates the same sequence of random int values:
From random1: 734 660 210 581 128 202 549 564 459 961
From random2: 734 660 210 581 128 202 549 564 459 961
Note
The ability to generate the same sequence of random values is useful in software testing
and many other applications. In software testing, often you need to reproduce the test
cases from a fixed sequence of random numbers.
same sequence
8.6.3
Displaying GUI Components
Pedagogical Note
Graphical user interface (GUI) components are good examples for teaching OOP. Simple
GUI examples are introduced here for this purpose. The full introduction to GUI pro-
gramming begins with Chapter 12, GUI Basics.
When you develop programs to create graphical user interfaces, you will use Java classes such
as JFrame , JButton , JRadioButton , JComboBox , and JList to create frames, buttons,
radio buttons, combo boxes, lists, and so on. Listing 8.5 is an example that creates two win-
dows using the JFrame class. The output of the program is shown in Figure 8.12.
F IGURE 8.12
The program creates two windows using the JFrame class.
L ISTING 8.5 TestFrame.java
1
import javax.swing.JFrame;
2
3
public class TestFrame {
4
public static void main(String[] args) {
JFrame frame1 = new JFrame();
create an object
invoke a method
5
6 frame1.setTitle( "Window 1" );
7 frame1.setSize( 200 , 150 );
8 frame1.setLocation( 200 , 100 );
9 frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
10 frame1.setVisible( true );
 
 
Search WWH ::




Custom Search