Как создать окно в java

от admin

Live guide по созданию приложения на Java

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

Примерно в это же время у меня возникла идея создать свое приложение для организации своего времени: условный прототип ежедневника. Да, довольно простенькая идея, но все же. Тогда у меня так и не дошли руки до написания программы. Зато дошли сейчас.

Так вот. Для написания этого самого приложения я решил изучить язык Java. Несмотря на то, что у меня к нему есть некое предубеждение (когда-то давно я начинал его учить и мне показалось, что в нем слишком длинные и непонятные названия методов, да и вообще все сложно), потребность в кроссплатформенности (почему бы приложение не запускать еще и на ПК без лишних приседаний?) вернула меня на путь изучения Java.

Для чего я все это пишу? Хочу делиться своим путем, своими ошибками, своим ходом мыслей в процессе создания приложения. Возможно, кому-то это поможет, кто-то в комментариях поделится чем-то интересным на этот счет, да и в процессе формулирования мыслей пройденное усвоится лучше).

С чего начать?

Лично мне очень тяжело было изучать C++ по книгам. Во многом потому, что я получал большой объем теории, но почти никак не подкреплял это написанием программ. Во многом потому, что просто не понимал, где это все мне может пригодиться. В результате куча времени была потрачена, а большая часть инфы в голове так и не засела.

Поэтому я решил немного поменять подход. Теперь я руководствуюсь четырьмя пунктами:

  1. Формулируем цели и понимаем, что нужно на начальном этапе.
    Например, я хочу написать программу-ежедневник. Я хочу, чтобы у меня была полноценное приложение с графикой, а не просто консольное нечто, поэтому мне точно понадобятся всякие окна, панели, кнопки и т.д.
  2. Продвигаемся к цели методом проб и ошибок. Например, я хочу создать окно. Ищу в интернете необходимую библиотеку, подключаю ее, создаю это окно.
    После этого вспоминаем работу с окнами в Windows/Linux и пытаемся сделать это через код. Условно, установить определенный размер и запретить его изменение.
  3. Включаем свою любознательность. Пытаемся переставлять строки местами, менять параметры и запускать после этого программу, подмечать, что поменялось
  4. Пишем комментарии к коду. Вот прям обязательно. Долгое время сам не использовал комментарии, но с ними гораздо удобнее: можно сэкономить много времени, не спрашивая «что здесь вообще происходит», ну и просто немного разгрузить мозг, освободив его «оперативку», записав мысль словами

Первый шаг — Окна

Начать я решил именно с графики, а не с написания алгоритмов. Не знаю, насколько это практично, но меня к ней очень тянет.

Тем не менее, еще до того, как я дошел до окон, у меня возник вопрос: можно ли создавать несколько классов внутри одного файла? Не по принципу матрешки (класс в главном классе).
Оказалось, что да.

Основной класс, в котором также содержится main, должен иметь такое же название, как и имя файла. Насколько я понимаю, обычно приложение состоит из многих файлов, поэтому основной класс должен быть открыт для доступа из других фалов, то есть иметь тип public. Остальные же классы создаются без public и private перед ключевым словом class и доступны они только в том файле, в котором их объявили.

Так вот, можно, наконец, перейти к окнам.

Окно в Java обозначается как JFrame. Если переводить на русский, то получится что-то типа «java — окно». Находится окно в библиотеке javax.swing.

Код по созданию нового окна выглядит примерно так:

Что мне очень нравится в Java, так это понятные названия методов. Например, догадайтесь, что делают следующие методы?:

А вот тот же код с пояснениями:

На сегодня это все. Получилось не так много, но, надеюсь, информативно.

How to Make Frames (Main Windows)

A Frame is a top-level window with a title and a border. The size of the frame includes any area designated for the border. The dimensions of the border area may be obtained using the getInsets method. Since the border area is included in the overall size of the frame, the border effectively obscures a portion of the frame, constraining the area available for rendering and/or displaying subcomponents to the rectangle which has an upper-left corner location of (insets.left , insets.top) , and has a size of width — (insets.left + insets.right) by height — (insets.top + insets.bottom) .

A frame, implemented as an instance of the JFrame class, is a window that has decorations such as a border, a title, and supports button components that close or iconify the window. Applications with a GUI usually include at least one frame. Applets sometimes use frames, as well.

