Как сделать кнопку в java

от admin

How to Use Buttons, Check Boxes, and Radio Buttons

To create a button, you can instantiate one of the many classes that descend from the AbstractButton class. The following table shows the Swing-defined AbstractButton subclasses that you might want to use:

Class Summary Where Described
JButton A common button. How to Use the Common Button API and How to Use JButton Features
JCheckBox A check box button. How to Use Check Boxes
JRadioButton One of a group of radio buttons. How to Use Radio Buttons
JMenuItem An item in a menu. How to Use Menus
JCheckBoxMenuItem A menu item that has a check box. How to Use Menus and How to Use Check Boxes
JRadioButtonMenuItem A menu item that has a radio button. How to Use Menus and How to Use Radio Buttons
JToggleButton Implements toggle functionality inherited by JCheckBox and JRadioButton . Can be instantiated or subclassed to create two-state buttons. Used in some examples

First, this section explains the basic button API that AbstractButton defines — and thus all Swing buttons have in common. Next, it describes the small amount of API that JButton adds to AbstractButton . After that, this section shows you how to use specialized API to implement check boxes and radio buttons.

How to Use the Common Button API

Here is a picture of an application that displays three buttons:

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

As the ButtonDemo example shows, a Swing button can display both text and an image. In ButtonDemo , each button has its text in a different place, relative to its image. The underlined letter in each button's text shows the mnemonic — the keyboard alternative — for each button. In most look and feels, the user can click a button by pressing the Alt key and the mnemonic. For example, Alt-M would click the Middle button in ButtonDemo.

When a button is disabled, the look and feel automatically generates the button's disabled appearance. However, you could provide an image to be substituted for the normal image. For example, you could provide gray versions of the images used in the left and right buttons.

How you implement event handling depends on the type of button you use and how you use it. Generally, you implement an action listener, which is notified every time the user clicks the button. For check boxes you usually use an item listener, which is notified when the check box is selected or deselected.

Below is the code from ButtonDemo.java that creates the buttons in the previous example and reacts to button clicks. The bold code is the code that would remain if the buttons had no images.

How to Use JButton Features

Ordinary buttons — JButton objects — have just a bit more functionality than the AbstractButton class provides: You can make a JButton be the default button.

At most one button in a top-level container can be the default button. The default button typically has a highlighted appearance and acts clicked whenever the top-level container has the keyboard focus and the user presses the Return or Enter key. Here is a picture of a dialog, implemented in the ListDialog example, in which the Set button is the default button:

You set the default button by invoking the setDefaultButton method on a top-level container's root pane. Here is the code that sets up the default button for the ListDialog example:

The exact implementation of the default button feature depends on the look and feel. For example, in the Windows look and feel, the default button changes to whichever button has the focus, so that pressing Enter clicks the focused button. When no button has the focus, the button you originally specified as the default button becomes the default button again.

How to Use Check Boxes

The JCheckBox class provides support for check box buttons. You can also put check boxes in menus, using the JCheckBoxMenuItem class. Because JCheckBox and JCheckBoxMenuItem inherit from AbstractButton , Swing check boxes have all the usual button characteristics, as discussed earlier in this section. For example, you can specify images to be used in check boxes.

Check boxes are similar to radio buttons but their selection model is different, by convention. Any number of check boxes in a group — none, some, or all — can be selected. A group of radio buttons, on the other hand, can have only one button selected.

Here is a picture of an application that uses four check boxes to customize a cartoon:

NOT a tutorial reader!

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

A check box generates one item event and one action event per click. Usually, you listen only for item events, since they let you determine whether the click selected or deselected the check box. Below is the code from CheckBoxDemo.java that creates the check boxes in the previous example and reacts to clicks.

How to Use Radio Buttons

Radio buttons are groups of buttons in which, by convention, only one button at a time can be selected. The Swing release supports radio buttons with the JRadioButton and ButtonGroup classes. To put a radio button in a menu, use the JRadioButtonMenuItem class. Other ways of displaying one-of-many choices are combo boxes and lists. Radio buttons look similar to check boxes, but, by convention, check boxes place no limits on how many items can be selected at a time.

Because JRadioButton inherits from AbstractButton , Swing radio buttons have all the usual button characteristics, as discussed earlier in this section. For example, you can specify the image displayed in a radio button.

