SlideShare uma empresa Scribd logo
1 de 46
Java GUI: Swing


          Part II

       CIS 2615

Copyright © 2002-2008 Shah Mumin
       All Rights Reserved
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();
           }
         }
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("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")
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 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);
  }
}
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.
Internal Frames
Swing Timer
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.
JTree & JEditorPane
package 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("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());
  }
JTree & JEditorPane
Run JTreeTester.cmd
JTabbedPane
JFileChooser
JColorChooser
BoxLayout
JSlider
JToolBar
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:
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 Clipboard

You all are familiar with copying text and images between applications by
using 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 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.
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);
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 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);
   }
}
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).
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");                     }
                                                     }
Swing DnD

Run SwingDnDTester.cmd
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.
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 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.
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();
         }
       }
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 Print
public 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 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).
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, 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), Iterator
Reflections

Mais conteúdo relacionado

Destaque

Chapter 11.4
Chapter 11.4Chapter 11.4
Chapter 11.4sotlsoc
 
java swing programming
java swing programming java swing programming
java swing programming Ankit Desai
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART IIOXUS 20
 
Java Swing
Java SwingJava Swing
Java SwingShraddha
 

Destaque (6)

Chapter 11.4
Chapter 11.4Chapter 11.4
Chapter 11.4
 
JDBC
JDBCJDBC
JDBC
 
java swing programming
java swing programming java swing programming
java swing programming
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART II
 
Java Swing
Java SwingJava Swing
Java Swing
 
java2 swing
java2 swingjava2 swing
java2 swing
 

Semelhante a 011 more swings_adv

PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdfPLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdfmohammedfootwear
 
import javax.swing.; import java.awt.; import java.awt.event..pdf
import javax.swing.; import java.awt.; import java.awt.event..pdfimport javax.swing.; import java.awt.; import java.awt.event..pdf
import javax.swing.; import java.awt.; import java.awt.event..pdfarwholesalelors
 
Nouveau document texte-_-_
Nouveau document texte-_-_Nouveau document texte-_-_
Nouveau document texte-_-_Mohamed Mlika
 
Program klik sederhana
Program klik sederhanaProgram klik sederhana
Program klik sederhanaHenfry Kai
 
I hope the below code is helpful to you, please give me rewards.im.pdf
I hope the below code is helpful to you, please give me rewards.im.pdfI hope the below code is helpful to you, please give me rewards.im.pdf
I hope the below code is helpful to you, please give me rewards.im.pdfapexelectronices01
 
Hafitz_Rizki 201343500823 JMenuBar_JavaMsAccess_JavaGrade
Hafitz_Rizki 201343500823 JMenuBar_JavaMsAccess_JavaGradeHafitz_Rizki 201343500823 JMenuBar_JavaMsAccess_JavaGrade
Hafitz_Rizki 201343500823 JMenuBar_JavaMsAccess_JavaGradeMuhamad Hafitz Rizki
 
Ejemplos Interfaces Usuario 3
Ejemplos Interfaces Usuario 3Ejemplos Interfaces Usuario 3
Ejemplos Interfaces Usuario 3martha leon
 
Tic Tac Toe game with GUI please dont copy and paste from google. .pdf
Tic Tac Toe game with GUI please dont copy and paste from google. .pdfTic Tac Toe game with GUI please dont copy and paste from google. .pdf
Tic Tac Toe game with GUI please dont copy and paste from google. .pdfformaxekochi
 
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdfTic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdfinfomalad
 
Initial UI Mockup - Part 2.pdf
Initial UI Mockup - Part 2.pdfInitial UI Mockup - Part 2.pdf
Initial UI Mockup - Part 2.pdfShaiAlmog1
 
10 awt event model
10 awt event model10 awt event model
10 awt event modelBayarkhuu
 
Programming a guide gui
Programming a guide guiProgramming a guide gui
Programming a guide guiMahmoud Hikmet
 
Getting started with GUI programming in Java_2
Getting started with GUI programming in Java_2Getting started with GUI programming in Java_2
Getting started with GUI programming in Java_2Muhammad Shebl Farag
 
Android Event and IntentAndroid Event and Intent
Android Event and IntentAndroid Event and IntentAndroid Event and IntentAndroid Event and Intent
Android Event and IntentAndroid Event and Intentadmin220812
 
Chat application in java using swing and socket programming.
Chat application in java using swing and socket programming.Chat application in java using swing and socket programming.
Chat application in java using swing and socket programming.Kuldeep Jain
 
