Java Introduction

advertisement
Intro to Java
Java Applications
Swing Class
Graphics
Java Outline
• Today
– Intro and Applications
– GUI
• Client / Server
• RMI, JDBC
2
JAVA Implementation
Java program
Java program
Java program
Java program
Java Cmds
Java Cmds
Java Cmds
VM
SPARC
VM
VM
PowerPC
Intel
3
Operations Environments
• Applications program (~DOS window)
– supports file access
• Applet (browser) – no longer generally supported
– supports Internet linkages.
4
Building Java Applications
Using Java Development Kit
• Get a copy of the JDK (www.oracle.com, etc.)
• Install the development kit (tools and classes)
• Create MyApp.java source file
– text editor (notepad, etc.)
– winedit, Café, etc.
• Compile .java file to create .class file
– javac MyApp.java
• Run application (.class file) through java VM
– java MyApp
5
Building Java Applications
Using Java IDEs
• NetBeans
– Available from netbeans.org
• Eclipse
– Available from www.eclipse.org
• jCreator le
– available from jcreator.com
– jcreator pro – academic license $35
• jDeveloper
– available from www.oracle.com/technetwork/developertools/jdev
• many others
Sample Java App
G:\Data\Java\MyHelloApp>type MyHelloApp.java
class MyHelloApp
{
public static void main (String argv[])
{
String message[] = new String[2];
message[0] = "Welcome to CS423";
message[1] = "The subject is JAVA!";
System.out.println (message[0]);
System.out.println (message[1]);
}
}
7
MyHelloApp Implementation
MyHelloApp.java
Java compiler
MyHelloApp.class
MyHelloApp.class
Java byte code
VM
machine code
8
Sample Java App
G:\Data\Java\MyHelloApp>javac MyHelloApp.java
G:\Data\Java\MyHelloApp>java MyHelloApp
Welcome to CS423
The subject is JAVA!
G:\Data\Java\MyHelloApp>
9
MyHelloApp.class
Get Input from User
import java.io.*;
class InputApp
{
InputApp ()
{
DataInputStream dis = new DataInputStream (System.in);
String sIn = " ";
String sOut = " ";
File fIn;
File fOut;
FileInputStream fis;
FileOutputStream fos;
int iNumBytesRead;
byte[] ab;
11
Get Input from User
System.out.println
("*-------------------------------------------*");
System.out.print ("Enter Source File Name Here: ");
System.out.flush ();
try {sIn = dis.readLine ();}
catch (Exception e)
{System.out.println ("Exception on input file name"
+ e);}
System.out.print("Enter Destination File Name Here: ");
System.out.flush ();
try {sOut = dis.readLine ();}
catch (Exception e)
{System.out.println ("Exception on output file name"
+ e);}
12
Get Input from User
try
{
fIn = new File (sIn);
fis = new FileInputStream (fIn);
fOut = new File (sOut);
fos = new FileOutputStream (fOut);
ab = new byte[2048];
while ((iNumBytesRead = fis.read (ab)) != -1)
{
fos.write (ab, 0, iNumBytesRead);
}
fis.close ();
fos.close ();
}
catch (Exception e)
{System.out.println ("Exception during copy: " + e); }
13
Get Input from User
System.out.println ("Data copied from " + sIn + " to "
+ sOut);
System.out.println
("*-------------------------------------------*");
}
public static void main (String args[])
{
new InputApp ();
}
}
14
Get Input from User
G:\Data\Java\InputApp>java InputApp
*-------------------------------------------*
Enter Source File Name Here: books_db.txt
Enter Destination File Name Here: My_list.txt
Data copied from books_db.txt to My_list.txt
*-------------------------------------------*
G:\Data\Java\InputApp>
15
Swing Components
• Defined in package javax.swing
– Pure Java components
• AWT components tied to local platform GUI
– UNIX java windows look like X windows
– Windows java windows look like Windows
windows (??)
– etc.
• Swing defines a common look and feel for
Java.
Product.java
// From Java: How to Program - Deitel and Deitel
// Calculate the product of three integers
import javax.swing.JOptionPane;
public class Product {
public static void main( String args[] )
{
int x, y, z, result;
String xVal, yVal, zVal;
xVal = JOptionPane.showInputDialog(
"Enter first integer:" );
yVal = JOptionPane.showInputDialog(
"Enter second integer:" );
zVal = JOptionPane.showInputDialog(
"Enter third integer:" );
Product.java
x = Integer.parseInt( xVal );
y = Integer.parseInt( yVal );
z = Integer.parseInt( zVal );
result = x * y * z;
JOptionPane.showMessageDialog( null,
"The product is " + result );
System.exit( 0 );
}
}
Product Output(s)
JOptionPane
• Similar to windows message boxes
• Types of Option Panes:
showConfirmDialog(null,message,title,optionType,msgType);
Asks a confirming question, like yes/no/cancel.
showInputDialog(message);
Prompt for some input.
showMessageDialog(null, message);
Tell the user about something that has happened.
showOptionDialog(....);
The Grand Unification of the above three.
20
Additional Swing Options
JOptionPane.showMessageDialog(null, "This is an alert",
"Alert", JOptionPane.ERROR_MESSAGE);
JOptionPane.showConfirmDialog(null,
"Is that your final answer?", "Choice Dialog",
JOptionPane.YES_NO_OPTION);
Additional Swing Options
Object[] options = { "Lady", "Tiger" };
choice = JOptionPane.showOptionDialog(null,
"What will it be -\nThe Lady or the Tiger?", "Decision",
JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
if (choice == 0)
JOptionPane.showMessageDialog( null, "You chose the Lady",
"Result", JOptionPane.PLAIN_MESSAGE );
else
JOptionPane.showMessageDialog( null, "You chose the Tiger",
"Result", JOptionPane.PLAIN_MESSAGE );
Additional Swing Options
Object[] possibleValues = { "First", "Second", "Third" };
Object selectedValue = JOptionPane.showInputDialog(null,
"Choose one", "Input", JOptionPane.INFORMATION_MESSAGE,
null, possibleValues, possibleValues[0]);
Graphics in Applications
• Must include a main() method
• Must extend the AWT Frame class, or swing
JFrame class
24
HelloWorldWindow
import java.awt.*;
import java.awt.event.*;
public class HelloWorldWindow implements WindowListener
{
public HelloWorldWindow()
{
myFrame f=new myFrame();
f.addWindowListener (this);
}
public void windowClosing(WindowEvent e) {
System.out.println ("Closing Window");
System.exit(0);
}
25
HelloWorldWindow
class myFrame extends Frame{
myFrame()
{
this.setSize(300, 200);
this.show();
}
public void paint(Graphics g)
{
String str = "A Windows version of Hello, World";
g.drawString(str, 25, 75);
}
public static void main(String[] args)
{ Frame f = new HelloWorldWindow();
f.resize(300, 200);
f.show();
}
}
}
HelloWorldWindow Output
public void paint (Graphics g)
• Provides an initial presentation of Graphics
• Works on Graphics object
– (like device context).
– Place to store settings for screen output (text,
images. etc.)
• Must be regenerated following changes.
28
Event Driven Programming
• Operating System recognizes an event
• Sends a signal to appropriate object
• Object receives event notification and calls
appropriate function
public void windowClosing(WindowEvent e) {
System.out.println ("Closing Window");
System.exit(0);
}
29
Object Layout
•
•
•
•
•
•
BorderLayout (default for Frames)
FlowLayout (default for Panels)
GridLayout
GridbagLayout
CardLayout
Fixed:
– object.reshape (x, y, width, height);
30
nuTextTest Example
Linux
Windows
NuTextTest2.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NuTextTest2 extends JFrame {
public NuTextTest2()
{
setTitle("NuTextTest2");
Container p = getContentPane();;
p.setLayout(new FlowLayout());
TickButton = new Button("Tick");
p.add(TickButton);
TickButton.addActionListener(
new ActionListener() {
public void actionPerformed (ActionEvent e)
{
int minutes = Integer.parseInt(minuteField.getText());
minutes += 1;
String min = String.valueOf(minutes);
minuteField.setText(min);
}
} //end of ActionListener
); //end of TickButton
NuTextTest2.java
SetTime = new Button("Set Time");
p.add(SetTime);
SetTime.addActionListener(
new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
String tim = hourField.getText()+ ":" +
minuteField.getText();
timeField.setText(tim);
}
}
);
NuTextTest2.java
hourField = new TextField("12", 3);
p.add(hourField);
minuteField = new TextField("00", 3);
p.add(minuteField);
timeField = new TextField("", 12);
p.add(timeField);
setSize (400,100);
show ();
}//end of NuTextTest2 (constructor)
private
private
private
private
private
TextField hourField;
TextField minuteField;
TextField timeField;
Button TickButton;
Button SetTime;
NuTextTest2.java
public static void main(String[] args)
{
NuTextTest2 app = new NuTextTest2();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}//end of main()
}//end of program
Summary
• Java is:
– Platform independent
– Object-oriented
– Dynamic
– Flexible – used in many different domains
– Command line or graphical
Download