Here is a picture of an application that uses five radio buttons to let you choose which kind of pet is displayed:

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

Each time the user clicks a radio button (even if it was already selected), the button fires an action event. One or two item events also occur — one from the button that was just selected, and another from the button that lost the selection (if any). Usually, you handle radio button clicks using an action listener.

Below is the code from RadioButtonDemo.java that creates the radio buttons in the previous example and reacts to clicks.

For each group of radio buttons, you need to create a ButtonGroup instance and add each radio button to it. The ButtonGroup takes care of deselecting the previously selected button when the user selects another button in the group.

You should generally initialize a group of radio buttons so that one is selected. However, the API doesn't enforce this rule — a group of radio buttons can have no initial selection. Once the user has made a selection, exactly one button is selected from then on.

The Button API

The following tables list the commonly used button-related API. Other methods you might call, such as setFont and setForeground , are listed in the API tables in The JComponent Class.

The API for using buttons falls into these categories:

Examples that Use Various Kinds of Buttons

The following examples use buttons. Also see Examples that Use Tool Bars, which lists programs that add JButton objects to JToolBar s.

Example Where Described Notes
ButtonDemo How to Use the Common Button API Uses mnemonics and icons. Specifies the button text position, relative to the button icon. Uses action commands.
ButtonHtmlDemo Using HTML in Swing Components A version of ButtonDemo that uses HTML formatting in its buttons.
ListDialog How to Use JButton Features Implements a dialog with two buttons, one of which is the default button.
DialogDemo How to Make Dialogs Has "Show it" buttons whose behavior is tied to the state of radio buttons. Uses sizable, though anonymous, inner classes to implement the action listeners.
ProgressBarDemo How to Monitor Progress Implements a button's action listener with a named inner class.
CheckBoxDemo How to Use Check Boxes Uses check box buttons to determine which of 16 images it should display.
ActionDemo How to Use Actions Uses check box menu items to set the state of the program.
RadioButtonDemo How to Use Radio Buttons Uses radio buttons to determine which of five images it should display.
DialogDemo How to Make Dialogs Contains several sets of radio buttons, which it uses to determine which dialog to bring up.
MenuDemo How to Use Menus Contains radio button menu items and check box menu items.
ColorChooserDemo2 How to Use Color Choosers The crayons in CrayonPanel are implemented as toggle buttons.
ScrollDemo How to Use Scroll Panes The cm button is a toggle button.

You can learn more about JavaFX button components from the following documents:

4.1: Buttons and clickable images

The user interface (UI) that appears on a screen of an Android-powered device consists of a hierarchy of objects called views. Every element of the screen is a view.

The View class represents the basic building block for all UI components. View is the base class for classes that provide interactive UI components, such as Button elements. Users tap these elements on a touchscreen or click them using a pointing device. Any element that users tap or click to perform an action is called a clickable element.

For an Android app, user interaction typically involves tapping, typing, using gestures, or talking. The Android framework provides corresponding user interface (UI) elements such as buttons, clickable images, menus, keyboards, text entry fields, and a microphone.

When designing an interactive app, make sure your app is intuitive; that is, your app should perform as your users expect it to perform. For example, when you rent a car, you expect the steering wheel, gear shift, headlights, and indicators to be in a certain place. Another example is that when you first enter a room, you expect the light switch to be in a certain place. Similarly, when a user starts an app, the user expects buttons and images to be clickable. Don't violate established expectations, or you'll make it harder for your users to use your app.

In this chapter you learn how to create buttons and clickable images for triggering actions.

Designing buttons

People like to press buttons. Show someone a big red button with a message that says "Do not press" and the person will probably press the button, just for the pleasure of pressing a big red button. (That the button is forbidden is also a factor.)

You use the Button class to make a button for an Android app. Buttons can have the following design:

  • Text only, as shown on the left side of the figure below.
  • Icon only, as shown in the center of the figure below.
  • Both text and an icon, as shown on the right side of the figure below.

When the user touches or clicks a button, the button performs an action. The button's text or icon should provide a hint about what that action will be. (Buttons are sometimes called "push-buttons" in Android documentation.)

A button is usually a rectangle or rounded rectangle with a descriptive caption or icon in its center. Android Button elements follow the guidelines in the Android Material Design specification. (You learn more about Material Design in another lesson.)

