Creating the User Interface


The CommPrinting.java file is the main file of the Printing application. This file displays a user interface with a menu bar and an edit pane. The menu bar contains three menus: File, Font, and Color. The menu options of these menus enable end users to open a document, select the color and the font of the text in the document, select the printer port, specify page setup, and print the text in the document.

Listing 4-1 shows the CommPrinting.java file:

Listing 4-1: The CommPrinting.java File

start example
 /* Imports required Comm classes */ import javax.comm.*; /* Imports required I/O classes */ import java.io.*; /* Imports required AWT classes */ import java.awt.*; import java.awt.event.*; import javax.swing.*; /* Imports required Filedialogbox classes */ import javax.swing.filechooser.*; /* Imports required Print classes */ import javax.print.*; import javax.print.attribute.*; import javax.print.event.*; import java.awt.print.*; import java.lang.reflect.*; import java.awt.Graphics2D; import javax.print.attribute.standard.*; /* class CommPrinting - This class is the main class of the application. This class initializes the interface and loads all components like the menubar,editpane before displaying the result.    Constructor: CommPrinting-This constructor creates GUI.    Methods:          createGUI-This method creates GUI. addlEvent - This method add event to components actionPerformed - This method describes which action will be performed on which component. getExtension - This method gives file extension. printDoc - This method print document. main - This method creates the main window of the application and displays all the components. */ class CommPrinting extends JFrame  implements ActionListener  {    /*        Declare object of JMenuBar class.    */    JMenuBar menubar;    /*        Declare objects of JMenu class.    */     JMenu file_menu;    JMenu setting_menu;    /*        Declare objects of JMenuItem class.    */ JMenuItem print_menuitem, setup_menuitem,  exit_menuitem, open_menuitem,font_menuitem,color_menuitem;    /*        Declare object of JFileChooser class.    */    JFileChooser filechooser;    /*        Declare object of JScrollPane class.    */    JScrollPane scrollpane;    /*        Declare object of JTextPane class.    */    JTextPane textpane;    /*        Declare object of DataInputStream class.    */    protected DataInputStream is;    /*        Declare object of PrintStream class.    */    protected PrintStream os;    /*        Declare object of InputStream class.    */    protected InputStream istr;    /*        Declare object of CommPort class.    */    CommPort commport;    /*     Declare and Initialize object of FontChoose class.    */    public FontChoose font = new FontChoose();    /*     Declare and Initialize object of ColorChoose class.    */    public ColorChoose color=new  ColorChoose();    /*     Declare and Initialize object of PortChoice class.    */    PortChoice comport=new PortChoice(null,this);    private boolean PrintJobDone = false;    public static final int TIMEOUTSECONDS = 30;    public static final int BAUD = 9600;    /*     Main method that creates the instance of the CommPrinting class.    */    public static void main(String[] args) throws IOException, NoSuchPortException, _    PortInUseException, UnsupportedCommOperationException    {       CommPrinting commprint=new CommPrinting();    }    public CommPrinting()    {       super("Printing Application");       createGUI();       addlEvent();    }    /*       createGUI: It is called to create menubar and textpane.       Parameter: N/A       Return Value: N/A    */    public void createGUI()    {       /*        Initialize and set the Look and Feel of the application to Windows Look and Feel.       */       try       {          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());       }       catch(Exception e)       {          System.out.println("Error in setting WLAF"+e);       }       Container container=getContentPane();       /*       Set the layout of the frame as BorderLayout.       */       container.setLayout(new BorderLayout());       /*        Initialize the object of JMenuBar class.       */       menubar = new JMenuBar();       /*        Initialize the objects of JMenu class and set the Title.       */            file_menu = new JMenu("File");       setting_menu=new JMenu("Settings");       /*        Initialize the objects of JMenuItem class and set the Title.       */            open_menuitem = new JMenuItem("Open");             setup_menuitem = new JMenuItem("Page Setup & Print");             print_menuitem = new JMenuItem("Choose COM Port to Print");            exit_menuitem = new JMenuItem("Exit");            font_menuitem = new JMenuItem("Font");       color_menuitem=new JMenuItem("Color");       /*        Initialize the object of JTextPane class.       */       textpane=new JTextPane();       /*        Initialize the object of JScrollPane class and set this on textpane object.       */       scrollpane=new JScrollPane(textpane);       /*       Add scrollpane to content pane and place it in center of container.       */       container.add(scrollpane, BorderLayout.CENTER);       /*       Add menuitems to menu and set actioncommand to them.       */       file_menu.add(open_menuitem);       file_menu.add(setup_menuitem);       file_menu.add(print_menuitem);       file_menu.add(exit_menuitem);       setting_menu.add(font_menuitem);       setting_menu.add(color_menuitem);       open_menuitem.setActionCommand("Open");       setup_menuitem.setActionCommand("Page");       setup_menuitem.setEnabled(false);       print_menuitem.setActionCommand("Print");       exit_menuitem.setActionCommand("Exit");       font_menuitem.setActionCommand("font");       color_menuitem.setActionCommand("color");       /*          Add menu to menubar.       */       menubar.add(file_menu);       menubar.add(setting_menu);       setJMenuBar(menubar);       /*       Initialize object of JFileChooser class.       */       filechooser=new JFileChooser();       /*          Set filter with file dialog box.       */       filechooser.setFileFilter(new javax.swing.filechooser.FileFilter ()       {          public boolean accept(File f)           {              if (f.isDirectory())               {               return true;              }              String name = f.getName();              if (name.endsWith(".txt"))               {               return true;              }              return false;       }       public String getDescription()        {          return ".txt";             }         });       /*       Set the location at which window will be displayed.       */       Dimension  scrnSize = Toolkit.getDefaultToolkit().getScreenSize();       setLocation((scrnSize.width / 2) - 350, (scrnSize.height / 2) - 250);       /*          Set window's size.       */       setSize(500,500);       setVisible(true);    }    /*    addlEvent: It is called to add event listener with components.          Parameter: N/A          Return Value: N/A    */    public void addlEvent()    {       addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});       open_menuitem.addActionListener(this);       setup_menuitem.addActionListener(this);       print_menuitem.addActionListener(this);       exit_menuitem.addActionListener(this);       font_menuitem.addActionListener(this);       color_menuitem.addActionListener(this);    }    /*    actionPerformed: It is called when user clicks open, Print setup &     print, print,Exit,font or color menu item.    Parameter: ae - an ActionEvent object containing details of the event.    Return Value: N/A    */     public void actionPerformed(ActionEvent ae)     {       /*       This is executed when user clicks the open menuitem.       */       if ("Open".equals(ae.getActionCommand()))       {          int returnVal = filechooser.showOpenDialog(this);          if(returnVal == JFileChooser.APPROVE_OPTION)           {             String fileextension=getExtension(filechooser.getSelectedFile());             String fileabspath=filechooser.getSelectedFile().getAbsolutePath();             if (fileextension.equals("jpg")||fileextension.equals("JPG")||             fileextension.equals("gif")||fileextension.equals("GIF")||             fileextension.equals("png")||fileextension.equals("PNG"))             {                textpane.insertIcon(new ImageIcon(fileabspath));             }             else             {                try                {                   FileInputStream inputStream = new                   FileInputStream(filechooser.getSelectedFile().getAbsolutePath());                   BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));                   StringBuffer strOut=new StringBuffer();                   String strTemp="";                   while ((strTemp = br.readLine())!=null)                   {                      strOut.append(strTemp).append("\n");                   }                   textpane.setText(strOut.toString());                }                catch(IOException e)                {                   System.out.println("Error in file reading"+e);                }                }             }          }          /*          This is executed when user clicks the Print menuitem.          */          if ("Print".equals(ae.getActionCommand()))          {             /*              Declare object of PortChoice class.             */             comport.setVisible(true);             setup_menuitem.setEnabled(true);          }          /*          This is executed when user clicks the page setup and print menuitem.          */          if ("Page".equals(ae.getActionCommand()))          {             new PrintComponent_Class(textpane).pageSetupAndPrint();          }          /*          This is executed when user clicks the exit menuitem.          */          if ("Exit".equals(ae.getActionCommand()))          {             System.exit(0);          }          /*          This is executed when user clicks the font menuitem.          */          if ("font".equals(ae.getActionCommand()))          {             font.setVisible(true);             font.getOk().addActionListener(new ActionListener()             {                public void actionPerformed(ActionEvent ae)                {                   textpane.setFont(font.font());                   font.setVisible(false);                }             });                font.getCancel().addActionListener(new ActionListener()             {                public void actionPerformed(ActionEvent ae)                {                   font.setVisible(false);                }             });          }          /*          This is executed when user clicks the color menuitem.          */          if ("color".equals(ae.getActionCommand()))          {             color.pack();             color.setVisible(true);             color.getOk().addActionListener(new ActionListener()             {                public void actionPerformed(ActionEvent ae)                {                   textpane.setForeground(color.color());                   color.setVisible(false);                }             });                color.getCancel().addActionListener(new ActionListener()             {                public void actionPerformed(ActionEvent ae)                {                   color.setVisible(false);                }             });          }       }       /*       getExtension:This method will extract file extension from file.        Parameter:f - object of File class       Return Value: file extension       */       public String getExtension(File f)        {          if(f != null)           {             String filename = f.getName();             int i = filename.lastIndexOf('.');             if(i>0 && i<filename.length()-1)              {                return filename.substring(i+1).toLowerCase();             };          }          return null;       }       /*       printDoc:This method will extract file extension from file.        Parameter:commportname - name of selected com port.       commid - object of CommPortIdentifier.        Return Value: NA       */       public void printDoc(String commportname,CommPortIdentifier commid)       {          if (commportname == null)          {             JOptionPane.showMessageDialog(null,"No port selected.","Port Choose",JOptionPane.PLAIN_MESSAGE);          }          else          {             try             {                commport=commid.open("DarwinSys DataComm", TIMEOUTSECONDS * 100);             }             catch(Exception e)             {             }             ParallelPort pPort = (ParallelPort)commport;             int mode = pPort.getMode();             switch (mode)              {                   case ParallelPort.LPT_MODE_ECP:                   System.out.println("Mode is: ECP");                   break;                   case ParallelPort.LPT_MODE_EPP:                   System.out.println("Mode is: EPP");                   break;                   case ParallelPort.LPT_MODE_NIBBLE:                   System.out.println("Mode is: Nibble Mode");                   break;                   case ParallelPort.LPT_MODE_PS2:                   System.out.println("Mode is: Byte mode.");                   break;                   case ParallelPort.LPT_MODE_SPP:                   System.out.println("Mode is: Compatibility mode.");                   break;                   default:                   throw new IllegalStateException                   ("Parallel mode " + mode + " invalid.");                }                try                 {                   is = new DataInputStream(commport.getInputStream());                   setup_menuitem.setEnabled(true);                }                 catch (IOException e)                 {                   System.err.println();                   is = null;                }                try                {                   os = new PrintStream(commport.getOutputStream(), true);                }                catch(IOException e)                {                   JOptionPane.showMessageDialog(null,"Can't open output stream.","                   Port Choose",JOptionPane.PLAIN_MESSAGE);                }                int startpos=0;                int endpos=0;                StringBuffer srtbuffer=new StringBuffer(2500);                srtbuffer=new StringBuffer(textpane.getText());                endpos=srtbuffer.indexOf("\n",startpos);                while (endpos!=-1)                {                   String strprint =  srtbuffer.substring(startpos,endpos) ;                   os.println(strprint);                   startpos=endpos+1;                   endpos=srtbuffer.indexOf("\n",startpos);                }                os.close();                commport.close();                comport.setVisible(false);           }       } } 
