011 more swings_adv

46
Java GUI: Swing Copyright © 2002-2008 Shah Mumin Copyright © 2002-2008 Shah Mumin All Rights Reserved All Rights Reserved Part II CIS 2615

description

......

Transcript of 011 more swings_adv

Page 1: 011 more swings_adv

Java GUI: Swing

Copyright © 2002-2008 Shah MuminCopyright © 2002-2008 Shah Mumin

All Rights ReservedAll Rights Reserved

Part II

CIS 2615

Page 2: 011 more swings_adv

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(); } }

Page 3: 011 more swings_adv

Swing Menus private void jbInit() throws Exception { this.getContentPane().setBackground(Color.cyan); this.setSize(new Dimension(350, 350)); this.setTitle("Swing Menu");

JPanel panel1 = new JPanel(); panel1.setBackground(Color.cyan); panel1.setPreferredSize(new Dimension(300, 200)); panel1.setLayout(new FlowLayout());

JScrollPane scrollpane1 = new JScrollPane(jtxta1); scrollpane1.setPreferredSize( new Dimension(280, 180)); scrollpane1.setHorizontalScrollBarPolicy( ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); scrollpane1.setVerticalScrollBarPolicy( ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); panel1.add(scrollpane1);

Container pane = this.getContentPane(); pane.setLayout(new BorderLayout()); pane.add(panel1, BorderLayout.CENTER); pane.add(new JButton("Tester"), BorderLayout.SOUTH); //add regular menu setupMenu();

//add popup menu this.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if(e.isPopupTrigger()) showPopup(e.getPoint()); } public void mouseReleased(MouseEvent e) { if(e.isPopupTrigger()) showPopup(e.getPoint()); } public void mouseClicked(MouseEvent e) { if(e.isPopupTrigger()) showPopup(e.getPoint()); } }); }

Page 4: 011 more swings_adv

Swing Menus private void setupMenu() { JMenu jMenu; JMenuItem item; JRadioButtonMenuItem rbMenuItem; JCheckBoxMenuItem cbMenuItem; JMenuBar menuBar = new JMenuBar(); this.setJMenuBar(menuBar);

//File Menu jMenu = new JMenu("File"); jMenu.setMnemonic('F');//can use setMnumonic(char)

item = new JMenuItem("New", new ImageIcon("new.gif")); //can use setMnumonic(KeyEvent number) //Mnemonics offeres keyboard to navigate through menu item.setMnemonic(KeyEvent.VK_N); //Accelarator allows bypassing menu and use Alt+letter/number item.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_1, ActionEvent.ALT_MASK)); item.getAccessibleContext().setAccessibleDescription("New Document"); item.addActionListener(this); jMenu.add(item);

item = new JMenuItem("Open", new ImageIcon("open.gif")); item.setMnemonic(KeyEvent.VK_O); item.addActionListener(this); jMenu.add(item); jMenu.addSeparator();

//a group of radio button menu items ButtonGroup group = new ButtonGroup(); rbMenuItem = new JRadioButtonMenuItem("Male"); rbMenuItem.setSelected(true); rbMenuItem.setMnemonic(KeyEvent.VK_M); group.add(rbMenuItem); jMenu.add(rbMenuItem);

rbMenuItem = new JRadioButtonMenuItem("Female"); rbMenuItem.setMnemonic(KeyEvent.VK_L); group.add(rbMenuItem); jMenu.add(rbMenuItem);

jMenu.addSeparator(); //a group of check box menu items cbMenuItem = new JCheckBoxMenuItem("Veteran"); cbMenuItem.setMnemonic(KeyEvent.VK_V); jMenu.add(cbMenuItem);

cbMenuItem = new JCheckBoxMenuItem("Financial Aid"); cbMenuItem.setMnemonic(KeyEvent.VK_D); jMenu.add(cbMenuItem); jMenu.addSeparator(); item = new JMenuItem("Exit", KeyEvent.VK_X); item.addActionListener(this); jMenu.add(item); menuBar.add(jMenu);

//Edit menu jMenu = new JMenu("Edit")

Page 5: 011 more swings_adv

Swing Menus

item = new JMenuItem("Copy"); item.addActionListener(this); jMenu.add(item);

item = new JMenuItem("Cut"); item.addActionListener(this); jMenu.add(item);

item = new JMenuItem("Paste"); item.addActionListener(this); jMenu.add(item);

menuBar.add(jMenu);

//move the last menu all the way to the right //Because JMemuBar uses BoxLayout //you can use a glue component to move item left-right, top-bottom menuBar.add(Box.createHorizontalGlue());

jMenu = new JMenu("Help");

item = new JMenuItem("About"); item.addActionListener(this); jMenu.add(item);

menuBar.add(jMenu);

}//end of setupMenu()

protected void showPopup(Point point){

JMenuItem mi; JPopupMenu myJPopupMenu = new JPopupMenu();

mi = myJPopupMenu.add(new JMenuItem("File", 'F')); mi.addActionListener(this);

mi = myJPopupMenu.add( new JMenuItem("New", KeyEvent.VK_N)); mi.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { jtxta1.setText("*New** popup menu has been pressed"); } });