Android offers several types of Button elements, including raised buttons and flat buttons as shown in the figure below. Each button has three states: normal, disabled, and pressed.

In the figure above:

  1. Raised button in three states: normal, disabled, and pressed
  2. Flat button in three states: normal, disabled, and pressed

Designing raised buttons

A raised button is an outlined rectangle or rounded rectangle that appears lifted from the screen—the shading around it indicates that it is possible to tap or click it. The raised button can show text, an icon, or both.

To use raised buttons that conform to the Material Design specification, follow these steps:

If your build.gradle (Module: app) file doesn't include the android.support:appcompat-v7 library, add it to the dependencies section:

In the snippet above, 26.1.0 is the version number. If the version number you specified is lower than the currently available library version number, Android Studio will warn you ("a newer version is available"). Update the version number to the one Android Studio tells you to use.

Make your Activity extend android.support.v7.app.AppCompatActivity :

In the figure above:

  1. Normal state: A raised Button .
  2. Disabled state: When disabled, the Button is dimmed out and not active in the app's context. In most cases you would hide an inactive Button , but there may be times when you would want to show it as disabled.
  3. Pressed state: The pressed state, with a larger background shadow, indicates that the Button is being touched or clicked. When you attach a callback to the Button (such as the android:onClick attribute), the callback is called when the Button is in this state.
Creating a raised button with text

Some raised Button elements are best designed as text, without an icon, such as a Save button, because an icon by itself might not convey an obvious meaning. The Button class extends the TextView class. To use it, add it to the XML layout:

The best practice with a text Button is to define a very short word as a string resource ( button_text in the example above), so that the string can be translated. For example, Save could be translated into French as Enregistrer without changing any of the code.

Creating a raised button with an icon and text

While a Button usually displays text that tells the user what the action is, a raised Button can also display an icon along with text.

Choosing an icon

To choose images of a standard icon that are resized for different displays, follow these steps:

  1. Expand app > res in the Project > Android pane, and right-click (or Command-click) the drawable folder.
  2. Choose New > Image Asset. The Configure Image Asset dialog appears.
  3. Choose Action Bar and Tab Icons in the drop-down menu. (For a complete description of this dialog, see Create app icons with Image Asset Studio.)

Click the Clipart: image (the Android logo) to select a clip art image as the icon. A page of icons appears as shown below. Click the icon you want to use.

Optional: Choose HOLO_DARK from the Theme drop-down menu to set the icon to be white against a dark-colored or black background.

Vector images of a standard icon are automatically resized for different sizes of device displays. To choose vector images, follow these steps:

  1. Expand app > res in the Project > Android pane, and right-click (or Command-click) the drawable folder.
  2. Choose New > Vector Asset for an icon that automatically resizes itself for each display.
  3. The Vector Asset Studio dialog appears for a vector asset. Click the Material Icon radio button, and then click the Choose button to choose an icon from the Material Design specification. (For a complete description of this dialog, see Add Multi-Density Vector Graphics.)
  4. Click Next after choosing an icon, and click Finish to finish. The icon name should now appear in the app > res > drawable folder.
Adding the button with text and icon to the layout

To create a button with text and an icon as shown in the figure below, use a Button in your XML layout. Add the android:drawableLeft attribute to draw the icon to the left of the button's text, as shown in the figure below:

Creating a raised button with only an icon

If the icon is universally understood, you may want to use it instead of text.

To create a raised button with just an icon or image (no text), use the ImageButton class, which extends the ImageView class. You can add an ImageButton to your XML layout as follows:

Changing the style and appearance of raised buttons

The simplest way to show a more prominent raised button is to use a different background color for the button. You can specify the android:background attribute with a drawable or color resource:

The appearance of your button—the background color and font—may vary from one device to another, because devices by different manufacturers often have different default styles for input controls. You can control exactly how your buttons and other input controls are styled using a theme that you apply to your entire app.

For instance, to ensure that all devices that can run the Holo theme will use the Holo theme for your app, declare the following in the <application> element of the AndroidManifest.xml file:

After adding the declaration above, the app will be displayed using the theme.

Apps designed for Android 4.0 and higher can also use the DeviceDefault public theme family. DeviceDefault themes are aliases for the device's native look and feel. The DeviceDefault theme family and widget style family offer ways for developers to target the device's native theme with all customizations intact.