To make a window that is dependent on another window — disappearing when the other window is iconified, for example — use a dialog instead of frame. . To make a window that appears within another window, use an internal frame.

Creating and Showing Frames

Here is a picture of the extremely plain window created by the FrameDemo demonstration application. You can find the source code in FrameDemo.java . You can run FrameDemo ( download JDK 7 or later).

The following FrameDemo code shows how to create and set up a frame.

Here are some details about the code:

    setDefaultLookAndFeelDecorated(true) requests that any subsequently created frames have window decorations provided by the look and feel, and not by the window system. For details, see Specifying Window Decorations.

For frames that have menus, you'd typically add the menu bar to the frame here using the setJMenuBar method. See How to Use Menus for details.

This example does not set the frame location, but it is easy to do so using either the setLocationRelativeTo or setLocation method. For example, the following code centers a frame onscreen:

Specifying Window Decorations

By default, window decorations are supplied by the native window system. However, you can request that the look-and-feel provide the decorations for a frame. You can also specify that the frame have no window decorations at all, a feature that can be used on its own, or to provide your own decorations, or with full-screen exclusive mode.

Besides specifying who provides the window decorations, you can also specify which icon is used to represent the window. Exactly how this icon is used depends on the window system or look and feel that provides the window decorations. If the window system supports minimization, then the icon is used to represent the minimized window. Most window systems or look and feels also display the icon in the window decorations. A typical icon size is 16×16 pixels, but some window systems use other sizes.

The following snapshots show three frames that are identical except for their window decorations. As you can tell by the appearance of the button in each frame, all three use the Java look and feel. The first uses decorations provided by the window system, which happen to be Microsoft Windows, but could as easily be any other system running the Java platform.The second and third use window decorations provided by the Java look and feel. The third frame uses Java look and feel window decorations, but has a custom icon.

A frame with decorations provided by the window system A frame with decorations provided by the look and feel A frame with a custom icon
Window decorations provided by the look and feel Window decorations provided by the window system Custom icon; window decorations provided by the look and feel

Here is an example of creating a frame with a custom icon and with window decorations provided by the look and feel:

As the preceding code snippet implies, you must invoke the setDefaultLookAndFeelDecorated method before creating the frame whose decorations you wish to affect. The value you set with setDefaultLookAndFeelDecorated is used for all subsequently created JFrame s. You can switch back to using window system decorations by invoking JFrame.setDefaultLookAndFeelDecorated(false) . Some look and feels might not support window decorations; in this case, the window system decorations are used.

The full source code for the application that creates the frames pictured above is in FrameDemo2.java . Besides showing how to choose window decorations, FrameDemo2 also shows how to disable all window decorations and gives an example of positioning windows. It includes two methods that create the Image objects used as icons — one is loaded from a file, and the other is painted from scratch.

    Click the Launch button to run the Frame Demo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.

Responding to Window-Closing Events

By default, when the user closes a frame onscreen, the frame is hidden. Although invisible, the frame still exists and the program can make it visible again. If you want different behavior, then you need to either register a window listener that handles window-closing events, or you need to specify default close behavior using the setDefaultCloseOperation method. You can even do both.

The argument to setDefaultCloseOperation must be one of the following values, the first three of which are defined in the WindowConstants interface (implemented by JFrame , JInternalPane , and JDialog ):

DO_NOTHING_ON_CLOSE Do not do anything when the user requests that the window close. Instead, the program should probably use a window listener that performs some other action in its windowClosing method. HIDE_ON_CLOSE (the default for JDialog and JFrame ) Hide the window when the user closes it. This removes the window from the screen but leaves it displayable. DISPOSE_ON_CLOSE (the default for JInternalFrame ) Hide and dispose of the window when the user closes it. This removes the window from the screen and frees up any resources used by it. EXIT_ON_CLOSE (defined in the JFrame class) Exit the application, using System.exit(0) . This is recommended for applications only. If used within an applet, a SecurityException may be thrown.

DISPOSE_ON_CLOSE can have results similar to EXIT_ON_CLOSE if only one window is onscreen. More precisely, when the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate. See AWT Threading Issues for details.

The default close operation is executed after any window listeners handle the window-closing event. So, for example, assume that you specify that the default close operation is to dispose of a frame. You also implement a window listener that tests whether the frame is the last one visible and, if so, saves some data and exits the application. Under these conditions, when the user closes a frame, the window listener will be called first. If it does not exit the application, then the default close operation — disposing of the frame — will then be performed.