mi = myJPopupMenu.add(new JMenuItem("Open", 'O')); mi.addActionListener(this);

mi = myJPopupMenu.add(new JMenuItem("Exit", 'x')); mi.addActionListener(this);

myJPopupMenu.addSeparator();

String colors[] ={"Black", "White", "Green", "Orange", "Pink", "Red", "Blue", "Cyan", "Gray"}; JMenu submenu = new JMenu("Text Colors"); for (int i = 0; i < colors.length; i++) { mi = new JMenuItem(colors[i]); submenu.add(mi); mi.addActionListener(this); } myJPopupMenu.add(submenu); myJPopupMenu.show(this, point.x, point.y); } //end of showPopup

Page 6: 011 more swings_adv

Swing Menus

public void actionPerformed(ActionEvent evt) { String arg = evt.getActionCommand(); if(arg.equals("File")) { jtxta1.setText("**File** menu has been pressed"); } else if(arg.equals("Open")) { jtxta1.setText("**Open** menu has been pressed"); } else if(arg.equals("New")) { jtxta1.setText("**New** menu has been pressed"); } else if(arg.equals("Copy")) { 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); } }

public static void main(String[] args) { SwingMenuTester frame = new SwingMenuTester(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}

Run SwingMenuTester.cmd

Page 7: 011 more swings_adv

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.

Page 8: 011 more swings_adv

Internal Frames

Page 9: 011 more swings_adv

Swing Timer

Page 10: 011 more swings_adv

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.

Page 11: 011 more swings_adv

JTree & JEditorPanepackage com.javaclass.advevent;

import java.awt.*;import java.awt.event.*;import java.util.*;import java.net.URL;import java.io.*;

import javax.swing.*;import javax.swing.event.*;import javax.swing.tree.*;

public class JTreeTester extends JFrame implements TreeSelectionListener {

private JEditorPane htmlPane; private URL helpURL; private boolean playWithLineStyle = true; private String lineStyle = "Angled"; private JTree tree; private String prefix = "";

public JTreeTester(String location) { this.prefix = "file:" + location + System.getProperty("file.separator"); try { jbInit(); } catch (Exception e) { e.printStackTrace(); } }

Page 12: 011 more swings_adv

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);

Page 13: 011 more swings_adv

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);

}

Page 14: 011 more swings_adv

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);

Page 15: 011 more swings_adv

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

Page 16: 011 more swings_adv

JTree & JEditorPane private void initHelp() { String filename = null; try { filename = "help.html"; helpURL = new URL(prefix + filename); displayURL(helpURL); } catch (Exception e) { System.err.println("Couldn't create help URL: " + filename); } }