For Android apps running on 4.0 and newer, you have the following options:

  • Use a theme, such as one of the Holo themes, so that your app has the exact same look across all Android-powered devices running 4.0 or newer. In this case, the app's look does not change when running on a device with a different default skin or custom skin.
  • Use one of the DeviceDefault themes so that your app takes on the look of the device's default skin.
  • Don't use a theme, but you may have unpredictable results on some devices.
  • If you're not familiar with Android's style and theme system, you should read Styles and themes.
  • For information about using the Holo theme while supporting older devices, see the blog post Holo Everywhere.
  • For a guide on styling and customizing buttons using XML, see Buttons in the Android developer documentation.
  • For a comprehensive guide to designing buttons, see Buttons in the Material Design specification.

Designing flat buttons

A flat button, also known as a text button or borderless button, is a text-only button that looks flat and doesn't have a shadow. The major benefit of flat buttons is simplicity: a flat button doesn't distract the user from the main content as much as a raised button does. Flat buttons are useful for dialogs that require user interaction, as shown in the figure below. In this case, you want the button to use the same font and style as the surrounding text to keep the look and feel consistent across all the elements in the dialog.

Flat buttons have no borders or background, but they do change their appearance when they change to different states.

In the figure above:

  1. Normal state: In its normal state, the button looks just like ordinary text.
  2. Disabled state: When the text is dimmed out, the button is not active in the app's context.
  3. Pressed state: A background shadow indicates that the button is being tapped or clicked. When you attach a callback (such as the android:onClick attribute) to the button, the callback is called when the button is in this state.

To create a flat button, use the Button class. Add a Button to your XML layout, and apply "?android:attr/borderlessButtonStyle" as the style attribute:

Responding to button-click events

An event listener is an interface in the View class that contains a single callback method. The Android system calls the method when the user triggers the View to which the listener is registered.

To respond to a user tapping or clicking a button, use the event listener called OnClickListener , which contains one method, onClick() . To provide functionality when the user clicks, you implement this onClick() method.

For more about event listeners and other UI events, see Input events overview in the Android developer documentation.

Adding onClick() to the layout element

A quick way to set up an OnClickListener for a clickable element in your Activity code and assign a callback method is to add the android:onClick attribute to the element in the XML layout.

For example, a Button in the layout would include the android:onClick attribute:

When a user clicks the Button , the Android framework calls the sendMessage() method in the Activity :

The callback method for the android:onClick attribute must be public , return void , and define a View as its only parameter (this is the View that was tapped). Use the method to perform a task or call other methods as a response to the Button tap.

Using the button-listener design pattern

You can also handle the click event in your Java code using the button-listener design pattern, shown in the figure below. For more information on the "listener" design pattern, see Creating Custom Listeners.

Use the event listener View.OnClickListener , which is an interface in the View class that contains a single callback method, onClick() . The method is called by the Android framework when the view is triggered by user interaction.

The event listener must already be registered to the View in order to be called for the event. Follow these steps to register the listener and use it (refer to the figure below the steps):

  1. Use the findViewById() method of the View class to find the Button in the XML layout file:
  2. Get a new View.OnClickListener and register it to the Button by calling the setOnClickListener() method. The argument to setOnClickListener() takes an object that implements the View.OnClickListener interface, which has one method: onClick() .
  3. Override the onClick() method:
  4. Do something in response to the button click, such as perform an action.

Using the event listener interface for other events

Other events can occur with UI elements, and you can use the callback methods already defined in the event listener interfaces to handle them. The methods are called by the Android framework when the view—to which the listener has been registered—is triggered by user interaction. You therefore must set the appropriate listener to use the method. The following are some of the listeners available in the Android framework and the callback methods associated with each one:

  • onClick() from View.OnClickListener : Handles a click event in which the user touches and then releases an area of the device display occupied by a View . The onClick() callback has no return value.
  • onLongClick() from View.OnLongClickListener : Handles an event in which the user maintains touch on a View for an extended period. This method returns a boolean to indicate whether you have consumed the event, and the event should not be carried further. That is, return true to indicate that you have handled the event and the event should stop here. Return false if you have not handled the event, or if the event should continue to any other listeners.
  • onTouch() from View.OnTouchListener : Handles any form of touch contact with the screen including individual or multiple touches and gesture motions, including a press, a release, or any movement gesture on the screen (within the bounds of the UI element). A MotionEvent is passed as an argument, which includes directional information, and it returns a boolean to indicate whether your listener consumes this event.
  • onFocusChange() from View.OnFocusChangeListener : Handles when focus moves away from the current View as the result of interaction with a trackball or navigation key.
  • onKey() from View.OnKeyListener : Handles when a key on a hardware device is pressed while a View has focus.

