Overview of Java programming projects for 3345 Programming
Document Sample


Overview of Java
programming projects for
3345
Programming assignments: submission
•.java files via WebCT, you may put them in one folder and archive
them together
•readme.txt with instructions how to compile and run your code,
format of the input, your assumptions, known bugs and limitations
etc. Do not write: program is self-explanatory, contact me with
questions you may have.
•sample input and output files, if any
•makefile (optional)
•presentation of an assignment may be required, short questions may
be asked
Programming assignments:
development and coding
Submit neat well-indented code, part of the grade is for code
Provide enough comments (each variable (except loop iterators),
function, block of code)
For your own benefit, you may want to learn of javadoc or doxygen
Follow good naming conventions
Code optimization vs. development time and readability: the
example below is hard to read
for(;P("\n"),R-;P("|"))
for(e=C;e-;P("_"+(*u++/8)%2))P("|"+(*u/4)%2);
Programming assignments:
development and coding
Simple and working program is better than sophisticated and not
working one. Bells and whistles go unnoticed when the basic
functionality is poor.
Develop with re-using in mind: some of the routines of the first project
(input\output, GUI) may be reused in the second project
Always make backups and always keep a running copy of your code!
If stuck in debugging, localize (isolate) errors: comment all your code,
insert only the “Hello, world!” line. See whether the program runs,
gradually adding pieces of your code.
Programming assignments: run time issues
Catch exceptions, exit gracefully, acknowledge exiting.
One should be able to easily understand how to interact with the
program, i.e. give meaningful labels to input fields, prompt for
input in command-line interface.
Program should be easy to use
Don‟t hard-code the input data, yet you may use randomly
generated numbers as the input
Programming assignments
It was agreed in class that the following environments are used to develop
the projects:
NetBeans
JBuilder
JCreator
Eclipse
or text editor
Please, stick to these options. Download the latest version of your favorite
environment before you start.
Using Unix machines
Putty tool to connect to
apache.utdallas.edu, ssh net01
New rules: net01-net50 machines cannot be used in this class
javac to compile programs, java to run programs
Makefiles and tarballs
Honor code
OK to use provided code examples
No code from the book or web. If you need to use external code for
some additional features, clearly specify the parts of the code that
are not yours.
Projects are individual. Explicitly acknowledge any cooperation.
Using the standard Tree and Graph libraries is not allowed. Write
your own classes corresponding to the objects.
Java code concepts
Source code written to .java
Compiled using javac to .class
A .class file does not contain code that is native to a given
processor; it instead contains bytecodes-- the machine
language of the Java Virtual Machine. The Java launcher tool
(java) then runs the application with an instance of the Java
Virtual Machine.
Platform: hardware or software environment in which a program
runs.
Java platform: software only
2 components
The Java Virtual Machine
The Java Application Programming Interface (API)
Java platform
One should have
Java Runtime Engine (JRE) to run java
applications
Java Source Development Kit (SDK/JDK) to
compile .java into .class
Optionally, the development environment.
Popular example
package javalecture;
public class FirstClass {
public static void main(String[] args) {
System.out.println("I think therefore I
think I am!");
}
}
Try to explain the underlined terms before looking at the next
slide.
Package: a unique namespace for the types it contains; classes in the
same package can access each other's protected members.
Public: class is visible to all classes everywhere.
No modifier: visible only within its own package.
Member (function) level:
Public, no modifier: same meaning
Private: can only be accessed in its own class
Protected: can only be accessed within its own package and, in
addition, by a subclass of its class in another package.
Instance methods are associated with an object and use the instance
variables of that object. This is the default.
Static methods take all they data from parameters and compute
something from those parameters, with no reference to variables.
This is typical of methods which do some kind of generic calculation.
Abstract classes and interfaces
An abstract class is a class that is declared abstract and may include abstract
methods (methods not implemented). Abstract classes cannot be instantiated,
but they can be subclassed. In Java, EVERY class is a subclass of
java.lang.Object (or subclass of its subclasses).
abstract class Account {
int amount;
void withdraw(double number) { ... }
abstract void changeBalance(); }
An interface: an abstract class declared as interface
all variables are static and final
only method signatures included, no method implementations.
Interface PrintableObject{
static final Integer MaximumSizeInBytes=256;
void print(); }
Extends vs implements
final class InterestBearingAccount extends Account:
Class InterestBearingAccount (subclass) inherits all members
(variables and functions) of class Account (superclass).
class Image implements PrintableObject:
Class Image provides implementation to methods of the class
PrintableObject (e.g. method print() that would specify how exactly
to print images).
Interfaces are used to encode similarities which classes of various
types share, but do not necessarily constitute a class relationship
(e.g. Image and Text classes).
A class which implements an interface must either implement all
methods in the interface, or be an abstract class.
Popular example using Swing
package javalecture;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class HelloWorld {
public static void main(String[] args) {
JFrame Frame = new JFrame ("Hello, World!");
Frame.setDefaultCloseOperation
(JFrame.DISPOSE_ON_CLOSE);
Frame.getContentPane().add (new JLabel("Hello,
World!"));
Frame.pack();
Frame.setVisible(true);
}
}
import java.awt.*;
Draw with Swing
import javax.swing.*;
public class Drawing {
public static void main(String[] args) {
new Drawing();
}
Drawing() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(new MyComponent());
frame.repaint();
frame.setSize(300, 300);
frame.setVisible(true);
}
}
Draw with Swing
class MyComponent extends JComponent {
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw an oval that fills the window
int x = 0;
int y = 0;
int width = getSize().width-1;
int height = getSize().height-1;
g.drawOval(x, y, width, height);
}
}
Create conten pane
public JPanel createContentPane (){
//Create and set up the content pane.
ContentPanel = new JPanel();
ContentPanel.setLayout(null);
SubmitButton = new JButton("Square!");
SubmitButton.setLocation(5, 220);
SubmitButton.setSize(100, 30);
SubmitButton.addActionListener(this);
ContentPanel.add(SubmitButton);
Create conten pane
ClearButton = new JButton("Clear...");
ClearButton.setLocation(5, 280);
ClearButton.setSize(100, 30);
ClearButton.addActionListener(this);
ContentPanel.add(ClearButton);
// Insert Textfields
XField = new JTextField(3);
XField.setLocation(5, 30);
XField.setSize(100, 30);
ContentPanel.add(XField);
ContentPanel.setOpaque(true);
return ContentPanel;
}
Process button click
public void actionPerformed(ActionEvent e) {
if(e.getSource()==SubmitButton){
//get the data from the text fields
Integer x;
x=
Integer.parseInt(XField.getText().trim());
Integer z;
z=x*x;
XField.setText(z.toString());
}
else if(e.getSource()==ClearButton){
//clean the fields
XField.setText("");}
}
Create and show GUI
private static void createAndShowGUI() {
//This is to turn on the Default 'Look and Feel'.
JFrame.setDefaultLookAndFeelDecorated(true);
Frame = new JFrame ("Multiplicator!");
ButtonEx demo = new ButtonEx();
Frame.setContentPane(demo.createContentPane());
Frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Frame.setSize(800,600);
Frame.setVisible(true);
}
Combine all
import java.util.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ButtonEx implements ActionListener{
static JTextField XField;
JButton SubmitButton, ClearButton ;
JPanel ContentPanel;
static JFrame Frame;
public static void main(String[] args) {
createAndShowGUI();
}}
public int readFromFile(){
try{
Read from file
fin = new FileInputStream ("input.txt");
BufferedReader reading = new BufferedReader(new
InputStreamReader(fin));
String thisLine;
//while not the end of file
while ((thisLine = reading.readLine()) != null) {
counter++; }
//close the input file
fin.close(); }
catch (IOException e)
{ System.err.println ("Unable to read from file");
return -1; }
finally{
System.out.println("file reading completed");
return counter; } }
Stream tokenizer
One option to read file with entries delimited by
a custom symbol (set of symbols) is to read line
by line and use an object of class
StringTokenizer to extract each entry.
For details, check:
http://java.sun.com/j2se/1.4.2/docs/api/java/util/StringTokenizer.html
Write to file
public void writeToFile(int n){
try {
BufferedWriter writting=new
BufferedWriter(new FileWriter("output.txt"));
writting.write("Total number of strings in
input file: " + n );
writting.close();
}
catch (IOException e)
{
System.err.println ("Unable to write to
file");
}
finally{
System.out.println("This is a last action");
}
}
Exercises
For using in the projects: draw an oval on a
button click
For your own interest: make your java
application look like „usual‟ OS application.
Set your own icon for the application. Make
application window appear in the center of
the screen.
These are optional, no grades involved.
Get documents about "