using objects chapter 6 “carcounter page 89 and 91 local variables declared in a method only...
TRANSCRIPT
Using ObjectsChapter 6
“CarCounter page 89 and 91
Local variables declared in a method only temporary
carCount is a local variable good only while the method exists. It is
an instance variable
Instantiation using random class
• Page 93 “RandomLines”
• Private Random randomPositions = new Random( );– xEnd = randomPositions.nextInt (100);– Using the method to generate a number from
the range 0 to 99
The Swing toolkit
• Imported as a Java library
• Components look the same on every platform (JButtons for example)
Events
• Action – like a button
• Change – adjust a slider
• “extends” current class (child) inherits from another class (parent)
Creating a JButton CarCounter extends JFame page 99
• Private JButton button;
• button = new JButton (“Car Enterng”);– Window.add(button);
• When button clicked actionListener called
General Guides for using objects
1. Determine what is to be imported
2. Select a constructor (with “new”) to be used
3. Add window, if needed
4. Use the instance via it’s methods
Page 102 SumTextFields uses JLabel class to display non-
changing text fields
• private JTextField number1Field, number2Field, sumField;
• JTextField class– A single line area to display text or input text– textField1 = new JTextField(15);– textField2 = new JTextField(“Hello!” ,15);– String s;– s = textField1.getText( );– textField1.setText(s);
JPanel class
• Used for drawing, or to hold objects such as buttons
• panel = new JPanel( );– Panel.setPreferedSize(new
Dimension(200,200));– window.add(panel);
Timer class
• Regularly spaced events
• timers, control speeds
• Not visible as Buttons are
TimerExamplepage 105
• Screenshot shows number of seconds
• Using timer.
JSlider“Raindrops” page 107
• private JSlider slider;
• slider = new JSlider(JSlider.HORIZONTAL, 200, 2000, 1000);
• window.add (slider);
• … gapField = new JTextField(10);
• gapField.setText(Integer.toString
• ( slider.getValue( ) ) );
Summary
• The Java language has a vast number of classes which you can (and ought to) use.
• Do not write your own code without investigating the libraries first.
• You may check http://www.java.sun.com and search tutorials and references about the various classes