011 more swings_adv
Upcoming SlideShare
Loading in...5
×
 

011 more swings_adv

on

  • 312 views

......

......

Statistics

Views

Total Views
312
Views on SlideShare
312
Embed Views
0

Actions

Likes
0
Downloads
17
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

011 more swings_adv 011 more swings_adv Presentation Transcript

  • Java GUI: Swing Part II CIS 2615Copyright © 2002-2008 Shah Mumin All Rights Reserved
  • Swing MenusMenu 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-dependantlocation.A popup menu shows up underneath the cursor when the user right-clicks themouse, 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(); } }
  • 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( //add popup menu ScrollPaneConstants. this.addMouseListener(new MouseAdapter() {HORIZONTAL_SCROLLBAR_AS_NEEDED); public void mousePressed(MouseEvent e) { scrollpane1.setVerticalScrollBarPolicy( if(e.isPopupTrigger()) showPopup(e.getPoint());ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEE }DED); public void mouseReleased(MouseEvent e) { panel1.add(scrollpane1); if(e.isPopupTrigger()) showPopup(e.getPoint()); Container pane = this.getContentPane(); } pane.setLayout(new BorderLayout()); public void mouseClicked(MouseEvent e) { pane.add(panel1, BorderLayout.CENTER); if(e.isPopupTrigger()) pane.add(new showPopup(e.getPoint()); JButton("Tester"), BorderLayout.SOUTH); } //add regular menu }); setupMenu(); }
  • 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("Financialitem.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")
  • 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
  • Swing Menuspublic 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); }}
  • Swing DialogsSo far, you have seen some sample dialogs like asking user to input data. Let’sexplain it little further.Every dialog is dependent on a frame. When the frame is destroyed, the dialogis destroyed too.A dialog can be modal. When a modal dialog is visible, it blocks user input toall 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.
  • Internal Frames
  • Swing Timer
  • JTree & JEditorPaneThe JTree component is very complex like the JTable. Most of the classes arelocated in a separated package called javax.swing.tree. A Tree is very usefulwhen you want to show hierarchical data.This example also shows how to use JEditorPane. The JEditorPane is a texteditor where you can show text as well as HTML pages.It also knows how to render fairly complex HTML pages. However, it is notdesigned for very complex web pages or pages with server side tags.If you display documents like image or word document, you will see binarycode. However, if you define an image inside an HTML page, it knows how torender it.
  • 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(); } }
  • 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);
  • 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); }
  • 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);
  • 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
  • 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("Couldnt 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()); }
  • JTree & JEditorPaneRun JTreeTester.cmd
  • JTabbedPane
  • JFileChooser
  • JColorChooser
  • BoxLayout
  • JSlider
  • JToolBar
  • StringTokenizerSometimes, data is provided in a flat file (or downloaded to a flat file from arelational 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 verycommon. You can read these files and break columns in each row (line), usingthe 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 likethe Enumeration class.In this example, we will read a flat file like the following. We will ignorecomment lines (lines starting with #) and any line that is empty. There is nospecific formatting for this file. It is a simple text file unlike the Properties filewe used earlier:
  • StringTokenizer # File Name: emp_data.txt # Author: Shah Mumin # 9:24 PM 10/24/02 123456789|Shah|Mumin|1500 Main|Apt A|Gladstone|MO|45678 343456789|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(); } }
  • 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); }
  • 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(); }
  • System ClipboardYou all are familiar with copying text and images between applications byusing application menu (editcopy and editpaste) or keyboard shortcuts(CTRL + C and CTRL + V).When you copy something, it goes to the system clipboard. It remains thereuntil 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 bittoo 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.
  • System Clipboardpackage 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);
  • 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); } }
  • System Clipboard private void pasteTextFromSystemClipboard() { Run SystemClipboardTester.cmd String text; //To get contents, we need to get a Transferable by a call to //the clipboards 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 = newSystemClipboardTester();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}
  • Swing DnDAWT provides a drag-and-drop as well as clipboard functionality. Startingwith JDK1.4, swing has added support for data transfer between apps. Youcan 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 withstandardize 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 changesWithout 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 fromthe Java Tutorial).
  • 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_CLOprivate void jbInit() throws Exception { SE); this.setSize(new Dimension(350, 80)); frame.setVisible(true); this.setTitle("Drag and Drop"); } }
  • Swing DnDRun SwingDnDTester.cmd
  • Object SerializationYou can also serialize any valid Java object (Image is not serializable) and writeto a disk for later use.This is very useful since you can save user preferences in the local computerand load it when the user signs in.The most powerful thing is that you can save a whole GUI object, and later loadit 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 simpleexample to explain how to get started.Please remember that you cannot access local resources (disk, printer, etc) froman applet for security reasons unless the applet is digitally singed.
  • 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());
  • 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);
  • 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"));
  • 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"); } }
  • Object Serialization catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (Exception ex) { Run ObjectSerializationTester.cmd ex.printStackTrace(); } } public static void main(String[] args) { ObjectSerializationTester frame = new ObjectSerializationTester(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}
  • Java PrintJava 2D API, and integral part of JFC, was introduced with JDK 1.2. It provides2D graphics, text and imaging capabilities though extension of the originalAWT 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 ellipsesand 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 arerendered Enhanced color support that facilitates color management Support for printing complex documentsWe will only discuss a simple printing mechanism; rest is out of the scope ofthis class.
  • 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(); } }
  • 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); }
  • Java Printpublic void actionPerformed(ActionEvent evt) { if(evt.getSource() == printButton) { Run JavaPrintTester.cmd 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); }}
  • Recommendations: Advanced BooksAWT 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/banglarwebdomainSwingSet 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/banglarwebdomainJDBC 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).
  • Recommendations: Advanced TopicsRecommended 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, JTreeAdvanced 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