csc 208
csc 208csc 208
csc 208priska
 
How do I make my JTable non editableimport java.awt.; import j.pdf
How do I make my JTable non editableimport java.awt.; import j.pdfHow do I make my JTable non editableimport java.awt.; import j.pdf
How do I make my JTable non editableimport java.awt.; import j.pdfforwardcom41
 

Semelhante a 011 more swings_adv (20)

PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdfPLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
 
Oop lecture9 10
Oop lecture9 10Oop lecture9 10
Oop lecture9 10
 
import javax.swing.; import java.awt.; import java.awt.event..pdf
import javax.swing.; import java.awt.; import java.awt.event..pdfimport javax.swing.; import java.awt.; import java.awt.event..pdf
import javax.swing.; import java.awt.; import java.awt.event..pdf
 
Nouveau document texte-_-_
Nouveau document texte-_-_Nouveau document texte-_-_
Nouveau document texte-_-_
 
Program klik sederhana
Program klik sederhanaProgram klik sederhana
Program klik sederhana
 
I hope the below code is helpful to you, please give me rewards.im.pdf
I hope the below code is helpful to you, please give me rewards.im.pdfI hope the below code is helpful to you, please give me rewards.im.pdf
I hope the below code is helpful to you, please give me rewards.im.pdf
 
Hafitz_Rizki 201343500823 JMenuBar_JavaMsAccess_JavaGrade
Hafitz_Rizki 201343500823 JMenuBar_JavaMsAccess_JavaGradeHafitz_Rizki 201343500823 JMenuBar_JavaMsAccess_JavaGrade
Hafitz_Rizki 201343500823 JMenuBar_JavaMsAccess_JavaGrade
 
Ejemplos Interfaces Usuario 3
Ejemplos Interfaces Usuario 3Ejemplos Interfaces Usuario 3
Ejemplos Interfaces Usuario 3
 
JButton in Java Swing example
JButton in Java Swing example JButton in Java Swing example
JButton in Java Swing example
 
Tic Tac Toe game with GUI please dont copy and paste from google. .pdf
Tic Tac Toe game with GUI please dont copy and paste from google. .pdfTic Tac Toe game with GUI please dont copy and paste from google. .pdf
Tic Tac Toe game with GUI please dont copy and paste from google. .pdf
 
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdfTic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
 
Initial UI Mockup - Part 2.pdf
Initial UI Mockup - Part 2.pdfInitial UI Mockup - Part 2.pdf
Initial UI Mockup - Part 2.pdf
 
10 awt event model
10 awt event model10 awt event model
10 awt event model
 
Programming a guide gui
Programming a guide guiProgramming a guide gui
Programming a guide gui
 
Getting started with GUI programming in Java_2
Getting started with GUI programming in Java_2Getting started with GUI programming in Java_2
Getting started with GUI programming in Java_2
 
culadora cientifica en java
culadora cientifica en javaculadora cientifica en java
culadora cientifica en java
 
Android Event and IntentAndroid Event and Intent
Android Event and IntentAndroid Event and IntentAndroid Event and IntentAndroid Event and Intent
Android Event and IntentAndroid Event and Intent
 
Chat application in java using swing and socket programming.
Chat application in java using swing and socket programming.Chat application in java using swing and socket programming.
Chat application in java using swing and socket programming.
 
csc 208
csc 208csc 208
csc 208
 
How do I make my JTable non editableimport java.awt.; import j.pdf
How do I make my JTable non editableimport java.awt.; import j.pdfHow do I make my JTable non editableimport java.awt.; import j.pdf
How do I make my JTable non editableimport java.awt.; import j.pdf
 

Último

Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 

Último (20)

Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 

011 more swings_adv

  • 1. Java GUI: Swing Part II CIS 2615 Copyright © 2002-2008 Shah Mumin All Rights Reserved
  • 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(); } }
  • 3. 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(); }
  • 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.
  • 11. JTree & JEditorPane package 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(); } }
  • 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()); }
  • 17. JTree & JEditorPane Run JTreeTester.cmd
  • 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:
  • 25. 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(); } }
  • 26. 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); }
  • 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 (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 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"); } }
  • 40. 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); } }
  • 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(); } }
  • 43. 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); }
  • 44. Java Print public 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); } }
  • 45. 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).
  • 46. 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, 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), Iterator Reflections