SEÇÃO 3 – DESENVOLVIMENTO JAVA SE 3.1 – Demonstrar habilidade para criar projetos no NetBeans a partir de código existente de um programa Java SE Para criar um projeto a partir de códigos já existentes, é necessário acessar o menu File, opção New Project (Atalho Ctrl+Shift+N), Categoria Java, opção “Java project with Existing sources”. Na tela seguinte é possível configurar o nome do projeto, pasta onde ficarão armazenados os arquivos, script do construção (utilizando padrão ANT) e definir se as bibliotecas externas serão utilizadas a partir de sua origem ou se serão criadas cópias dessas bibliotecas para uma determinada pasta interna ao projeto além de decidir se este projeto será o projeto principal (ativo) da IDE. Avançando mais uma tela, é necessário configurar as origens de código que serão utilizados (lembrese que você está utilizando a opção de projeto COM CÓDIGOS EXISTENTES) e podem ser adicionados separadamente códigos fonte de projeto e de testes. O próximo passo (opcional) é, a partir dos códigos adicionados na fase anterior, selecionar quais pacotes serão adicionados ao seu projeto de forma individual ou atavés de caracteres coringa “*” (em inglês, wildcards). Essa listagem é construida a partide uma varredura em seus códigosfonte adicionados, onde a opção includes serve para indicar os caminhos absolutos ou relativos que serão adicionados ao seu projeto enquanto que excludes aponta para os caminhos para os pacotes que você deseja não importar para seu projeto. O caractere *: quando usado no formato simples, indica que serão consideradas quaisquer combinações de nomes de arquivos de um ou mais caracteres no lugar do *. Quando utilizado em formato duplo ** ele aponta para os diretórios recursivamente até o diretório raiz. Ao terminar este procedimento de filtragem, quando o botão “Finish” for pressionado, seu projeto será criado e os arquivos fonte serão copiados para seu diretório do novo projeto, desta vez,no PADRÃO NETBEANS, será criado. 3.2 – Descrever como gerenciar o classpath de um projeto Java SE, incluíndo manter classpaths separados para compilação e depuração Classpath é um conjunto de caminhos informados para a JVM (através de um argumento de linha de comando e/ou variável de ambiente) que aponta onde ela deve buscar pelas classes usadas em um determinado programa Java tanto em tempo de compilação quanto de execução. O NetBeans, além das funcionalidades básicas, utiliza o classpath para gerar a completação automática de código, destaque com cores (syntax highlighting) além de informar erros de compilação e refatoração. Um exemplo prático de onde a refatoração é utilizada acontece quando o usuário deseja modificar o nome de um pacote. A ferramenta irá buscar por todas as classes que tem o nome antigo do pacote e atualizálas. Nos projetos padrão do NetBeans a IDE mantém classpaths separados para as ações de compilação e execução os quais podem ser visualizados com um clique com o botão direito no seu projeto, opção “Properties”, em seguida clicando na categoria “Libraries” ou a partir do icone “Libraries”, opção “Properties” diretamente da janela principal do NetBeans. Será exibida uma janela com quatro abas que são exatamente os classpaths para “Compilação” e “Execução” dos programas e “Compilação” e “Execução” dos testes onde é possível adicionar desde projetos inteiros, bibliotecas JAR ou pastas com JARs. 3.3 – Demonstrar conhecimento no NetBeans GUI Builder e habilidade para desenhar e ligar formulários básicos usando este recurso The GUI Builder is the primary workspace within which GUI design takes place in the IDE. The GUI Builder enables you to lay out forms by placing components where you want them and by providing visual feedback in the form of guidelines. Designing Java GUIs with the GUI Builder The IDE's GUI Builder enables you to design GUI's (graphical user interfaces) visually. As you create and modify your GUI, the IDE automatically generates the Java code to implement the interface. GUI forms are indicated by form nodes ( ) in the Projects, Files, and Favorites windows. Using the GUI Builder Whenever you open a GUI form, the IDE displays it in a Editor tab with toggle buttons enabling you to switch between Source and Design views. The Design view enables you to work with GUI forms visually while the Source view permits editing of the form's source code directly. Each time you select a form's Design toggle button, the Palette, Inspector, and Properties windows appear automatically. Typically, components are added to a form using the Palette window and arranged in the GUI Builder workspace. As you work, the GUI Builder automatically displays guidelines suggesting preferred alignment and anchoring for the components you add. Using the Inspector window in conjunction with the Properties window, you can then examine and adjust properties of a form's components and layout managers, manage component event handlers, and define how code is generated. By default, the GUI Builder uses the GroupLayout layout manager for all new forms you create. If you want to use another layout manager, you can do so by rightclicking the container, choosing Set Layout, and then choosing the desired layout manager. In order for interfaces that you create with the GroupLayout layout manager to run outside of the IDE, they must have the Swing Layout Extensions library available. The Swing Layout Extension Library is included in version 6 of the Java Platform, so no additional steps are needed if you develop the application with JDK 6 and deploy in environments that have version 6 of the JRE. If you are developing for earlier versions of the Java Platform, you must bundle the Swing Layout Extension Library with the application. For more information, see Deploying Java GUI Applications. Guarded Blocks As you work with a form in the Design view, code is generated automatically by the GUI Builder and is displayed in the Source view with a blue background. This code is called guarded text and is not directly editable. Guarded text generated by the GUI Builder's includes: • • • Blocks of components' variable declarations. The initComponents() method, in which form initialization is performed. This method is called from the form's constructor and though it is not editable manually, you can affect the way it is generated by editing the Code properties in the component's property sheet. The header (and trailing brace) of all event handlers. For more information about editing the IDE's GUI source code, see Modifying GUI Source Code GUI Form Hierarchy in the IDE The IDE's Inspector window provides a hierarchical tree view of the form's various components. Each form is represented by a root node ( ) within which all components in the form's class are contained. All other GUI components are organized into one of the following two subnodes: • • Form Container node ( ). Represents the top level of the form's hierarchy and contains the visible components currently displayed in the GUI Builder. Other Components node ( ). Contains the form's nonvisual components. Notes: • • • • To use the GUI Builder, you must work with files that were created with the IDE's GUI form templates. You cannot use the GUI Builder to edit GUI forms that were created outside of the IDE. You can combine FreeDesign containers and containers using other layout managers together in the same form. Forms created in earlier versions of the IDE are not automatically converted to the FreeDesign layout manager and remain editable in the same way as before. New containers added to forms created in earlier versions of the IDE do not assume the FreeDesign layout manager in order to ensure code compatibility. However, you can set it manually in the Set Layout submenu. Options Window: Miscellaneous: GUI Builder You use this panel to configure code generation properties for the GUI Builder. You can access this panel by choosing Tools > Options from the main menu, clicking the Miscellaneous category and then clicking the GUI Builder tab. Code Generation settings • • • Generate Components as. Select how the GUI Builder components are generated. Variables Modifier. Select from the dropdown list an access modifier for variables generated for components on the form. Listener Generation Style. Determines how the code for component events and their handlers is generated. All of the options produce functionally equivalent code, but each option has different performance qualities. Select one of the following options from the dropdown list: • Anonymous Innerclasses. One anonymous innerclass is generated for each event. This option might have a negative impact on the performance and memory of the application because the application must load and keep open many classes when the form is executed. • One Innerclass. One common innerclass is generated for the whole form. This innerclass implements all necessary listeners and dispatches all events to the attached event handlers. The resulting code is less compact and slightly less efficient, but the anonymous innerclasses are eliminated. This option is particularly suitable for large • • • forms with many components and event handlers. • Main Class. The form's main class implements the listeners. No special innerclass for events is generated. This is the most efficient option, but it does not work well with all types of forms. This option should only be used if the form class does not declare any listener implementation that could interact with events that are generated by components in the form. Automatic Internationalization. Select an option from the dropdown list to specify if the GUI Builder should automatically generate the properties files where internationalized strings are stored. Fold Generated Code. If selected, generated code is folded in the Source Editor. Show Assistant. If selected, the GUI Builder Assistant is displayed in design view. GUI Builder Tasks: Quick Reference The following table describes common GUI Builder tasks. To perform this Follow these steps task Do one of the following: • Reload a form. Create a menu bar. Add a menu to a menu bar. Add a menu item. • Press CtrlR in either the GUI Builder or the Source Editor. Rightclick the root node of the form in either the Files window, Projects window, or Inspector window and select Reload Form from the contextual menu. 1. In the Palette window, click a JMenuBar ( ) or MenuBar ( ) component. 2. Click anywhere in the JFrame, JDialog, or JApplet container to which you want to add the menu bar. If this is the first menu bar you have added to the form, the menu bar appears visually on the form. If this is not the form's first menu bar, the menu appears below the Other Components node in the Inspector window and is not visible in the form. 1. Rightclick the menu bar in the Inspector window and choose Add JMenu or Add Menu from the contextual menu. 2. If you wish to name the new menu, expand the menu bar node in the Inspector window, rightclick the newly created menu node, and choose Properties. Then enter the desired name for the text property. 1. In the Inspector window, rightclick the menu to which you would like to add an item. 2. Choose Add from the contextual menu and then choose an item from the submenu. 3. If you wish to rename the new menu item, expand the menu node in the Inspector window, rightclick the newly created menu item, and choose Properties. Then enter the desired name for the text property. Create a contextual menu. 1. In the Palette window, click the JPopupMenu ( ) or PopupMenu ( ) contextual menu component. 2. Click anywhere in the form to add the contextual menu. The new menu appears under the Other Components list in the Inspector window. Do one of the following: • Add an event handler to a component. Configure the GUI Builder. Move or copy a component. Edit component labels. Create a Palette window category. Create a Palette • • Select the component in the Inspector window. Then click the Events button in the Properties window and select the desired event property. Rightclick the component in the Inspector window or GUI Builder and choose the desired event from the Events menu in the contextual menu. Use the Connection wizard by clicking the connection icon in the GUI Builder toolbar, next clicking the source component, and then clicking the target component. 1. Choose Tools > Options. 2. Select the GUI Builder Settings node. 3. Edit the desired GUI Builder properties. 1. Select the component in the GUI Builder or Inspector window. 2. Rightclick the component and choose Cut or Copy from the contextual menu. 3. Rightclick the destination container in the GUI Builder or Inspector window and choose Paste from its contextual menu. The component or components are moved or copied with all properties intact. Events are maintained only if you are pasting within the same form. 1. Select the component in the GUI Builder and do one of the following to display the inplace editing field: • Press the spacebar. • Click the component again. • Rightclick the component and choose Edit Text from the contextual menu. 2. Type the new label and press Enter. 1. Choose Tools > Palette > Swing/AWT Components. 2. In the Palette window, rightclick any existing category button and choose Create New Category from the contextual menu. 3. Type a name for the new category in the dialog box that appears and click OK. 1. Choose Tools > Palette > Swing/AWT Components. window category. Remove a Palette window category. Copy a palette category item. Remove a palette category item. Add a bean to the Palette window. 2. Click the New Category button. 3. Type a name for the new category in the dialog box that appears and click OK. 1. Choose Tools > Palette > Swing/AWT Components. 2. Click the Remove button. 3. Click Yes in the dialog box that appears. 1. Choose Tools > Palette > Swing/AWT Components. 2. In the Palette, rightclick any existing component and choose Copy from the contextual menu. 3. Rightclick the Palette category in which you wish to place the component and choose Paste > Copy. 1. Choose Tools > Palette > Swing/AWT Components. 2. Click the Remove button. 3. Click Yes in the dialog box that appears. 1. Choose Tools > Palette > Swing/AWT Components. 2. If you wish to create a new category for the bean, click New Category before you add the bean. 3. Click Add from JAR, Add from Library, or Add from Project. Complete the wizard to add the bean. Preparing a JAR File for Deployment Outside the IDE Whenever you build a standard Java project for which a main class is specified, the IDE automatically copies any JAR files on the project's classpath to the dist/lib folder. The IDE also adds each of the JAR files to the ClassPath element in the application JAR's manifest.mf file. This simplifies running the application outside the IDE. Though the IDE copies the necessary files to the dist/lib directory automatically, the following special cases should be kept in mind: • If two JAR files on the project classpath have the same name, only the first JAR file is copied to the lib folder. • If you added a folder of classes or resources to the classpath (as opposed to a JAR file or project), none of the classpath elements are copied to the dist folder. • If a library on the project's classpath also has a ClassPath element specified in its manifest, the content of the ClassPath element must be on the project's runtime path. Running an Application JAR Outside of the IDE Once you have distributed the archive of your application, the application can be run outside of the IDE from the command line. To run an application JAR file from the command line: 1. Navigate to the project's dist folder. 2. Type the following: java jar <jar_name>.jar When you run the jar command, the JAR tool uses the JAR manifest to determine the application entry point and the paths to the dependent binaries that are specified in the manifest.mf file.