2. Swing Menus
Menu is unique in a way that they are not placed in other components. Instead,
they appear either in a menubar or in popup menu.
A menubar can contain one or more menu and uses a platform-dependant
location.
A popup menu shows up underneath the cursor when the user right-clicks the
mouse, for example (in Windows).
package com.javaclass.advevent;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class SwingMenuTester extends JFrame implements ActionListener {
private JTextArea jtxta1 = new JTextArea(10, 30);
public SwingMenuTester() {
try {
jbInit();
}
catch (Exception e) {
e.printStackTrace();
}
}
4. Swing Menus
private void setupMenu() { //a group of radio button menu items
JMenu jMenu; ButtonGroup group = new ButtonGroup();
JMenuItem item; rbMenuItem = new JRadioButtonMenuItem("Male");
JRadioButtonMenuItem rbMenuItem; rbMenuItem.setSelected(true);
JCheckBoxMenuItem cbMenuItem; rbMenuItem.setMnemonic(KeyEvent.VK_M);
JMenuBar menuBar = new JMenuBar(); group.add(rbMenuItem);
this.setJMenuBar(menuBar); jMenu.add(rbMenuItem);
//File Menu rbMenuItem = new
jMenu = new JMenu("File"); JRadioButtonMenuItem("Female");
jMenu.setMnemonic('F');//can use setMnumonic(char) rbMenuItem.setMnemonic(KeyEvent.VK_L);
group.add(rbMenuItem);
item = new JMenuItem("New", new jMenu.add(rbMenuItem);
ImageIcon("new.gif"));
//can use setMnumonic(KeyEvent number) jMenu.addSeparator();
//Mnemonics offeres keyboard to navigate through menu //a group of check box menu items
item.setMnemonic(KeyEvent.VK_N); cbMenuItem = new
//Accelarator allows bypassing menu and use JCheckBoxMenuItem("Veteran");
Alt+letter/number cbMenuItem.setMnemonic(KeyEvent.VK_V);
item.setAccelerator(KeyStroke.getKeyStroke( jMenu.add(cbMenuItem);
KeyEvent.VK_1, ActionEvent.ALT_MASK));
cbMenuItem = new JCheckBoxMenuItem("Financial
item.getAccessibleContext().setAccessibleDescription("New Aid");
Document"); cbMenuItem.setMnemonic(KeyEvent.VK_D);
item.addActionListener(this); jMenu.add(cbMenuItem);
jMenu.add(item); jMenu.addSeparator();
item = new JMenuItem("Exit", KeyEvent.VK_X);
item = new JMenuItem("Open", new item.addActionListener(this);
ImageIcon("open.gif")); jMenu.add(item);
item.setMnemonic(KeyEvent.VK_O); menuBar.add(jMenu);
item.addActionListener(this);
jMenu.add(item); //Edit menu
jMenu.addSeparator(); jMenu = new JMenu("Edit")
5. Swing Menus protected void showPopup(Point point){
JMenuItem mi;
item = new JMenuItem("Copy");
JPopupMenu myJPopupMenu = new JPopupMenu();
item.addActionListener(this);
jMenu.add(item);
mi = myJPopupMenu.add(new JMenuItem("File", 'F'));
mi.addActionListener(this);
item = new JMenuItem("Cut");
item.addActionListener(this);
mi = myJPopupMenu.add(
jMenu.add(item);
new JMenuItem("New", KeyEvent.VK_N));
mi.addActionListener(new ActionListener() {
item = new JMenuItem("Paste");
public void actionPerformed(ActionEvent evt) {
item.addActionListener(this);
jtxta1.setText("*New** popup menu has been pressed");
jMenu.add(item);
}
});
menuBar.add(jMenu);
mi = myJPopupMenu.add(new JMenuItem("Open", 'O'));
//move the last menu all the way to the right
mi.addActionListener(this);
//Because JMemuBar uses BoxLayout
//you can use a glue component to move item
mi = myJPopupMenu.add(new JMenuItem("Exit", 'x'));
left-right, top-bottom
mi.addActionListener(this);
menuBar.add(Box.createHorizontalGlue());
myJPopupMenu.addSeparator();
jMenu = new JMenu("Help");
String colors[] ={"Black", "White", "Green", "Orange", "Pink",
item = new JMenuItem("About");
"Red", "Blue", "Cyan", "Gray"};
item.addActionListener(this);
JMenu submenu = new JMenu("Text Colors");
jMenu.add(item);
for (int i = 0; i < colors.length; i++) {
mi = new JMenuItem(colors[i]);
menuBar.add(jMenu);
submenu.add(mi);
mi.addActionListener(this);
}//end of setupMenu()
}
myJPopupMenu.add(submenu);
myJPopupMenu.show(this, point.x, point.y);
} //end of showPopup
6. Swing Menus
public void actionPerformed(ActionEvent evt) { public static void main(String[] args) {
String arg = evt.getActionCommand(); SwingMenuTester frame = new
if(arg.equals("File")) { SwingMenuTester();
jtxta1.setText("**File** menu has been pressed"); frame.setDefaultCloseOperation(
} JFrame.EXIT_ON_CLOSE);
else if(arg.equals("Open")) { frame.setVisible(true);
jtxta1.setText("**Open** menu has been pressed"); }
} }
else if(arg.equals("New")) {
jtxta1.setText("**New** menu has been pressed");
}
else if(arg.equals("Copy")) {
Run SwingMenuTester.cmd
jtxta1.setText("**Copy** menu has been pressed");
}
else if(arg.equals("Cut")) {
jtxta1.setText("**Cut** menu has been pressed");
}
else if(arg.equals("Paste")) {
jtxta1.setText("**Paste** menu has been pressed");
}
else if(arg.equals("Black")) {
jtxta1.setText("**Black** menu has been pressed");
}
else if(arg.equals("Exit")) {
System.exit(0);
}
}
7. Swing Dialogs
So far, you have seen some sample dialogs like asking user to input data. Let’s
explain it little further.
Every dialog is dependent on a frame. When the frame is destroyed, the dialog
is destroyed too.
A dialog can be modal. When a modal dialog is visible, it blocks user input to
all other windows in the program. Dialog provided by JOptionPane is modal.
If you want to create non-modal dialog, you have to use JDialog directly.
10. JTree & JEditorPane
The JTree component is very complex like the JTable. Most of the classes are
located in a separated package called javax.swing.tree. A Tree is very useful
when you want to show hierarchical data.
This example also shows how to use JEditorPane. The JEditorPane is a text
editor where you can show text as well as HTML pages.
It also knows how to render fairly complex HTML pages. However, it is not
designed for very complex web pages or pages with server side tags.
If you display documents like image or word document, you will see binary
code. However, if you define an image inside an HTML page, it knows how to
render it.
12. JTree & JEditorPane
private void jbInit() throws Exception {
Container pane = this.getContentPane();
pane.setBackground(Color.cyan);
this.setSize(new Dimension(550, 580));
this.setTitle("Simple Tree");
JPanel mainSwingpanel = new JPanel();
mainSwingpanel.setPreferredSize(new Dimension(540, 520));
mainSwingpanel.setBackground(Color.white);
//Like JTable, a JTree object does not contain data; it simply provides a view of the data.
//Create the instance of DefaultMutableTreeNode to serve as the root node for the tree.
DefaultMutableTreeNode top = new DefaultMutableTreeNode("javaclass Programs");
//create the rest of the tree through the method createNodes
//which receives DefaultMutableTreeNode in the constructor
createNodes(top);
//Create a tree that allows one selection at a time. Creation of tree is done by
//specifying the root node as an argument to the JTree constructor.
tree = new JTree(top);
tree.getSelectionModel().setSelectionMode
(TreeSelectionModel.SINGLE_TREE_SELECTION);
//Responding to tree node selections is simple.
//You implement a tree selection listener and register it on the tree
tree.addTreeSelectionListener(this);
//By default, the Java Look & Feel draws no lines between nodes.
//By setting the JTree.lineStyle client property of a tree, you
//can specify a different convention.
//JTree.lineStyle: Possible values are "Angled", "Horizontal", and "None" (the default).
if (playWithLineStyle)
tree.putClientProperty("JTree.lineStyle", lineStyle);
13. JTree & JEditorPane
//puts the tree in a scroll pane, a common tactic because showing the full,
//expanded tree would otherwise require too much space.
JScrollPane treeView = new JScrollPane(tree);
treeView.setPreferredSize(new Dimension(100, 50));
htmlPane = new JEditorPane();
htmlPane.setEditable(false);
initHelp();//setup initial help text for the htmlPane
JScrollPane htmlView = new JScrollPane(htmlPane);
htmlView.setMinimumSize(new Dimension(100, 50));
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPane.setTopComponent(treeView);
splitPane.setBottomComponent(htmlView);
splitPane.setDividerLocation(250);
splitPane.setPreferredSize(new Dimension(500, 500));
mainSwingpanel.add(splitPane, BorderLayout.CENTER);
pane.add(mainSwingpanel, BorderLayout.CENTER);
pane.add(new JLabel(" "), BorderLayout.NORTH);
pane.add(new JLabel(" "), BorderLayout.SOUTH);
pane.add(new JLabel(" "), BorderLayout.EAST);
pane.add(new JLabel(" "), BorderLayout.WEST);
}
14. JTree & JEditorPane
private void createNodes(DefaultMutableTreeNode top) {
//level 1
DefaultMutableTreeNode category = null;
//level 2(Leaf)
DefaultMutableTreeNode book = null;
//First node
category = new DefaultMutableTreeNode("Sports and Misc");
//add to parent provided
top.add(category);
//defineing a Leaf
book = new DefaultMutableTreeNode(
new BookInfo("HTML: FIFA All Time Players", "fifa_all_time_dreamteam_players.html"));
//adding leaf to immediate parent node
category.add(book);
book = new DefaultMutableTreeNode(
new BookInfo("JPG: All time players", "fifa_all_time_dreamteam_players.jpg"));
category.add(book);
book = new DefaultMutableTreeNode(new BookInfo("HTML loads PDF","pdf.html"));
category.add(book);
book = new DefaultMutableTreeNode(new BookInfo("Java Source File", "ShapesPrint.java"));
category.add(book);
book = new DefaultMutableTreeNode(new BookInfo("Word File", "sylhetidictionary.doc"));
category.add(book);
//Second node
category = new DefaultMutableTreeNode("Resumes");
//add the parent node
top.add(category);
15. JTree & JEditorPane
book = new DefaultMutableTreeNode(
new BookInfo("E-Commerce Resume","ecommerce_resume.html"));
category.add(book);
book = new DefaultMutableTreeNode(
new BookInfo("IT Professional Resume", "it_professional_resume.html"));
category.add(book);
book = new DefaultMutableTreeNode(new BookInfo("Student Resume","student_resume.html"));
category.add(book);
}
private class BookInfo {
private String bookName;
private URL bookURL;
public BookInfo(String book, String filename) {
bookName = book;
try {
bookURL = new URL(prefix + filename);
}
catch (java.net.MalformedURLException exc) {
System.err.println("Attempted to create a BookInfo "
+ "with a bad URL: " + bookURL);
bookURL = null;
}
}
//Since we implemented a custom object, we
//should implement its toString method so that it returns the string to
//be displayed for that node.
//returns only the name instead of the whole class info
public String toString() {
return bookName;
}
} //end of inner class BookInfo
16. JTree & JEditorPane
private void initHelp() { private void displayURL(URL url) {
String filename = null; try {
try { htmlPane.setPage(url);
filename = "help.html"; }
helpURL = new URL(prefix + filename); catch (IOException e) {
displayURL(helpURL); System.err.println("Attempted to read a bad URL: "
} + url);
catch (Exception e) { }
System.err.println("Couldn't create help URL: " + }
filename);
} public static void main(String[] args) {
} if(args.length < 1) {
System.out.println("You must provide the location of
public void valueChanged(TreeSelectionEvent e) { your help files, exiting");
DefaultMutableTreeNode node = System.exit(1);
}
(DefaultMutableTreeNode)tree.getLastSelectedPathCompon JTreeTester frame = new JTreeTester(args[0]);
ent();
if (node == null) { frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE
return; );
} frame.setVisible(true);
Object nodeInfo = node.getUserObject(); }
if (node.isLeaf()) { }
BookInfo book = (BookInfo)nodeInfo;
displayURL(book.bookURL);
System.out.print(book.bookURL + "n");
}
else {
displayURL(helpURL);
}
System.out.println(nodeInfo.toString());
}
24. StringTokenizer
Sometimes, data is provided in a flat file (or downloaded to a flat file from a
relational database) with column delimiters such as comma, pipe (|), space, tab,
etc. Each line is one row of data.
Next row starts with a line break character such as n or r. These files are very
common. You can read these files and break columns in each row (line), using
the java.util.StringTokenizer class.
The StringTokenizer class expects a String and delimiter to separate in item
(called token). It is a child class of java.util.Enumeration and you can use it like
the Enumeration class.
In this example, we will read a flat file like the following. We will ignore
comment lines (lines starting with #) and any line that is empty. There is no
specific formatting for this file. It is a simple text file unlike the Properties file
we used earlier:
27. StringTokenizer catch (Exception ex) {
ex.printStackTrace();
public void actionPerformed(ActionEvent evt) { System.exit(1);
if(evt.getSource() == loadButton) { }
System.out.println("loadButton button has been clicked"); //set text of the text area
processData(); jtxta1.setText(dataString);
} }
}
public static void main(String[] args) {
private void processData() { StringTokenizerFileIO frame = new
String dataString = ""; StringTokenizerFileIO();
try {
RandomAccessFile source = null; frame.setDefaultCloseOperation(JFrame.EXIT_ON_CL
String str = ""; OSE);
source = new RandomAccessFile(fileName, "r"); frame.setVisible(true);
while (source.getFilePointer() < source.length()) { }
str = source.readLine(); }
if( (str.startsWith("#")) || (str.trim().length() < 1) ) {
System.out.println(
"Ignoring comment or empty line: " + str); Run StringTokenizerFileIO.cmd
}
else {
//StringTokenizer is a child class of Enumeration
//so a call to the constuctor returns an Enumeration
StringTokenizer tokenizer =
new StringTokenizer(str, "|");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
dataString+= token + " ";
}
dataString+= "n";
}
}
source.close();
}
28. System Clipboard
You all are familiar with copying text and images between applications by
using application menu (editcopy and editpaste) or keyboard shortcuts
(CTRL + C and CTRL + V).
When you copy something, it goes to the system clipboard. It remains there
until you copy something else.
Java provides the capability of copying and pasting for both text and images
(objects). Copying text is straightforward, however, copying image is little bit
too involved for this class. We will discuss a simple text transfer.
You must import java.awt.datatransfer package to use Clipboard,
StringSelection, Transferable and UnsupportedFlavorException.
29. System Clipboard
package com.javaclass.advevent; JPanel panel1 = new JPanel();
panel1.setBackground(Color.cyan);
import java.awt.*; panel1.setPreferredSize(dimen);
import java.awt.event.*; panel1.setLayout(new FlowLayout());
import javax.swing.*;
import java.awt.datatransfer.*; jtxta1.setText("So the songbirds left n" +
" no void n" +
public class SystemClipboardTester extends JFrame " no empty hours n" +
implements ActionListener { " when they fled n" +
" because the hour itself n" +
private JButton copyButton = new JButton("Copy"); " had died before them. n" +
private JButton pasteButton = new JButton("Paste"); " Morning no longer existed.nn" +
private JTextArea jtxta1 = new JTextArea(10, 30); " --Chinua Achebe: The Anthills of Savannah ");
private JTextArea jtxta2 = new JTextArea(10, 30); JScrollPane scrollpane1 = new JScrollPane(jtxta1);
private Clipboard sysClipBoard = scrollpane1.setPreferredSize(new Dimension(130, 180));
Toolkit.getDefaultToolkit().getSystemClipboard();
scrollpane1.setHorizontalScrollBarPolicy(
public SystemClipboardTester() {
try { ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEED
jbInit(); ED);
} scrollpane1.setVerticalScrollBarPolicy(
catch (Exception e) {
e.printStackTrace(); ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
} );
} panel1.add(scrollpane1);
private void jbInit() throws Exception { JPanel panel2 = new JPanel();
this.getContentPane().setBackground(Color.cyan); panel2.setBackground(Color.cyan);
this.setSize(new Dimension(350, 350)); panel2.setPreferredSize(dimen);
this.setTitle("System Clipboard"); panel2.setLayout(new FlowLayout());
Dimension dimen = new Dimension(150, 200);
30. System Clipboard
JScrollPane scrollpane2 = new JScrollPane(jtxta2);
scrollpane2.setPreferredSize(new Dimension(130, public void actionPerformed(ActionEvent evt) {
180)); if(evt.getSource() == copyButton) {
scrollpane2.setHorizontalScrollBarPolicy( System.out.println("copy button has been clicked");
copyTextToSystemClipboard();
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_N }
EEDED); else if (evt.getSource() == pasteButton) {
scrollpane2.setVerticalScrollBarPolicy( System.out.println("paste button has been clicked");
pasteTextFromSystemClipboard();
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEE }
DED); }
panel2.add(scrollpane2);
private void copyTextToSystemClipboard() {
JPanel panel3 = new JPanel();
panel3.setBackground(Color.cyan); String text = jtxta1.getSelectedText();
panel3.setPreferredSize(new Dimension(330, 40)); if(text == null) text = "";
panel3.setLayout(new FlowLayout()); System.out.println("Selected text is " + text);
if(text.equals("")){
Dimension dimen2 =new Dimension(130, 30); text = jtxta1.getText();
copyButton.setPreferredSize(dimen2); System.out.println("Since no text was selected we
copyButton.addActionListener(this); selected all " + text);
jtxta1.select(0, jtxta1.getText().length());
pasteButton.setPreferredSize(dimen2); }
pasteButton.addActionListener(this); //For strings to be transferred to the clipboard, they need
panel3.add(copyButton); to be wrapped into
panel3.add(pasteButton); // StringSelection objects. Actual transfer is done
through setContents
Container pane = this.getContentPane(); StringSelection selection = new StringSelection(text);
pane.setLayout(new FlowLayout()); // text clipboard owner
pane.add(panel1); sysClipBoard.setContents(selection, null);
pane.add(panel2);
pane.add(panel3); }
}
31. System Clipboard
private void pasteTextFromSystemClipboard() {
Run SystemClipboardTester.cmd
String text;
//To get contents, we need to get a Transferable by a call to
//the clipboard's getContents() method.
Transferable selection = sysClipBoard.getContents(this);
try {
text = (String)
(selection.getTransferData(DataFlavor.stringFlavor));
jtxta2.setText(text);
}
catch(UnsupportedFlavorException e) {
e.printStackTrace();
}
catch(Exception f){
f.printStackTrace();
}
jtxta1.setCaretPosition(0);
jtxta2.setCaretPosition(0);
}
public static void main(String[] args) {
SystemClipboardTester frame = new
SystemClipboardTester();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
32. Swing DnD
AWT provides a drag-and-drop as well as clipboard functionality. Starting
with JDK1.4, swing has added support for data transfer between apps. You
can do a drag-and-drop (DnD) or use clipboard transfer via copy/cut/paste.
The original AWT DnD was extremely complex, Swing made it easy with
standardize API to enable DnD. The following functionality has been added:
API to enable data transfer
API to enable DnD (can be turned off to use AWT DnD)
Updated swing Look and Feel to support the changes
Without going to a great deal of discussions, here is the simple example.
Please note, JLabel does not support DnD by default.
This example shows how to implement DnD in JLabel (partially adapted from
the Java Tutorial).
33. Swing DnD JPanel panel1 = new JPanel();
panel1.setBackground(Color.cyan);
package com.javaclass.advevent;
panel1.setPreferredSize(new Dimension(150,
import java.awt.*; 200));
import java.awt.event.*; panel1.setLayout(new GridLayout(2, 2));
import javax.swing.*;
jtxtf.setDragEnabled(true);
public class SwingDnDTester extends JFrame { jlbl.setTransferHandler(
new TransferHandler("text"));
private JTextField jtxtf = new JTextField(40); MouseListener ml = new MouseAdapter() {
private JLabel jlbl = new JLabel("Drop Here", public void mousePressed(MouseEvent e) {
SwingConstants.LEFT); JComponent c = (JComponent)e.getSource();
TransferHandler th = c.getTransferHandler();
static { th.exportAsDrag(c, e, TransferHandler.COPY);
try { }
UIManager.setLookAndFeel( };
jlbl.addMouseListener(ml);
UIManager.getCrossPlatformLookAndFeelClassName());
} panel1.add(jtxtf);
catch(Exception e) {} panel1.add(jlbl);
} jlbl.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)
);
public SwingDnDTester() {
try { this.getContentPane().add(panel1,
jbInit(); BorderLayout.CENTER);
} }
catch (Exception e) {
e.printStackTrace(); public static void main(String[] args) {
} SwingDnDTester frame = new SwingDnDTester();
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLO
private void jbInit() throws Exception { SE);
this.setSize(new Dimension(350, 80)); frame.setVisible(true);
this.setTitle("Drag and Drop"); }
}
35. Object Serialization
You can also serialize any valid Java object (Image is not serializable) and write
to a disk for later use.
This is very useful since you can save user preferences in the local computer
and load it when the user signs in.
The most powerful thing is that you can save a whole GUI object, and later load
it from the disk. Any object member that is transient is not serialized.
Object serialization is an advanced topic. Our goal here is to give a very simple
example to explain how to get started.
Please remember that you cannot access local resources (disk, printer, etc) from
an applet for security reasons unless the applet is digitally singed.
36. Object Serialization
package com.javaclass.advevent;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class ObjectSerializationTester extends JFrame
implements ActionListener {
private JButton serializeButton = new JButton("Serialize");
private JButton retrieveButton = new JButton("Retrieve");
private JTextArea jtxta1 = new JTextArea(10, 30);
private JPanel panel2 = new JPanel();
private JScrollPane scrollpane2 = new JScrollPane();
public ObjectSerializationTester() {
try {
jbInit();
}
catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.getContentPane().setBackground(Color.cyan);
this.setSize(new Dimension(350, 350));
this.setTitle("Object Serialization Test");
Dimension dimen = new Dimension(150, 200);
JPanel panel1 = new JPanel();
panel1.setBackground(Color.cyan);
panel1.setPreferredSize(dimen);
panel1.setLayout(new FlowLayout());
37. Object Serialization
jtxta1.setText("Please type some text to serialize the whole JTextArea");
JScrollPane scrollpane1 = new JScrollPane(jtxta1);
scrollpane1.setPreferredSize(new Dimension(130, 180));
scrollpane1.setHorizontalScrollBarPolicy(
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollpane1.setVerticalScrollBarPolicy(
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
panel1.add(scrollpane1);
JPanel panel2 = new JPanel();
panel2.setBackground(Color.cyan);
panel2.setPreferredSize(dimen);
panel2.setLayout(new FlowLayout());
scrollpane2.setPreferredSize(new Dimension(130, 180));
scrollpane2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollpane2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
panel2.add(scrollpane2);
JPanel panel3 = new JPanel();
panel3.setBackground(Color.cyan);
panel3.setPreferredSize(new Dimension(330, 40));
panel3.setLayout(new FlowLayout());
Dimension dimen2 =new Dimension(130, 30);
serializeButton.setPreferredSize(dimen2);
serializeButton.addActionListener(this);
retrieveButton.setPreferredSize(dimen2);
retrieveButton.addActionListener(this);
panel3.add(copyButton);
panel3.add(pasteButton);
38. Object Serialization
Container pane = this.getContentPane();
pane.setLayout(new FlowLayout());
pane.add(panel1);
pane.add(panel2);
pane.add(panel3);
}
public void actionPerformed(ActionEvent evt) {
if(evt.getSource() == serializeButton) {
serializeNow();
}
else if (evt.getSource() == retrieveButton) {
retrieveNow();
}
}
private void serializeNow() {
try {
//create a <B>FileOutputStream</B> object bound to a disk file named <B>jtextarea</B>
//if the file of that neame does not exist, the FileOutputStream class crates a file for you
FileOutputStream fileOut = new FileOutputStream("serializedJTextArea");
//<B>ObjectOutputStream</B> object bound to the FileOutputStream object.
//FileOutputStream has no method to write objects, but ObjectOutputStream can write objects.
//We passed a reference of FileOutputStream in the ObjectOutputStream constructor
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
//you can combine above two lines in one
//ObjectOutputStream objectOut = new ObjectOutputStream(
new FileOutputStream("serializedJTextArea"));
39. Object Serialization
//Writes the JTextArea to the ObjectOutputStream. You can write multiple object at one time.
objectOut.writeObject(jtxta1);
//you should always close any IO stream.
objectOut.close();
System.out.println("Your JTextArea has been serialized and stored in the disk");
}
catch (IOException ioe) {
ioe.printStackTrace();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
private void retrieveNow() {
try {
//creates a <B>FileInputStream</B> object bound to the disk file named <B>jtextarea</B>
FileInputStream fileIn = new FileInputStream("serializedJTextArea");
//creates an <B>ObjectInputStream</B> bound to the FileInputStream
ObjectInputStream objectIn = new ObjectInputStream(fileIn);
//read the object ans store it in an Object varialbel called <B>c</B>
Object c = objectIn.readObject();
//close the inputstream
objectIn.close();
//now, check that the object is a type of component before adding it to the panel
if(c instanceof Component) {
// cast the Object as a <B>Component</B> before adding, you can cast as a JTextArea too.
scrollpane2.getViewport().add((Component)c, null);
panel2.repaint();
System.out.println("Your JTextArea has been retrived and shown");
}
}
41. Java Print
Java 2D API, and integral part of JFC, was introduced with JDK 1.2. It provides
2D graphics, text and imaging capabilities though extension of the original
AWT components. Here are the components (see the Java Tutorial for details):
A uniform rendering model for display devices and printers
A wide range of geometric primitives, such as curves, rectangles, and ellipses
and a mechanism for rendering virtually any geometric shape
Mechanisms for performing hit detection on shapes, text, and images
A compositing model that provides control over how overlapping objects are
rendered
Enhanced color support that facilitates color management
Support for printing complex documents
We will only discuss a simple printing mechanism; rest is out of the scope of
this class.
42. Java Print
To support printing, the application must:
Job Control – managing the print job
Imaging – rendering the page to be printed
package com.javaclass.advevent;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.print.*;
public class JavaPrintTester extends JFrame
implements Printable, ActionListener {
private JButton printButton = new JButton("Print");
private JTextArea jtxta1 = new JTextArea(10, 30);
private Font fnt = new Font("Helvetica-Bold", Font.PLAIN, 12);
public JavaPrintTester() {
try {
jbInit();
}
catch (Exception e) {
e.printStackTrace();
}
}