Java desktop application with netbeans

NetBeans Platform Quick Start

The NetBeans Platform is a generic application framework primarily for Java desktop applications. The main benefit of the NetBeans Platform is its predefined modular architecture. Secondary benefits are the NetBeans Platform’s reusable solutions such as its docking framework and its out-of-the-box pluggable components, in combination with the tools provided by its SDK, NetBeans IDE, in particular its award winning «Matisse» GUI Builder for designing GUI components.

In this quick start, you are introduced to the benefits and usages of modularity on the Java desktop via a very simple example, contributed by Thomas Würthinger, a PhD student at the Johannes Kepler University in Linz, Austria. Once you have grasped the concepts introduced in this quick start, you will be ready to step onto the NetBeans Platform Learning Trail, providing a very rich variety of tutorials for many different scenarios relating to the NetBeans Platform.

If you are new to the NetBeans Platform, it is highly recommended to get hold of NetBeans Platform for Beginners (published in 2014).

For troubleshooting purposes, you are welcome to download the completed tutorial source code.

Even though it is a separate product, there is no need to download the NetBeans Platform separately. Typically, you develop the application in NetBeans IDE and then exclude the modules that are specific to the IDE but that are not required for your application.
Читайте также:  Javascript this tag name

A Single Module NetBeans Platform Application

We start by creating a new NetBeans Platform application, containing a single module.

Create the Application

In this section, you create your first NetBeans Platform application.

  1. Choose File | New Project and then choose NetBeans Modules. Select «NetBeans Platform Application». You should see this:

quickstart platform new project 1

The difference between the 4 templates above is as follows:

  • NetBeans Platform Application. A project that groups a set of module projects and library wrapper module projects that have dependencies on each other, and lets you deploy them together as a unit. Automatically included are a subset of the modules that make up the NetBeans Platform.
  • Module Suite. Same as above, except that the pre-included modules are more than only those relating to the NetBeans Platform—in this case, all the modules that make up NetBeans IDE are included as well.
  • Library Wrapper Module. A project that puts a library JAR file on its classpath and exports some or all of the JAR file’s packages from the module as public packages.
  • Module. A project for implementing the functionality, business logic, and user interface of a module or application built on the NetBeans Platform.

quickstart platform new project 2

Click Finish. The new project appears as follows in the Projects window:

quickstart platform new project 3

Create the Module

In this section, you create your first NetBeans Platform module.

quickstart platform new module 1

The New Module Project dialog will appear. Name the new module WordEditorCore :

quickstart platform new module 2

  1. Specify «org.word.editor.core» as the Code Name Base, which is a unique string identifying the module. The Module Display Name is used as a label for the module in the Projects window.

quickstart platform new module 3

Click Finish. The new module is created and its structure is shown in the Projects window:

quickstart platform new module 4

Create the Window

Having created a module, you now create your first NetBeans window.

quickstart platform new window 1

The New File dialog appears. In the Module Development category, select «Window»:

quickstart platform new window 2

  1. You should now see a dialog for specifying the position where the new window will appear in the application frame, as well as whether it will open automatically when the application starts, among other settings.

Set the Window Position to be editor , which is the default central position within the application frame, and select «Open on Application Start».

quickstart platform new window 3

quickstart platform new window 4

Click Finish. The new window («WordTopComponent.java») is added to the source structure of your module:

quickstart platform new window 5

  1. The new window should have opened in the Design view of the «Matisse» GUI Builder. You can double-click (or select «Open» from the context menu) it if it didn’t open automatically.

quickstart platform new window 6

The Palette should be open on the right side (you can use Window IDE Tools Palette or Ctrl + Shift + 8 if not). Drag and drop a Button and a Text Area from the Palette onto the window:

quickstart platform new window 7

Do the following to make the new GUI components more meaningful:

  • Right-click the text area, choose «Change Variable Name», and then name it text .
  • Right-click the button, choose «Edit Text», and then set the text of the button to Filter! . Also rename the variable to filterButton .

quickstart platform new window 7

  1. Double click on the button. This will create an event handling method in the Source editor. The method is called whenever the button is clicked. Change the body of the method to the following code:
 private void filterButtonActionPerformed(java.awt.event.ActionEvent evt)

You have now created the window module. When the «Filter!» button is clicked, the filterButtonActionPerformed method will be called, which will get the content of the text text area, convert that text to upper case, and put the upper case version into the text text area.

Run the Application

In this section, you deploy the application.

quickstart platform new app 1

Doing so will start up your new NetBeans Platform application and install your module. You will have a new window, as well as a new menu item for opening it, as shown below:

quickstart platform new app 2

quickstart platform new app 3

You should see that the text is now shown in uppercase:

quickstart platform new app 4

You have learned how to create a new Apache NetBeans Platform application and how to add new modules to it. In the next section, you will be introduced to the Apache NetBeans Platform’s pluggable service infrastructure.

A Modular Application Using Lookup

In this section, you create two additional modules. The first new module, «WordEditorAPI», contains a service provider interface. The second module, «UppercaseFilter», is a service provider for the interface.

The GUI module, which you created in the previous section, will be loosely coupled from the «UppercaseFilter» service provider because the GUI module will not refer to any code from the «UppercaseFilter» service provider. That will be possible because the «UppercaseFilter» service provider will be registered in the META-INF/services folder and loaded via the NetBeans Lookup class, which is comparable to the JDK 6 ServiceLoader class.

You will then create another loosely coupled service provider, named «LowercaseFilter».

The concept is that instead of all the different functions needing to be added to «WordEditorCore», each function can be implemented separately, without coupling the filter operation to the display of the result.