public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent(); if (node == null) { return; } 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()); }

private void displayURL(URL url) { try { htmlPane.setPage(url); } catch (IOException e) { System.err.println("Attempted to read a bad URL: " + url); } }

public static void main(String[] args) { if(args.length < 1) { System.out.println("You must provide the location of your help files, exiting"); System.exit(1); } JTreeTester frame = new JTreeTester(args[0]); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}

Page 17: 011 more swings_adv

JTree & JEditorPane

Run JTreeTester.cmd

Page 18: 011 more swings_adv

JTabbedPane

Page 19: 011 more swings_adv

JFileChooser

Page 20: 011 more swings_adv

JColorChooser

Page 21: 011 more swings_adv

BoxLayout

Page 22: 011 more swings_adv

JSlider

Page 23: 011 more swings_adv

JToolBar

Page 24: 011 more swings_adv

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:

Page 25: 011 more swings_adv

StringTokenizer# File Name: emp_data.txt# Author: Shah Mumin# 9:24 PM 10/24/02123456789|Shah|Mumin|1500 Main|Apt A|Gladstone|MO|45678343456789|Kazi|Anirban|1500 Main|Apt A|Gladstone|MO|45678

763456789|Devzani|Sikdar|5600 South St| |Gladstone|MO|45678

package com.javaclass.advevent;