Using clickable images

You can turn any View , such as an ImageView , into a button by adding the android:onClick attribute in the XML layout. The image for the ImageView must already be stored in the drawable folder of your project.

For example, the following images in the drawable folder (icecream_circle.jpg, donut_circle.jpg, and froyo_circle.jpg) are defined for ImageView elements arranged in a LinearLayout :

Using a floating action button

A floating action button ( FloatingActionButton ), shown below as #1 in the figure below, is a circular button that appears to float above the layout.

You should use a floating action button only to represent the primary action for a screen. For example, the primary action for the Contacts app main screen is adding a contact, as shown in the figure above. A floating action button is the right choice if your app requires an action to be persistent and readily available on a screen. Only one floating action button is recommended per screen.

The floating action button uses the same type of icons that you would use for a button with an icon, or for actions in the app bar at the top of the screen. You can add an icon as described previously in "Choosing an icon for the button".

If you start your project or Activity with the Basic Activity template, Android Studio adds a floating action button to the layout file for the Activity . To create a floating action button yourself, use the FloatingActionButton class, which extends the ImageButton class. You can add a floating action button to your XML layout as follows:

  • Floating action buttons, by default, are 56 x 56 dp in size. It is best to use the default size unless you need the smaller version to create visual continuity with other screen elements.
  • You can set the mini size (30 x 40 dp) with the app:fabSize attribute: app:fabSize="mini"
  • To set it back to the default size (56 x 56 dp): app:fabSize="normal"

For more design instructions involving floating action buttons, see Components– Buttons: Floating Action Button in the Material Design Spec.

Recognizing gestures

A touch gesture occurs when a user places one or more fingers on the touchscreen, and your app interprets that pattern of touches as a particular gesture, such as a tap, touch & hold, double-tap, fling, or scroll.

Android provides a variety of classes and methods to help you create and detect gestures. Although your app should not depend on touch gestures for basic behaviors (because the gestures may not be available to all users in all contexts), adding touch-based interaction to your app can greatly increase its usefulness and appeal.

To provide users with a consistent, intuitive experience, your app should follow the accepted Android conventions for touch gestures. The Gestures design guide shows you how to design common gestures in Android apps. For more code samples and details, see Using touch gestures in the Android developer documentation.

Detecting common gestures

If your app uses common gestures such as double tap, long press, fling, and so on, you can take advantage of the GestureDetector class for detecting common gestures. Use GestureDetectorCompat , which is provided as a compatibility implementation of the framework's GestureDetector class which guarantees the newer focal point scrolling behavior from Jellybean MR1 on all platform versions. This class should be used only with motion events reported for touch devices—don't use it for trackball or other hardware events.

GestureDetectorCompat lets you detect common gestures without processing the individual touch events yourself. It detects various gestures and events using MotionEvent objects, which report movements by a finger (or mouse, pen, or trackball).

The following snippets show how you would use GestureDetectorCompat and the GestureDetector.SimpleOnGestureListener class.

Creating an instance of GestureDetectorCompat

To use GestureDetectorCompat , create an instance ( mDetector in the snippet below) of the GestureDetectorCompat class, using the onCreate() method in the Activity (such as MainActivity ):

When you instantiate a GestureDetectorCompat object, one of the parameters it takes is a class that you must create, which is MyGestureListener in the snippet above. The class you create should do one of the following:

  • Implement the GestureDetector.OnGestureListener interface to detect all standard gestures, or
  • Extend the GestureDetector.SimpleOnGestureListener class, which you can use to process only a few gestures by overriding the methods you need.

SimpleOnGestureListener provides methods such as onDown() , onLongPress() , onFling() , onScroll() , and onSingleTapUp() .

Extending GestureDetector.SimpleOnGestureListener

Create the class MyGestureListener as a separate Activity (MyGestureListener ) to extend GestureDetector.SimpleOnGestureListener . Override the onFling() and onDown() methods to show log statements about the event:

Intercepting touch events