For more information about handling window-closing events, see How to Write Window Listeners. Besides handling window-closing events, window listeners can also react to other window state changes, such as iconification and activation.

The Frame API

The following tables list the commonly used JFrame constructors and methods. Other methods you might want to call are defined by the java.awt.Frame , java.awt.Window , and java.awt.Component classes, from which JFrame descends.

Because each JFrame object has a root pane, frames have support for interposing input and painting behavior in front of the frame children, placing children on different "layers", and for Swing menu bars. These topics are introduced in Using Top-Level Containers and explained in detail in How to Use Root Panes.

The API for using frames falls into these categories:

  • DO_NOTHING_ON_CLOSE
  • HIDE_ON_CLOSE
  • DISPOSE_ON_CLOSE
  • EXIT_ON_CLOSE

Examples that Use Frames

All of the standalone applications in this trail use JFrame . The following table lists a few and tells you where each is discussed.

Java/Первое окно

Так как в большинстве своем сегодняшние начинающие программисты не любят окно командной строки — приведу пример оконного приложения.

Содержание

Начнем с простого [ править ]

Вот у нас и получилось ничего не делающее приложение!

Делаем что-то полезное [ править ]

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

How to Make Dialogs

A Dialog window is an independent sub window meant to carry temporary notice apart from the main Swing Application Window. Most Dialogs present an error message or warning to a user, but Dialogs can present images, directory trees, or just about anything compatible with the main Swing Application that manages them.

For convenience, several Swing component classes can directly instantiate and display dialogs. To create simple, standard dialogs, you use the JOptionPane class. The ProgressMonitor class can put up a dialog that shows the progress of an operation. Two other classes, JColorChooser and JFileChooser , also supply standard dialogs. To bring up a print dialog, you can use the Printing API. To create a custom dialog, use the JDialog class directly.

Читать:
Почему принтер обрезает изображение при печати

The code for simple dialogs can be minimal. For example, here is an informational dialog:

An informational dialog requires minimal code

Here is the code that creates and shows it:

The rest of this section covers the following topics:

An Overview of Dialogs

Every dialog is dependent on a Frame component. When that Frame is destroyed, so are its dependent Dialogs. When the frame is iconified, its dependent Dialogs also disappear from the screen. When the frame is deiconified, its dependent Dialogs return to the screen. A swing JDialog class inherits this behavior from the AWT Dialog class.

A Dialog can be modal. When a modal Dialog is visible, it blocks user input to all other windows in the program. JOptionPane creates JDialog s that are modal. To create a non-modal Dialog, you must use the JDialog class directly.

Starting with JDK 7, you can modify dialog window modality behavior using the new Modality API. See The New Modality API for details.

The JDialog class is a subclass of the AWT java.awt.Dialog class. It adds a root pane container and support for a default close operation to the Dialog object . These are the same features that JFrame has, and using JDialog directly is very similar to using JFrame . If you're going to use JDialog directly, then you should understand the material in Using Top-Level Containers and How to Make Frames, especially Responding to Window-Closing Events.

Even when you use JOptionPane to implement a dialog, you're still using a JDialog behind the scenes. The reason is that JOptionPane is simply a container that can automatically create a JDialog and add itself to the JDialog 's content pane.

The DialogDemo Example

Here is a picture of an application that displays dialogs.

DialogDemo lets you bring up many kinds of dialogs

    Click the Launch button to run the Dialog Demo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.

JOptionPane Features

Using JOptionPane , you can quickly create and customize several different kinds of dialogs. JOptionPane provides support for laying out standard dialogs, providing icons, specifying the dialog title and text, and customizing the button text. Other features allow you to customize the components the dialog displays and specify where the dialog should appear onscreen. You can even specify that an option pane put itself into an internal frame ( JInternalFrame ) instead of a JDialog .

When you create a JOptionPane , look-and-feel-specific code adds components to the JOptionPane and determines the layout of those components.

JOptionPane 's icon support lets you easily specify which icon the dialog displays. You can use a custom icon, no icon at all, or any one of four standard JOptionPane icons (question, information, warning, and error). Each look and feel has its own versions of the four standard icons. The following figure shows the icons used in the Java (and Windows) look and feel.

Icons used by JOptionPane

