I l @ ve RuBoard |
If you've spent time writing an application in Java, the last thing you want to do is to rewrite it using the .NET classes. In this section, we'll look at how you can compile and run an AWT application under .NET. The code we'll use is for a simple text editor. In this section, the code will use the AWT libraries. The code for the application follows , in the class EditorFrame . We won't walk you through how the AWT works (this is a book about .NET, after all), but to summarize, the EditorFrame constructor calls the initComponents method, which creates new instances of all the components used within the application. The bulk of this method builds the menu structure for the application. For each menu item instance, the code sets shortcut and name properties and adds an ActionListener, which wires the event that each menu item fires to a corresponding event handler method. Most of the event handlers perform fairly straightforward operations, but it is important to note that the cut , copy , and paste methods in this application use the system clipboard, so the EditorFrame class also implements the ClipboardOwner interface: EditorFrame.javaimportjava.io.*; importjava.awt.*; importjava.awt.event.*; importjava.awt.datatransfer.*; publicclassEditorFrameextendsFrameimplementsClipboardOwner{ //Thismethodiscalledfromwithintheconstructorto //initializetheform. privatevoidinitComponents(){ //Initializethecomponentsandmenus mainMenuBar=newjava.awt.MenuBar(); fileMenu=newjava.awt.Menu(); openMenuItem=newjava.awt.MenuItem(); saveMenuItem=newjava.awt.MenuItem(); exitMenuItem=newjava.awt.MenuItem(); editMenu=newjava.awt.Menu(); cutMenuItem=newjava.awt.MenuItem(); copyMenuItem=newjava.awt.MenuItem(); pasteMenuItem=newjava.awt.MenuItem(); textEditor=newjava.awt.TextArea(); //InitializetheFilemenuanditsmenuitems fileMenu.setLabel("File"); //TheOpenfilemenuitem openMenuItem.setShortcut(newMenuShortcut(79)); openMenuItem.setLabel("Open"); openMenuItem.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEventevt){ openMenuItemActionPerformed(evt); } }); fileMenu.add(openMenuItem); //TheSavefilemenuitem saveMenuItem.setShortcut(newMenuShortcut(65)); saveMenuItem.setLabel("Save"); saveMenuItem.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEventevt){ saveMenuItemActionPerformed(evt); } }); fileMenu.add(saveMenuItem); fileMenu.addSeparator(); //TheExitfilemenuitem exitMenuItem.setLabel("Exit"); exitMenuItem.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEventevt){ exitMenuItemActionPerformed(evt); } }); fileMenu.add(exitMenuItem); //AddtheFilemenutothemainmenubar mainMenuBar.add(fileMenu); //InitializetheEditmenuanditsmenuitems editMenu.setLabel("Edit"); //TheCuteditmenuitem cutMenuItem.setShortcut(newMenuShortcut(88)); cutMenuItem.setLabel("Cut"); cutMenuItem.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEventevt){ cutMenuItemActionPerformed(evt); } }); editMenu.add(cutMenuItem); //TheCopyeditmenuitem copyMenuItem.setShortcut(newMenuShortcut(67)); copyMenuItem.setLabel("Copy"); copyMenuItem.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEventevt){ copyMenuItemActionPerformed(evt); } }); editMenu.add(copyMenuItem); //Thepasteeditmenuitem pasteMenuItem.setShortcut(newMenuShortcut(86)); pasteMenuItem.setLabel("Paste"); pasteMenuItem.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEventevt){ pasteMenuItemActionPerformed(evt); } }); editMenu.add(pasteMenuItem); //AddtheEditmenutothemainmenubar mainMenuBar.add(editMenu); //Setthetitleoftheframetosomethingmeaningful setTitle("Editor"); //Allowthewindowtoclosecleanly addWindowListener(newWindowAdapter(){ publicvoidwindowClosing(WindowEventevt){ exitForm(evt); } }); //Definethepropertiesofthetextboxthatisusedas //themaineditareas textEditor.setBackground(java.awt.Color.white); textEditor.setFont(newjava.awt.Font("Dialog",0,11)); textEditor.setColumns(120); textEditor.setForeground(java.awt.Color.black); textEditor.setRows(30); //Addthetexteditortextboxtothewindow add(textEditor,java.awt.BorderLayout.CENTER); //Addthemainmenubartothewindow setMenuBar(mainMenuBar); } //Eventhandlingmethodsforthevariousmenuitems //OpenafileanddisplayitscontentsinthetextEditortextarea privatevoidopenMenuItemActionPerformed(ActionEventevt) { BufferedReaderbr=null; Stringtext=""; Stringline; StringtheFile=null; //Displayafiledialogtoallowtheusertoselectthefile FileDialogfd=newFileDialog(this, "Pickafile", FileDialog.LOAD); fd.show(); theFile=fd.getDirectory()+fd.getFile(); if(theFile==null) { System.err.println("thefileisnull"); } //readthecontentsofthetextfile try { br=newBufferedReader(newFileReader(theFile)); while((line=br.readLine())!=null) { text+=line+System.getProperty("line.separator"); } } catch(IOExceptionioe) { System.err.println("Exception: " +ioe.getMessage()); } //Updatethedisplay textEditor.setText(text); } //SavethecontentsofthetextEditortextareatoafile privatevoidsaveMenuItemActionPerformed(ActionEventevt){ StringtheFile; BufferedWriterbw=null; //Firstfindoutwhattheywanttosaveitas FileDialogfd=newFileDialog(this, "Saveas",FileDialog.SAVE); fd.show(); theFile=fd.getDirectory()+fd.getFile(); //Nowwritethecontentstothefile try{ bw=newBufferedWriter(newFileWriter(theFile)); bw.write(textEditor.getText()); } catch(IOExceptionioe){ System.err.println("Exception: " +ioe.getMessage()); } finally{ try{ bw.flush(); bw.close(); } catch(IOExceptionioe){ System.err.println("Exception: " +ioe.getMessage()); } } } //Exittheapplication(calledbytheexitmenuitem) privatevoidexitMenuItemActionPerformed(ActionEventevt){ System.exit(0); } //ExittheApplication(calledbythewindowitself) privatevoidexitForm(WindowEventevt){ System.exit(0); } //CuttheselectedtextfromthetextEditortextareatotheclipboard privatevoidcutMenuItemActionPerformed(ActionEventevt){ //Copytheselectedtexttotheclipboard,reusing //theCopyeventhandlerdefinedbelow copyMenuItemActionPerformed(evt); //Deletetheselectedtextfromthetextarea //byoverwritingitwithanemptystring intstartPos=textEditor.getSelectionStart(); intendPos=textEditor.getSelectionEnd(); textEditor.replaceRange("",startPos,endPos); } //Thismethodplacesstuffontheclipboardwhenausercopies //inthisexampleusingthesystemclipboardthroughtheToolkit //however,thisisnotplatformportable.Ifwewishplatform //independenceweshouldusetheClipboardinthe //java.awt.datatransferpackage privatevoidcopyMenuItemActionPerformed(ActionEventevt) { //Gettheselectedtext Strings=textEditor.getSelectedText(); //TheclipboardholdsonlyTransferabletypes,soweuse //oneofitsimplementations StringSelectionss=newStringSelection(s); //Copythestringintothesystemclipboard this.getToolkit().getSystemClipboard().setContents(ss,this); } //PastethecontentsoftheclipboardtothetextEditortextarea privatevoidpasteMenuItemActionPerformed(ActionEventevt) { //Gettheclipboard Clipboardc=this.getToolkit().getSystemClipboard(); //Getthecontentsoftheclipboard Transferablet=c.getContents(this); try { if(t.isDataFlavorSupported(DataFlavor.stringFlavor)) { Strings=(String) t.getTransferData(DataFlavor.stringFlavor); //Obtainthecaretposistion intp=textEditor.getCaretPosition(); //Insertthetextatthispoint textEditor.insert(s,p); } } catch(Exceptione){ System.err.println("Exception: " +e.getMessage()); } } //Miscellaneousmethodsandconstructors //RequiredmethodbecauseweareimplementingClipboardOwner publicvoidlostOwnership(Clipboardc,Transferablet){ } //CreatesnewformEditorFrame publicEditorFrame() { initComponents(); pack(); } //Theentrypointtotheprogram publicstaticvoidmain(Stringargs[]){ newEditorFrame().show(); } //Variabledeclarations privatejava.awt.MenuBarmainMenuBar; privatejava.awt.MenufileMenu; privatejava.awt.MenuItemopenMenuItem; privatejava.awt.MenuItemsaveMenuItem; privatejava.awt.MenuItemexitMenuItem; privatejava.awt.MenueditMenu; privatejava.awt.MenuItemcutMenuItem; privatejava.awt.MenuItemcopyMenuItem; privatejava.awt.MenuItempasteMenuItem; privatejava.awt.TextAreatextEditor; } You can compile and run this application using the JDK version 1.1.4 or later. However, the main purpose of showing this code is to demonstrate that it will also work unchanged with J#. You can compile the EditorFrame.java file using vjc to produce EditorFrame.exe, which will run like any other .NET executable program.
A good IDE takes the pain out of GUI development. The IDE for Windows .NET development is Visual Studio .NET. It has many great features, such as
Visual Studio .NET provides a number of project templates that can give you a head start on building different types of applications. For building GUI applications, you'll probably find the Windows Application template most useful, as described later. Porting AWT Applications to .NETYou've seen that you can compile ordinary Java (.java) source files from the command line using the vjc compiler to build a .NET executable. You can also use the Visual Studio .NET IDE. The simplest way to edit and compile existing . java files with Visual Studio .NET is to create a new empty project and then import the Java source code: From the Visual Studio IDE, choose New and then Project from the File menu. The New Project dialog box will appear, as shown in Figure 4-4. Figure 4-4. The New Project dialog box in Visual Studio .NET
In the Project Types pane, select Visual J# Projects, and in the Templates pane, select Empty Project. To create the project, give the project a name ”for example, EditorAWT ” and then click OK. Your first impression might be that nothing has happened . But if you look at the right side of the IDE, you'll see Solution Explorer displaying the project you just created. The project is currently empty, so to add the existing source file choose Add Existing Item from the Project menu. The Add Existing Item dialog box will appear, as shown in Figure 4-5. Browse to the folder containing your .java files, select the file you want to add to the project, and then click Open. Visual Studio .NET will add the file to the current project. Figure 4-5. The Add Existing Item dialog box in Visual Studio .NET
You should see the code appear in the main window of the IDE. Although we won't be changing this code, go ahead and browse through it to appreciate the colorized highlighting that identifies key words and comments. (How many times have you opened a multiline comment and forgotten to close it again? This sort of error is easier to spot in a colorized environment!)
This feature allows you to focus on the areas of the program you're currently developing, without needing to scroll through large quantities of code to find various methods. To build and run the project, choose Start from the Debug menu. If there are any errors in your source, these will be displayed in the Output window of the IDE. Otherwise, the application will open a command window and execute. |
I l @ ve RuBoard |