To intercept touch events, override the onTouchEvent() callback of the GestureDetectorCompat class:

Detecting all gestures

To detect all types of gestures, you need to perform two essential steps:

  1. Gather data about touch events.
  2. Interpret the data to see if it meets the criteria for any of the gestures your app supports.

The gesture starts when the user first touches the screen, continues as the system tracks the position of the user's finger or fingers, and ends when the system captures the event of the user's fingers leaving the screen. Throughout this interaction, an object of the MotionEvent class is delivered to onTouchEvent() , providing the details. Your app can use the data provided by the MotionEvent to determine if a gesture it cares about happened.

For example, when the user first touches the screen, the onTouchEvent() method is triggered on the View that was touched, and a MotionEvent object reports movement by a finger (or mouse, pen, or trackball) in terms of:

  • An action code: Specifies the state change that occurred, such as a finger tapping down or lifting up.
  • A set of axis values: Describes the position in X and Y coordinates of the touch and information about the pressure, size and orientation of the contact area.

The individual fingers or other objects that generate movement traces are referred to as pointers. Some devices can report multiple movement traces at the same time. Multi-touch screens show one movement trace for each finger. Motion events contain information about all of the pointers that are currently active even if some of them have not moved since the last event was delivered. Based on the interpretation of the MotionEvent object, the onTouchEvent() method triggers the appropriate callback on the GestureDetector.OnGestureListener interface.

Each MotionEvent pointer has a unique id that is assigned when it first goes down (indicated by ACTION_DOWN or ACTION_POINTER_DOWN) . A pointer id remains valid until the pointer eventually goes up (indicated by ACTION_UP or ACTION_POINTER_UP ) or when the gesture is canceled (indicated by ACTION_CANCEL ). The MotionEvent class provides methods to query the position and other properties of pointers, such as getX(int) , getY(int) , getAxisValue(int) , getPointerId(int) , and getToolType(int) .

The interpretation of the contents of a MotionEvent varies significantly depending on the source class of the device. On touchscreens, the pointer coordinates specify absolute positions such as view X/Y coordinates. Each complete gesture is represented by a sequence of motion events with actions that describe pointer state transitions and movements.

A gesture starts with a motion event with ACTION_DOWN that provides the location of the first pointer down. As each additional pointer goes down or up, the framework generates a motion event with ACTION_POINTER_DOWN or ACTION_POINTER_UP accordingly. Pointer movements are described by motion events with ACTION_MOVE . A gesture ends when the final pointer goes up as represented by a motion event with ACTION_UP , or when the gesture is canceled with ACTION_CANCEL .

To intercept touch events in an Activity or View , override the onTouchEvent() callback as shown in the snippet below. You can use the getActionMasked() method of the MotionEventCompat class to extract the action the user performed from the event parameter. ( MotionEventCompat is a helper for accessing features in a MotionEvent , which was introduced after API level 4 in a backwards compatible fashion.) This gives you the raw data you need to determine if a gesture you care about occurred:

You can then do your own processing on these events to determine if a gesture occurred.

JavaFX Button руководство по работе с кнопками

Элемент управления JavaFX Button позволяет приложению выполнять некоторые действия, когда пользователь приложения нажимает кнопку. Элемент представлен классом javafx.scene.control.Button. Кнопка может иметь текст и значок, которые указывают пользователю, что будет делать нажатие кнопки.

Создание

Вы создаете элемент управления Button, создавая экземпляр класса Button:

Текст, отображаемый на кнопке, передается в качестве параметров конструктору Button.

Добавление в граф Scene

Чтобы кнопка была видимой, объект кнопки должен быть добавлен в граф Scene. Это означает добавление его к объекту Scene или как дочерний элемент макета, который присоединен к объекту Scene.

Вот пример, который присоединяет кнопку к графу сцены:

Обратите внимание, что кнопка добавляется непосредственно в объект Scene. Обычно вы вкладываете Button в какой-либо компонент макета.

Результатом выполнения приведенного выше примера кнопки является приложение, которое выглядит следующим образом:

Обратите внимание, что кнопка занимает все пространство, доступное в окне. Вот почему трудно увидеть края кнопки. Когда кнопка добавлена к компоненту макета, вы можете легче увидеть края кнопки.

Текст