Icon description Java look and feel Windows look and feel
question The Java look and feel icon for dialogs that ask questions The Windows look and feel icon for dialogs that ask questions
information The Java look and feel icon for informational dialogs The Windows look and feel icon for informational dialogs
warning The Java look and feel icon for warning dialogs The Windows look and feel icon for warning dialogs
error The Java look and feel icon for error dialogs The Windows look and feel icon for error dialogs

Creating and Showing Simple Dialogs

For most simple modal dialogs, you create and show the dialog using one of JOptionPane 's showXxxDialog methods. If your dialog should be an internal frame, then add Internal after show — for example, showMessageDialog changes to showInternalMessageDialog . If you need to control the dialog window-closing behavior or if you do not want the dialog to be modal, then you should directly instantiate JOptionPane and add it to a JDialog instance. Then invoke setVisible(true) on the JDialog to make it appear.

The two most useful showXxxDialog methods are showMessageDialog and showOptionDialog . The showMessageDialog method displays a simple, one-button dialog. The showOptionDialog method displays a customized dialog — it can display a variety of buttons with customized button text, and can contain a standard text message or a collection of components.

The other two showXxxDialog methods are used less often. The showConfirmDialog method asks the user to confirm something, but presents standard button text (Yes/No or the localized equivalent, for example) rather than button text customized to the user situation (Start/Cancel, for example). A fourth method, showInputDialog , is designed to display a modal dialog that gets a string from the user, using either a text field, an uneditable combo box or a list.

Here are some examples, taken from DialogDemo.java , of using showMessageDialog , showOptionDialog , and the JOptionPane constructor. For more example code, see DialogDemo.java and the other programs listed in Examples that Use Dialogs.

The arguments to all of the showXxxDialog methods and JOptionPane constructors are standardized, though the number of arguments for each method and constructor varies. The following list describes each argument. To see the exact list of arguments for a particular method, see The Dialog API.

Component parentComponent The first argument to each showXxxDialog method is always the parent component, which must be a Frame, a component inside a Frame, or null. If you specify a Frame or Dialog, then the Dialog will appear over the center of the Frame and follow the focus behavior of that Frame. If you specify a component inside a Frame, then the Dialog will appear over the center of that component and will follow the focus behavior of that component's Frame. If you specify null, then the look and feel will pick an appropriate position for the dialog — generally the center of the screen — and the Dialog will not necessarily follow the focus behavior of any visible Frame or Dialog.

The JOptionPane constructors do not include this argument. Instead, you specify the parent frame when you create the JDialog that contains the JOptionPane , and you use the JDialog setLocationRelativeTo method to set the dialog position.

Object message This required argument specifies what the dialog should display in its main area. Generally, you specify a string, which results in the dialog displaying a label with the specified text. You can split the message over several lines by putting newline ( \n ) characters inside the message string. For example:

You can either let the option pane display its default icon or specify the icon using the message type or icon argument. By default, an option pane created with showMessageDialog displays the information icon, one created with showConfirmDialog or showInputDialog displays the question icon, and one created with a JOptionPane constructor displays no icon. To specify that the dialog display a standard icon or no icon, specify the message type corresponding to the icon you desire. To specify a custom icon, use the icon argument. The icon argument takes precedence over the message type; as long as the icon argument has a non-null value, the dialog displays the specified icon.

Customizing Button Text

When you use JOptionPane to create a dialog, you can either use the standard button text (which might vary by look and feel and locale) or specify different text. By default, the option pane type determines how many buttons appear. For example, YES_NO_OPTION dialogs have two buttons, and YES_NO_CANCEL_OPTION dialogs have three buttons.

The following code, taken from DialogDemo.java , creates two Yes/No dialogs. The first dialog is implemented with showConfirmDialog , which uses the look-and-feel wording for the two buttons. The second dialog uses showOptionDialog so it can customize the wording. With the exception of wording changes, the dialogs are identical.

As the previous code snippets showed, the showMessageDialog , showConfirmDialog , and showOptionDialog methods return an integer indicating the user's choice. The values for this integer are YES_OPTION , NO_OPTION , CANCEL_OPTION , OK_OPTION , and CLOSED_OPTION . Except for CLOSED_OPTION , each option corresponds to the button the user pressed. When CLOSED_OPTION is returned, it indicates that the user closed the dialog window explicitly, rather than by choosing a button inside the option pane.