Источник

Быстрое учебное руководство по Java IDE NetBeans

В этом учебной курсе приводится очень простое и быстрое введение в поток операций IDE NetBeans путем пошагового описание создания простого консольного приложения «Hello World» Java. Ознакомление с этим руководством даст общее представление о создании, сборке и выполнении приложений в среде IDE.

Изучение материала, представленного в этом руководстве, занимает приблизительно 10 минут.

После завершения этого учебного курса можно перейти к учебным картам, на которые имеются ссылки на странице Документация, обучение & поддержка. Учебные карты обеспечивают полные учебные руководства, в которых описываются широкий диапазон функций IDE и приемов программирования для различных типов приложений. Если не нужно использовать приложение «Здравствуй, мир», можно пропустить это учебное руководство и перейти напрямую к учебным картам.

netbeans stamp 80 74 73

Для работы с этим учебным курсом требуются программное обеспечение и ресурсы, перечисленные ниже.

Настройка проекта

Для создания проекта IDE выполните следующие действия:

new proj

  1. В мастере создания проекта разверните категорию «Java» и выберите «Приложение Java». Затем нажмите кнопку «Дальше».

proj wizard small

  • введите HelloWorldApp в поле «Имя проекта»;
  • Не устанавливайте флажок «Использовать отдельную папку для хранения библиотек».
  • в поле «Создать главный класс» введите helloworldapp.HelloWorldApp ;

proj wizard2 small

Проект будет создан и открыт в среде IDE. На экране должны быть представлены следующие элементы:

  • окно «Проекты», которое содержит дерево элементов проекта, в том числе исходные файлы, библиотеки, от которых зависит код, и т.д.;
  • окно редактора исходного кода с открытым файлом HelloWorldApp ;
  • окно «Переходы», которое можно использовать для быстрого перемещения между элементами внутри выбранного класса.

proj opened small

Добавление кода к автоматически созданному исходному файлу

Поскольку в мастере создания проекта не был снят флажок «Создать главный класс», средой IDE был создан новый главный класс. К коду этого класса можно добавить, например, сообщение «Hello World!» путем замены строки

 // TODO code application logic here
 System.out.println("Hello World!");

Сохраните изменения путем выбора команды «Файл» > «Сохранить».

Файл должен быть похож на следующий пример:

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package helloworldapp; /** * * @author */ public class HelloWorldApp < /** * @param args the command line arguments */ public static void main(String[] args) < System.out.println("Hello World!"); >>

Компиляция и выполнение проекта

Благодаря функции среды IDE «Компиляция при сохранении» компилировать проект вручную для выполнения в среде IDE не требуется. При сохранении исходного файла Java в среде IDE выполняется автоматическая компиляция.

Функция компиляции при сохранении отключается в окне «Свойства проекта». Щелкните проект правой кнопкой мыши, выберите «Свойства». В окне «Свойства» перейдите на вкладку «Компиляция». Флажок «Компиляция при сохранении» расположен вверху справа. Обратите внимание, что в окне «Свойства проекта» можно выполнять настройку многочисленных параметров проекта: библиотеки проекта, пакетирование, сборка, выполнение и т. д.

Для запуска программы выполните следующие действия.

На экране должны появиться сообщения, подобные приведенным ниже.

run output

Поздравляем! Программа работает!

Если при компиляции возникли ошибки, они отмечаются специальными красными символами в левом и правом полях редактора исходного кода. Символы в левом поле указывают на ошибки в соответствующих строках. Символы в правом поле указывают на все области файла, в которых есть ошибки, в том числе не отображаемые визуально ошибки в строках. Для получения описания ошибки можно навести курсор на метку ошибки. Для перехода к строке с ошибкой щелкните специальный символ в правом поле.

Сборка и развертывание приложения

После сборки и тестирования приложения для подготовки его к развертыванию можно использовать команду «Очистить и собрать». При использовании команды «Очистить и собрать» в среде IDE автоматически запускается сценарий сборки, выполняющий следующие задачи:

  • удаление предварительно скомпилированных файлов и других результатов сборки;
  • повторная компиляция приложения и формирование файла JAR, содержащего скомпилированные файлы.

Для сборки приложения выполните следующие действия

Для просмотра выходных файлов сборки можно открыть окно «Файлы» и развернуть узел HelloWorldApp . Скомпилированный файл байтового кода HelloWorldApp.class находится в подузле build/classes/helloworldapp . Развертываемый архив JAR, содержащий HelloWorldApp.class , находится в узле dist .

files window

Итак, теперь вы можете выполнять базовые задачи по программированию в среде IDE.

Подробнее о том, как запустить приложение из командной строки, см. главу Запуск приложений Java учебного руководства по упаковке и распределению приложений Java.

Дополнительные сведения

Информацию о создании стандартных и произвольных проектов Java и работе с ними см. в разделе Создание проектов Java в документе Разработка приложений в IDE NetBeans.

Дополнительные сведения о разработке приложений Java в среде IDE, включая управление путем к классам, доступны в документе Разработка базовых приложений Java.

Для получения подробных инструкций о том, как скомпилировать и выполнить простое приложение «Hello World!» в используемой операционной системе, см. занятие Приложение «Hello World» в учебных курсах по Java.

Чтобы найти сведения, связанные с определенным типом разрабатываемых приложений, используйте карту обучения для этого типа приложений. Каждая учебная карта содержит ряд учебных курсов и руководств различных уровней сложности. Доступны следующие учебные карты:

Источник

Оцените статью