Есть два способа установить текст кнопки:

  1. передать текст конструктору Button;
  2. вызвать метод setText() для экземпляра Button. Это можно сделать после создания экземпляра Button. Таким образом, его можно использовать для изменения текста кнопки, которая уже видна. Вот пример:

Размер текста

Вы можете установить размер текста кнопки с помощью свойства CSS -fx-text-size.

Обтекание текстом кнопки

Элемент управления Button поддерживает перенос текста текста кнопки. Под переносом текста подразумевается, что если текст слишком длинный для отображения в одной строке внутри кнопки, текст разбивается на несколько строк.

Вы включаете перенос текста в экземпляре Button с помощью метода setWrapText(). Он принимает один логический параметр. Если вы передаете значение true в setWrapText(), тогда вы включаете перенос текста. Если false, отключаете. Вот пример:

Вот снимок экрана с двумя кнопками JavaFX, для одной из которых включена функция переноса текста:

Изображение

Можно отобразить изображение внутри кнопки рядом с текстом. Класс Button содержит конструктор, который может принимать Node в качестве дополнительного параметра. Вот пример метки, который добавляет изображение с помощью компонента ImageView:

Результатом выполнения приведенного выше примера кнопки является приложение, которое выглядит следующим образом:

Размер

Класс Button содержит набор методов, которые вы можете использовать для установки размера кнопки:

  • Методы setMinWidth() и setMaxWidth() устанавливают минимальную и максимальную ширину, которую должна иметь кнопка.
  • Метод setPrefWidth() устанавливает предпочтительную ширину кнопки. Когда есть достаточно места для отображения кнопки в ее предпочтительной ширине, JavaFX сделает это. Если нет, уменьшит размер кнопки, пока она не достигнет минимальной ширины.
  • Методы setMinHeight() и setMaxHeight() устанавливают минимальную и максимальную высоту, которую должна иметь кнопка.
  • Метод setPrefHeight() устанавливает предпочтительную высоту кнопки. Когда есть достаточно места для отображения кнопки в ее предпочтительной высоте, JavaFX сделает это. Если нет, уменьшит размер, пока она не достигнет минимальной высоты.
  • Методы setMinSize(), setMaxSize() и setPrefSize() устанавливают ширину и высоту кнопки за один вызов. Таким образом, эти методы принимают параметры ширины и высоты:

Вот скриншот двух кнопок. Первая имеет размер по умолчанию, рассчитанный по ее тексту кнопки и компоненту макета, внутри которого она вложена. Вторая имеет предпочтительную ширину 200 и высоту 48, установленную на ней:

События

Чтобы реагировать на нажатие кнопки, необходимо прикрепить прослушиватель событий к объекту Button:

Вот как выглядит присоединение слушателя события щелчка с помощью лямбда-выражения Java:

Наконец, давайте посмотрим на полный пример, который изменяет текст метки при нажатии кнопки:

Мнемоника

Вы можете установить мнемонику для экземпляра Button – это клавиша клавиатуры, которая активирует кнопку при нажатии вместе с клавишей ALT. Таким образом, мнемоника – это сочетание клавиш для активации кнопки.

Мнемоника для кнопки указывается внутри текста кнопки. Вы отмечаете, какая клавиша будет использоваться как мнемоника, помещая символ подчеркивания (_) перед символом в тексте кнопки. Символ подчеркивания не будет отображаться в тексте кнопки. Вот пример:

Обратите внимание, что необходимо сначала вызвать setMnemonicParsing() для кнопки со значением true. Это дает команду кнопке анализировать мнемонику в ее тексте. Если вы вызываете этот метод со значением false, символ подчеркивания в тексте кнопки будет просто отображаться как текст и не будет интерпретироваться как мнемоника.

Вторая строка устанавливает текст _Click . Это говорит кнопке использовать ключ с как мнемонику. Мнемоника нечувствительна к регистру, поэтому она не должна быть прописной буквой C, которая активирует кнопку.

Чтобы активировать кнопку, теперь вы можете нажать ALT-C (одновременно). Это активирует кнопку, как если бы вы щелкнули по ней мышью.

Вы также можете сначала нажать клавишу ALT один раз. Это покажет мнемонику кнопки в тексте кнопки. Затем вы можете нажать клавишу c. Если вы нажмете ALT, а затем снова ALT, мнемоника сначала будет показана, а затем снова скрыта. Когда мнемоника видна, вы можете активировать кнопку только с помощью мнемонической клавиши, не нажимая при этом ALT. Когда мнемоника не видна, вы должны одновременно нажать ALT и клавишу мнемоники, чтобы активировать кнопку.