Even if you change the strings that the standard dialog buttons display, the return value is still one of the pre-defined integers. For example, a YES_NO_OPTION dialog always returns one of the following values: YES_OPTION , NO_OPTION , or CLOSED_OPTION .

Getting the User's Input from a Dialog

The only form of showXxxDialog that does not return an integer is showInputDialog , which returns an Object instead. This Object is generally a String reflecting the user's choice. Here is an example of using showInputDialog to create a dialog that lets the user choose one of three strings:

An input dialog with a combo box

If you do not care to limit the user's choices, you can either use a form of the showInputDialog method that takes fewer arguments or specify null for the array of objects. In the Java look and feel, substituting null for possibilities results in a dialog that has a text field and looks like this:

An input dialog with a text field

Because the user can type anything into the text field, you might want to check the returned value and ask the user to try again if it is invalid. Another approach is to create a custom dialog that validates the user-entered data before it returns. See CustomDialog.java for an example of validating data.

If you're designing a custom dialog, you need to design your dialog's API so that you can query the dialog about what the user chose. For example, CustomDialog has a getValidatedText method that returns the text the user entered.

Stopping Automatic Dialog Closing

By default, when the user clicks a JOptionPane -created button, the dialog closes. But what if you want to check the user's answer before closing the dialog? In this case, you must implement your own property change listener so that when the user clicks a button, the dialog does not automatically close.

DialogDemo contains two dialogs that implement a property change listener. One of these dialogs is a custom modal dialog, implemented in CustomDialog , that uses JOptionPane both to get the standard icon and to get layout assistance. The other dialog, whose code is below, uses a standard Yes/No JOptionPane . Though this dialog is rather useless as written, its code is simple enough that you can use it as a template for more complex dialogs.

Besides setting the property change listener, the following code also calls the JDialog 's setDefaultCloseOperation method and implements a window listener that handles the window close attempt properly. If you do not care to be notified when the user closes the window explicitly, then ignore the bold code.

The Dialog API

The following tables list the commonly used JOptionPane and JDialog constructors and methods. Other methods you're likely to call are defined by the Dialog , Window and Component classes and include pack , setSize , and setVisible .

The API is listed as follows:

Frequently Used JDialog Constructors and Methods

Method or Constructor Purpose
JDialog()
JDialog(Dialog)
JDialog(Dialog, boolean)
JDialog(Dialog, String)
JDialog(Dialog, String, boolean)
JDialog(Dialog, String, boolean, GraphicsConfiguration)
JDialog(Frame)
JDialog(Frame, boolean)
JDialog(Frame, String)
JDialog(Frame, String, boolean)
JDialog(Frame, String, boolean, GraphicsConfiguration)
JDialog(Window owner)
JDialog(Window owner, Dialog.ModalityType modalityType)
JDialog(Window owner, String title)
JDialog(Window owner, String title, Dialog.ModalityType modalityType)
JDialog(Window owner, String title, Dialog.ModalityType modalityType, GraphicsConfiguration gc)
Creates a JDialog instance. The Frame argument, if any, is the frame (usually a JFrame object) that the dialog depends on. Make the boolean argument true to specify a modal dialog, false or absent to specify a non-modal dialog. You can also specify the title of the dialog, using a string argument.
void setContentPane(Container)
Container getContentPane()
Get and set the content pane, which is usually the container of all the dialog's components. See Using Top-Level Containers for more information.
void setDefaultCloseOperation(int)
int getDefaultCloseOperation()
Get and set what happens when the user tries to close the dialog. Possible values: DISPOSE_ON_CLOSE , DO_NOTHING_ON_CLOSE , HIDE_ON_CLOSE (the default). See Responding to Window-Closing Events for more information.
void setLocationRelativeTo(Component) Centers the dialog over the specified component.
static void setDefaultLookAndFeelDecorated(boolean)
static boolean isDefaultLookAndFeelDecorated()
Set or get a hint as to whether the dialog's window decorations (such as borders, or widgets to close the window) should be provided by the current look and feel. Otherwise the dialog's decorations will be provided by the current window manager. See Specifying Window Decorations for more information.

Examples that Use Dialogs

This table lists examples that use JOptionPane or JDialog . To find other examples that use dialogs, see the example lists for progress bars, color choosers, and file choosers.

Похожие статьи