import java.io.*;import java.util.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class StringTokenizerFileIO extends JFrame implements ActionListener {

private String fileName = "emp_data.txt"; private JButton loadButton = new JButton("Load"); private JTextArea jtxta1 = new JTextArea(10, 30);

public StringTokenizerFileIO() { try { jbInit(); } catch (Exception e) { e.printStackTrace(); } }

Page 26: 011 more swings_adv

StringTokenizer private void jbInit() throws Exception { this.getContentPane().setBackground(Color.cyan); this.setSize(new Dimension(350, 350)); this.setTitle("StringTokenizer");

JPanel panel1 = new JPanel(); panel1.setBackground(Color.cyan); panel1.setPreferredSize(new Dimension(300, 200)); panel1.setLayout(new FlowLayout());

JScrollPane scrollpane1 = new JScrollPane(jtxta1); scrollpane1.setPreferredSize(new Dimension(280, 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(new Dimension(330, 40)); panel2.setLayout(new FlowLayout());

loadButton.setPreferredSize(new Dimension(130, 30)); loadButton.addActionListener(this); panel2.add(loadButton);

Container pane = this.getContentPane(); pane.setLayout(new BorderLayout()); pane.add(panel1, BorderLayout.CENTER); pane.add(panel2, BorderLayout.SOUTH); }

Page 27: 011 more swings_adv

StringTokenizer public void actionPerformed(ActionEvent evt) { if(evt.getSource() == loadButton) { System.out.println("loadButton button has been clicked"); processData(); } }

private void processData() { String dataString = ""; try { RandomAccessFile source = null; String str = ""; source = new RandomAccessFile(fileName, "r"); while (source.getFilePointer() < source.length()) { str = source.readLine(); if( (str.startsWith("#")) || (str.trim().length() < 1) ) { System.out.println( "Ignoring comment or empty line: " + str); } 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(); }

catch (Exception ex) { ex.printStackTrace(); System.exit(1); } //set text of the text area jtxta1.setText(dataString); }

public static void main(String[] args) { StringTokenizerFileIO frame = new StringTokenizerFileIO(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}

Run StringTokenizerFileIO.cmd

Page 28: 011 more swings_adv

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.

Page 29: 011 more swings_adv

System Clipboardpackage com.javaclass.advevent;

import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.awt.datatransfer.*;

public class SystemClipboardTester extends JFrame implements ActionListener {

private JButton copyButton = new JButton("Copy"); private JButton pasteButton = new JButton("Paste"); private JTextArea jtxta1 = new JTextArea(10, 30); private JTextArea jtxta2 = new JTextArea(10, 30); private Clipboard sysClipBoard = Toolkit.getDefaultToolkit().getSystemClipboard();

public SystemClipboardTester() { 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("System Clipboard");

Dimension dimen = new Dimension(150, 200);

JPanel panel1 = new JPanel(); panel1.setBackground(Color.cyan); panel1.setPreferredSize(dimen); panel1.setLayout(new FlowLayout());

jtxta1.setText("So the songbirds left \n" + " no void \n" + " no empty hours \n" + " when they fled \n" + " because the hour itself \n" + " had died before them. \n" + " Morning no longer existed.\n\n" + " --Chinua Achebe: The Anthills of Savannah "); 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());

Page 30: 011 more swings_adv

System Clipboard JScrollPane scrollpane2 = new JScrollPane(jtxta2); 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); copyButton.setPreferredSize(dimen2); copyButton.addActionListener(this);

pasteButton.setPreferredSize(dimen2); pasteButton.addActionListener(this); panel3.add(copyButton); panel3.add(pasteButton);

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() == copyButton) { System.out.println("copy button has been clicked"); copyTextToSystemClipboard(); } else if (evt.getSource() == pasteButton) { System.out.println("paste button has been clicked"); pasteTextFromSystemClipboard(); } }

private void copyTextToSystemClipboard() {

String text = jtxta1.getSelectedText(); if(text == null) text = ""; System.out.println("Selected text is " + text); if(text.equals("")){ text = jtxta1.getText(); System.out.println("Since no text was selected we selected all " + text); jtxta1.select(0, jtxta1.getText().length()); } //For strings to be transferred to the clipboard, they need to be wrapped into // StringSelection objects. Actual transfer is done through setContents StringSelection selection = new StringSelection(text); // text clipboard owner sysClipBoard.setContents(selection, null);

}

Page 31: 011 more swings_adv

System Clipboard

private void pasteTextFromSystemClipboard() {

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); }}

Run SystemClipboardTester.cmd

Page 32: 011 more swings_adv

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).

Page 33: 011 more swings_adv

Swing DnDpackage com.javaclass.advevent;

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class SwingDnDTester extends JFrame {

private JTextField jtxtf = new JTextField(40); private JLabel jlbl = new JLabel("Drop Here", SwingConstants.LEFT);

static { try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch(Exception e) {} }

public SwingDnDTester() { try { jbInit(); } catch (Exception e) { e.printStackTrace(); } }

private void jbInit() throws Exception { this.setSize(new Dimension(350, 80)); this.setTitle("Drag and Drop");

JPanel panel1 = new JPanel(); panel1.setBackground(Color.cyan); panel1.setPreferredSize(new Dimension(150, 200)); panel1.setLayout(new GridLayout(2, 2));

jtxtf.setDragEnabled(true); jlbl.setTransferHandler( new TransferHandler("text")); MouseListener ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { JComponent c = (JComponent)e.getSource(); TransferHandler th = c.getTransferHandler(); th.exportAsDrag(c, e, TransferHandler.COPY); } }; jlbl.addMouseListener(ml);

panel1.add(jtxtf); panel1.add(jlbl); jlbl.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

this.getContentPane().add(panel1, BorderLayout.CENTER); }

public static void main(String[] args) { SwingDnDTester frame = new SwingDnDTester(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}

Page 34: 011 more swings_adv

Swing DnD

Run SwingDnDTester.cmd

Page 35: 011 more swings_adv

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.

Page 36: 011 more swings_adv

Object Serializationpackage 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());

Page 37: 011 more swings_adv

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);

Page 38: 011 more swings_adv

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"));

Page 39: 011 more swings_adv

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"); } }

Page 40: 011 more swings_adv

Object Serialization

catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } }

public static void main(String[] args) { ObjectSerializationTester frame = new ObjectSerializationTester(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}

Run ObjectSerializationTester.cmd

Page 41: 011 more swings_adv

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.

Page 42: 011 more swings_adv

Java PrintTo 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(); } }

Page 43: 011 more swings_adv

Java Print private void jbInit() throws Exception { this.getContentPane().setBackground(Color.cyan); this.setSize(new Dimension(350, 350)); this.setTitle("StringTokenizer");

JPanel panel1 = new JPanel(); panel1.setBackground(Color.cyan); panel1.setPreferredSize(new Dimension(300, 200)); panel1.setLayout(new FlowLayout());

jtxta1.setFont(fnt); JScrollPane scrollpane1 = new JScrollPane(jtxta1); scrollpane1.setPreferredSize(new Dimension(280, 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(new Dimension(330, 40)); panel2.setLayout(new FlowLayout());

printButton.setPreferredSize(new Dimension(130, 30)); printButton.addActionListener(this); panel2.add(printButton);

Container pane = this.getContentPane(); pane.setLayout(new BorderLayout()); pane.add(panel1, BorderLayout.CENTER); pane.add(panel2, BorderLayout.SOUTH); }

Page 44: 011 more swings_adv

Java Printpublic void actionPerformed(ActionEvent evt) { if(evt.getSource() == printButton) { PrinterJob printJob = PrinterJob.getPrinterJob(); printJob.setPrintable(this); if (printJob.printDialog()) { try { printJob.print(); } catch (Exception ex) { ex.printStackTrace(); }//end try-catch }//end if }//end if }//end method

//method implementation for Printable interface public int print(Graphics g, PageFormat pf, int pi) throws PrinterException { if (pi >= 1) { return Printable.NO_SUCH_PAGE;

} g.setFont(fnt); g.setColor(Color.black); g.drawString(jtxta1.getText(), 100, 200); return Printable.PAGE_EXISTS; }

public static void main(String[] args) { JavaPrintTester frame = new JavaPrintTester(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}

Run JavaPrintTester.cmd

Page 45: 011 more swings_adv

Recommendations: Advanced Books

AWT Readings:AWT: Graphic Java 2, Volume 1: AWT (3rd Edition) by David M. Geary. Prentice Hall PTR; ISBN: 0130796662; 1st edition (September 21, 1998).http://www.amazon.com/exec/obidos/ASIN/0130796662/banglarwebdomain

SwingSet Readings:SwingSet: Graphic Java 2, Volume 2: Swing (3rd Edition) by David M. Geary. Prentice Hall PTR; ISBN: 0130796670; 3rd edition (March 12, 1999)http://www.amazon.com/exec/obidos/ASIN/0130796670/banglarwebdomain

JDBC Redings:JDBC API Tutorial and Reference: Universal Data Access for the Java 2 Platform (2nd Edition). By Seth White, Maydene Fisher, Rick Cattell, Graham Hamilton, Mark Hapner. Publisher: Addison-Wesley Pub Co; ISBN: 0201433281; 2nd edition (June 11, 1999).

Page 46: 011 more swings_adv

Recommendations: Advanced Topics

Recommended Book:Core Java 2, Volume II: Advanced Features (5th Edition) by Cay Horstmann, Gary Cornell. Prentice Hall; ISBN: 0130927384; 5th edition (December 10, 2001).http://www.amazon.com/exec/obidos/ASIN/0130927384/banglarwebdomain

Object Serialization RMI Multithreading Networking: Sockets, ServerSocket, FTP, HTTP JDBC Advanced Swingset: JTable, JList, JTreeAdvanced AWT: DnD (Drag and Drop), System Clipboard, Printing, Image Manipulation JavaBeans Security Internationalization JNI (Java Native Interface) Collections: Set/SortedSet(HashSet, TreeSet), List(ArrayList, LinkedList), Map/ SortedMap (HashMap, TreeMap), IteratorReflections