Вот два скриншота, показывающих, как это выглядит, когда мнемоника невидима и видима:

CSS-стили

Вы можете стилизовать кнопку, используя стили CSS. Элемент управления Button поддерживает следующие стили CSS:

Вот пример установки цвета фона кнопки на красный:

Этот пример устанавливает стиль непосредственно для кнопки с помощью метода setStyle(), но вы также можете стилизовать кнопку с помощью таблиц стилей.

Вот пример, который создает 4 разных кнопки. На каждой установлен стиль CSS.

Вот скриншот 4 кнопок JavaFX с их стилем CSS:

Первая кнопка имеет свойства CSS -fx-border-width и -fx-border-color. Это приводит к появлению красной рамки шириной 5 пикселей.

Вторая имеет свойство CSS -fx-background-color. Это приводит к зеленому цвету фона.

Третья имеет свойство CSS -fx-font-size. В результате получается кнопка с текстом, который в 2 раза больше обычного.

Четвертая имеет набор CSS-свойств -fx-text-fill. Это приводит к кнопке с синим цветом текста.

Вы можете объединить стили CSS для кнопки, просто установив для нее несколько свойств CSS, как это сделала первая кнопка в приведенном выше примере.

Отключение

Вы можете отключить кнопку с помощью метода setDisable(). Он принимает логический параметр, который указывает, должна ли кнопка быть отключена или нет. Значение true означает, что кнопка будет отключена, а значение false означает, что она не будет отключена, что означает, что она включена. Вот пример отключения:

JButton кнопка — обработка нажатия

Каждое приложение, которое имеет графический интерфейс пользователя не может обходиться без кнопок. В Java Swing кнопка представлена классом JButton. У кнопки имеются различные методы для ее конфигурирования — установка надписи на JButton, установка иконки, выравнивание текста, установка размеров и так далее. Кроме всего прочего разработчику необходимо навесить на JButton слушателя, который будет выполняться как только пользователь нажмет на кнопку. Как это сделать? Поговорим об этом ниже.

Ранее я писал, что все взаимодействия пользователя с приложением основано на событиях. Не является исключением и JButton. Как только пользователь нажимает кнопку, создается ActionEvent событие, которое передается слушателям кнопки. Для того, чтобы организовать слушателя Swing предоставляет интерфейс ActionListener, который необходимо реализовать. Интерфейс ActionListener требует только реализации одного метода — actionPerformed. Пример класса, реализующего интерфейс ActionListener представлен ниже.

После того, как обработчик создан, его необходимо добавить к кнопке. Делается это при помощи метода addActionListener. В качестве параметра методу передается обработчик. Например, это можно сделать вот так:

Здесь мы создаем сначала кнопку. Потом создаем экземпляр нашего слушателя TestActionListener, а затем добавляем его в качестве слушателя к кнопке с помощью вызова addActionListener и передаем ему экземпляр обработчика. Вообще слушателей может быть неопределенное количество. Если нам будет необходимо два или более слушателей, которые должны будут по-разному реагировать на нажатие кнопки, то для каждого из них вызовем addActionListener. Кроме того может когда-нибудь понадобиться отключить слушателя и сказать ему, чтобы он больше не прослушивал нажатие кнопки. Это можно сделать при помощи метода removeActionListener. Сюда в качестве параметра придется передать ссылку на слушателя, которого хотим удалить из списка слушателей кнопки JButton.

Ну и напоследок пример приложения для демонстрации обработчиков нажатия кнопки JButton.

Стоит сказать про несколько интересных на мой взгляд моментов. Первый — это использование action command. Можно заметить, что у кнопок вызывается метод setActionCommand, в который для каждой кнопки передает своё строковое значение. Таким образом в приложении можно понять, какая именно кнопка была нажата, если обработку нажатия нескольких кнопок выполняет один слушатель. Для того, чтобы узнать это у ActionEvent берется action command с помощью метода getActionCommand.

Второй момент — для обработки события нажатия кнопки JButton можно создать анонимный класс, который реализует интерфейс ActionListener. Это можно наблюдать вот здесь:

Читать:
Как открыть общий доступ к диску в windows 7

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