end example

Download this listing.

In the above listing, the main() method creates an instance of the CommPrinting class. This class generates the main window of the Printing application, as shown in Figure 4-2:

click to expand: this figure shows the user interface of the printing application. the user interface contains the menu bar and the edit pane.
Figure 4-2: The Printing Application User Interface

The edit pane enables an end user to display and edit the document to be printed.

The menu bar provides two menus, File and Settings. The File menu of the Printing application provides four menu options: Open, Page Setup & Print, Choose COM Port to Print, and Exit, as shown in Figure 4-3:

this figure shows the menu options that the file menu provides.
Figure 4-3: The File Menu

The Open menu option of the File menu enables the end user to open the text document to be printed. The user interface of the Printing application provides a file filter to ensure that the end user selects and opens only the text file. The Page Setup and Print menu option on the File menu specifies page setup properties and prints the text in the document. The Choose COM Port to Print menu option on the File menu allows the end user to select the COM port to which the printer is connected. The Exit menu option terminates the Printing application.

The Settings menu of the Printing application provides two menu options, Font and Color, as shown in Figure 4-4:

this figure shows the menu options that the settings menu provides to allow an end user to change the font and the color of text in the specified document.
Figure 4-4: The Color Menu

The Font menu option enables an end user to select the font of the text in the document to be printed. The Color menu option specifies the color of the text in the document printed using the Printing application.




Developing Applications Using JCA
Developing Applications Using JCA
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 43

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net