- Eclipse Window Builder Tutorial for GUI Creation
- Thank you!
- 2.Simple Java Window Application
- 2.1 System requirements
- 2.1.1 Eclipse
- 2.1.2 Java
- 3. Open New Project
- 4. New SWT Application
- 5. Components in the editor
- 6. Editor Features
- 7. Layouts in SWT
- 8. New UI Page
- 9. Source View
- 10. Button Listener
- 11. Conclusion
- 12. Download the Code Project
- Java Eclipse пример оконного приложения — создание окна, задание размеров, добавление надписей и кнопок, вывод сообщения
- пакет TestForm
- Key Words for FKN + antitotal forum (CS VSU):
- Hello world, jFrame и Java
Eclipse Window Builder Tutorial for GUI Creation
In this example, we will show you how to develop Java GUI Application using Eclipse WindowBuilder plug-in. Eclipse WindowBuilder is a powerful and easy to use bi-directional Java GUI designer that makes it very easy to create Java GUI applications without spending a lot of time writing code to display simple forms. The bi-directional Java GUI designer means the developer can seamlessly move between a Drag n’ Drop designer and the generated code. Using Eclipse WindowBuilder, the developer will enjoy creating Java GUI based applications. One can create complicated windows in minutes using WindowBuilder. WYSIWYG (What You See Is What You Get) layout tools in WindowBuilder are used to generate back-end java code by drag-and-drop of components to the container.
In order to help you master Eclipse, we have compiled a kick-ass guide with all the basic features of the popular IDE! Besides studying them online you may download the eBook in PDF format!
Thank you!
2.Simple Java Window Application
2.1 System requirements
2.1.1 Eclipse
WindowBuilder is built as a plug-in to Eclipse. ‘Eclipse for RCP and RAP Developers’ is the default IDE bundled with ‘Windows Builder’ plug-in. This IDE has a complete set of tools for developers who want to create Eclipse plug-ins, Rich Client Applications (RCA). Download ‘Eclipse for RCP and RAP Developers’ from here. Please refer the picture given below to identify the correct IDE.
2.1.2 Java
3. Open New Project
Let us create a new ‘SWT/JFace Java Project’ to see the usage of WindowBuilder for building GUI components. Open ‘File – New – Other’ and then click ‘SWT/JFace Project’ as depicted below
The reason for creating new project as ‘SWT/JFace Java Project’ is to have all the necessary JARs and native libraries included by the IDE itself. Otherwise, you have to add all these dependent JARs and native libraries on your own.
The Standard Widget Toolkit (SWT) is a graphical widget toolkit to be used with the Java platform. It provides a portable graphics API independent of the OS but that relies on the native widgets.
JFace is a UI toolkit with classes for handling many common UI programming tasks. JFace is window-system-independent in both its API and implementation, and is designed to work with SWT without hiding it.
JFace is a higher-level user interface toolkit that uses the raw SWT widgets to provide model-driven widgets, and to some extent some functionality that isn’t available in the Swing libraries, such as advanced editors, dialog boxes, and wizards.
4. New SWT Application
Let us add widget to the project. As a main window, create Application Window as shown below. Right click on the project and select ‘New – Other – Window Builder – SWT Designer – SWT – Application Window’. And then click ‘Next’
Enter Class Name and click ‘Finish’
A basic window application has been created. Window Builder can be used to get your UI up and running quickly. Click ‘Design’ tab as shown below.
Now, you will see the graphical representation (Design View) of your code.
This application can be simply executed like any other java program with main method. Right click on the class name and ‘Run As – Java Application’
As we have not yet added any other elements, you will see a simple window popping-up as a result of the execution.
5. Components in the editor
- Design View – the main visual layout area.
- Source View – write code and review the generated code
- Structure View – composed of the Component Tree and the Property Pane.
- Component Tree – shows the hierarchical relationship between all of the components.
- Property Pane – displays properties and events of the selected components.
6. Editor Features
- Bi-directional Code Generation – read and write almost any format and reverse-engineer most hand-written code
- Internationalization (i18n) / Localization – externalize component strings, create and manage resource bundles.
- Custom Composites & Panels – create custom, reusable components.
- Factories – create custom factory classes and methods.
- Visual Inheritance – create visual component hierarchies.
- Event Handling – add event handlers to your components.
- Menu Editing – visually create and edit menubars, menu items and popup menus.
- Morphing – convert one component type into another.
7. Layouts in SWT
Layouts are non-visible widgets used to give GUI windows a specific look and it helps to control the position and size of children in a Composite.
To make sure the GUI application developed in one environment works perfect in another platform, Java provides a system of portable layout managers. We use these layout managers to specify rules and constraints for the layout of the UI in a way that will be portable.
- Correctly positioned components that are independent of fonts, screen resolutions, and platform differences.
- Intelligent component placement for containers that are dynamically resized at runtime.
- Ease of translation. If a string increases in length after translation, the associated components stay properly aligned.
SWT Designer supports the following layout managers.
Layout Manager Description AbsoluteLayout AbsoluteLayout or Null Layout helps to specify the exact position, the width and the height of components. In a generic environment where the size of the screens may vary, this layout manager should be avoided. FillLayout FillLayout is the simplest layout class. It lays out controls in a single row or column, forcing them to be the same size. RowLayout Puts the widgets in rows or columns and allows you to control the layout with options, e.g., wrap, spacing, fill and so on. GridLayout Arranges widgets in a grid. FormLayout Arranges the widgets with the help of the associated attachments. StackLayout A StackLayout object is a layout manager for a container. It treats each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards. BorderLayout BorderLayout lays out a container, arranging and resizing its components to fit in five regions: north, south, east, west, and center. Each region may contain no more than one component, and is identified by a corresponding constant: NORTH, SOUTH, EAST, WEST, and CENTER. BoxLayout BoxLayout allows multiple components to be laid out either vertically or horizontally. The components will not wrap so, for example, a vertical arrangement of components will stay vertically arranged when the frame is resized. Nesting multiple panels with different combinations of horizontal and vertical gives an effect similar to GridBagLayout, without the complexity. FlowLayout A flow layout arranges components in a left-to-right flow, much like lines of text in a paragraph. Flow layouts are typically used to arrange buttons in a panel. It will arrange buttons left to right until no more buttons fit on the same line. 8. New UI Page
We will now design a new Login UI page using Window Builder. For this normal size screen, we will continue with the default (absolute) layout. We are going to have an image, two labels, one text field, one password field and a button on the screen.
To display image use CLabel widget. CLabel supports aligned text and/or an image and different border styles.
As shown below, click ‘CLabel’ once and keep your cursor on the screen and click. Now, the ‘CLabel’ is placed on the screen.
Let us attach an image with ‘CLabel’. For this, you need to have an image in the folder where your ‘MainWindow’ source file is placed. For this example, I have used eclipse logo.
Click on the ‘CLabel’ and then, in the ‘Properties’ window select ‘image’.
You will now see the Image chooser window pops up. Select ‘Classpath resource’ option and navigate to the image file, select it and then click ‘OK’.
Adjust the field bounds according to the size of the logo so that the image is visible on the screen.
Similarly, add Labels, Text Fields and a Button. Finally the screen will be looking like the one shown below.
To test this design, right click on the window and select ‘Test/Preview’ from the popup menu.
9. Source View
Click ‘Source’ tab to see the code generated by the IDE. Single line of code in this was not written manually.
10. Button Listener
Attach listener with the button to validate field entries. Refer the source code of the main file given below.
package com.jcg.rca.main; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.wb.swt.SWTResourceManager; public class MainWindow < protected Shell shlLogin; private Text userNameTxt; private Text passwordTxt; private String userName = null; private String password = null; /** * Launch the application. * * @param args */ public static void main(String[] args) < try < MainWindow window = new MainWindow(); window.open(); >catch (Exception e) < e.printStackTrace(); >> /** * Open the window. */ public void open() < Display display = Display.getDefault(); createContents(); shlLogin.open(); shlLogin.layout(); while (!shlLogin.isDisposed()) < if (!display.readAndDispatch()) < display.sleep(); >> > /** * Create contents of the window. */ protected void createContents() < shlLogin = new Shell(SWT.CLOSE | SWT.TITLE | SWT.MIN); shlLogin.setSize(450, 300); shlLogin.setText("Login"); CLabel label = new CLabel(shlLogin, SWT.NONE); label.setImage(SWTResourceManager.getImage(MainWindow.class, "/com/jcg/rca/main/eclipse_logo.png")); label.setBounds(176, 10, 106, 70); label.setText(""); Label lblUsername = new Label(shlLogin, SWT.NONE); lblUsername.setBounds(125, 115, 55, 15); lblUsername.setText("Username"); Label lblPassword = new Label(shlLogin, SWT.NONE); lblPassword.setBounds(125, 144, 55, 15); lblPassword.setText("Password"); userNameTxt = new Text(shlLogin, SWT.BORDER); userNameTxt.setBounds(206, 109, 173, 21); passwordTxt = new Text(shlLogin, SWT.BORDER | SWT.PASSWORD); passwordTxt.setBounds(206, 144, 173, 21); Button btnLogin = new Button(shlLogin, SWT.NONE); btnLogin.setBounds(206, 185, 75, 25); btnLogin.setText("Login"); btnLogin.addListener(SWT.Selection, new Listener() < public void handleEvent(Event event) < userName = userNameTxt.getText(); password = passwordTxt.getText(); if (userName == null || userName.isEmpty() || password == null || password.isEmpty()) < String errorMsg = null; MessageBox messageBox = new MessageBox(shlLogin, SWT.OK | SWT.ICON_ERROR); messageBox.setText("Alert"); if (userName == null || userName.isEmpty()) < errorMsg = "Please enter username"; >else if (password == null || password.isEmpty()) < errorMsg = "Please enter password"; >if (errorMsg != null) < messageBox.setMessage(errorMsg); messageBox.open(); >> else < MessageBox messageBox = new MessageBox(shlLogin, SWT.OK | SWT.ICON_WORKING); messageBox.setText("Info"); messageBox.setMessage("Valid"); messageBox.open(); >> >); > >
11. Conclusion
From this example, we learned how quickly a Java GUI application can be developed using Eclipse Window Builder. WindowBuilder Engine provides a rich API for creating UI designers. It supports Java-based UI frameworks such as Swing, SWT/RCP, eRCP, GWT etc. It also supports XML-based UI frameworks like XWT, GWT UiBinder, Android etc.
12. Download the Code Project
This was a Tutorial about Eclipse Window Builder for GUI Creation.
Java Eclipse пример оконного приложения — создание окна, задание размеров, добавление надписей и кнопок, вывод сообщения
Далее пример урока 8 по программированию на Java.
Это пример содержит 5 классов (в проекте вам надо будет создать пять классов), предварительно создав два пакета пакета.
пакет TestForm
Этот пакет содержит два класса.
класс FormStart (создаёт «рамку», задаёт её размеры и запрашивает холст):
//IT FOR FREE //fkn.ktu10.com; Онлайн-встречи IFF каждый понедельник в 20-20 по мск //(можно задавать вопросы на сайте или онлайн-встречах) package TestForm; import javax.swing.JFrame; import javax.swing.JLabel; public class FormStart < public static void main(String[] args) < JFrame.setDefaultLookAndFeelDecorated(true); // устанавливае стандартный внешний вид JFrame frame = new JFrame("Здесь заголовок окна"); // желаемый заголовок //Далее создаём поверхность (панель) для размещения компонентов MainFormAppearance demo = new MainFormAppearance(); // внешность формы frame.setContentPane(demo.createContentPane()); // передаем как параметр в коструктор // задаём операцию, которая выполниться при закрытии frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 300); // задаём размер окна frame.setVisible(true); // форма будет видимой >/* youtube.com/toybattle */ >
класс MainFormAppearance ( в одном своём методе задаёт внешность холста и возвращает ссылку на холст):
package TestForm; import TestActions.*; import javax.swing.*; // импортируем SWING import java.awt.*; // импортируем все подпакеты AWT import java.awt.event.ActionListener; // Класс. который будет описывать внешний вид нашей формы public class MainFormAppearance < public JPanel createContentPane ()< // We create a bottom JPanel to place everything on. // сначала создаётся "панель", на которой и размещаюся // остальные компоненты JPanel totalGUI = new JPanel(); // создаём "поверхность" totalGUI.setLayout(null); // Создадим ярлык (надпись) синего цвета JLabel blueLabel = new JLabel("Какая-то надпись =)"); blueLabel.setLocation(10, 10); /* надпись синего цвета*/ blueLabel.setSize(300, 100); // размер области надписи blueLabel.setHorizontalAlignment(0); blueLabel.setForeground(Color.blue); // задаём цвет totalGUI.add(blueLabel); // добавляем текстовую метку на поверхность // Создаём кнопку--------------- JButton redButton = new JButton("Название кнопки 1 :))"); redButton.setLocation(120, 200); // расположение кнопки redButton.setSize(200,50 ); // размер кнопки // создаём объект-обработчик события ActionListener actionListener = new TestActionListener(); // создаём создаём действие // назначаем этот обработчик кнопке redButton.addActionListener(actionListener);// прикрепляем действие к кнопке (срабоет по нажатии на неё) totalGUI.add(redButton); // добавляем кнопку на поверхность // Создадим ещё одну кнопку------------------------- JButton ParceButton = new JButton("Кнопка 2!"); ParceButton.setLocation(200, 100); // расположение кнопки ParceButton.setSize(100, 30 ); // размер кнопки ActionListener ParceListener = new ParceListener(); // создаём создаём действие ParceButton.addActionListener(ParceListener); // прикрепляем действие к кнопке totalGUI.add(ParceButton); // добавляем на поверхность // 3-я кнопка--------------------------------------- JButton Button3 = new JButton("Кнопка 3"); Button3.setLocation(200, 150); // местоположение Button3.setSize(150, 30); // размер ActionListener CListener = new CsvListener(); // создаём создаём действие типа CsvListener Button3.addActionListener(CListener); // прикрепляем действие к кнопке типа CsvListener к кнопке 3 totalGUI.add(Button3); totalGUI.setOpaque(true); return totalGUI; // возвращаем внешний вид >>
В этом пакете будут расположены 3 класса-действия (действий), которые мы будем «прикреплять» к создаваемым кнопкам (см. класс выше MainFormAppearance)
Класс CsvListener:
package TestActions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JOptionPane; // действие для кнопки 3 public class CsvListener implements ActionListener < public void actionPerformed(ActionEvent e) < // нет реализации (никаких действий) //System.exit(1); // если раскомментировать, то будет закрывать программу >>
класс ParceListener:
package TestActions; import javax.swing.JFrame; import javax.swing.JOptionPane; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ParceListener implements ActionListener < // реализация интерфейса public void actionPerformed(ActionEvent e) < // задаём текст для сообщения String message = "Кнопка 2 нажата=))"; // выполняем команду вывода сообщения JOptionPane.showMessageDialog(new JFrame(), message, "Message by 2", JOptionPane.ERROR_MESSAGE); >>
Класс TestActionListener:package TestActions; import javax.swing.JFrame; import javax.swing.JOptionPane; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class TestActionListener implements ActionListener < // наследуемся от стандартного класса ActionListener public void actionPerformed(ActionEvent e) < // выведем сообщение из нескольких строк // одну из них в кавычках String message = "\"строка 1\"\n" + "строка2\n" + "строка 3"; JOptionPane.showMessageDialog(new JFrame(), message, "Несколько строк", JOptionPane.ERROR_MESSAGE); >>
Key Words for FKN + antitotal forum (CS VSU):
Hello world, jFrame и Java
Для создания воспользуемся средой Eclipse.
Естественно для работы вам необходимы расширения eclipse для Java ( eclipse-jdt или как его обозвали в вашей системе ) .
Сейчас мы создадим вот такое окошко:У меня Gnome 3. Не пугайтесь окна будут выглядит согласно вашей теме.
Создайте новый Java проект в Eclipse. Подробнее об этом тут.
Создаём новый класс. Я назвал его TestFrame.
Когда всё готово, подымитесь выше в коде и внесите такие строки:import java.awt.Dimension; //для задания размера окна import javax.swing.JFrame; //для использования JFrame import javax.swing.JLabel; //для создания текстовой метки
Теперь перейдите внутрь класса и создайте метод createGUI() :
public static void createGUI() < JFrame frame = new JFrame("JFrame howto"); //новый экземпляр JFrame. Параметр - заголовок окна frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //указываем что после клика по кнопке закрытия - завершаем работу JLabel label = new JLabel("how2.org.ua"); //текстовая метка frame.getContentPane().add(label); //добавляем метку в окно frame.setPreferredSize(new Dimension(200, 100)); //задаём размер окна frame.pack(); // "разворачивает" окно таким образом, чтобы оно приняло необходимый размер frame.setVisible(true); //показываем окно >
Теперь необходимо создать «функцию», которая выполнит этот метод. Это будет метод main:
public static void main(String[] args)