Tutorial for java swing

Как создать графический интерфейс с примерами Swing на Java

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

Объединение всех этих компонентов создает графический интерфейс пользователя.

Что такое Swing в Java?

Swing в Java – это легкий инструментарий с графическим интерфейсом, который имеет широкий спектр виджетов для создания оптимизированных оконных приложений. Это часть JFC (Java Foundation Classes). Он построен на основе AWT API и полностью написан на Java. Он не зависит от платформы в отличие от AWT и имеет легкие компоненты.

Создавать приложения становится проще, поскольку у нас уже есть компоненты GUI, такие как кнопка, флажок и т. д.

Контейнерный класс

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

Ниже приведены три типа контейнерных классов:

  1. Панель – используется для организации компонентов в окне.
  2. Рамка – полностью функционирующее окно со значками и заголовками.
  3. Диалог – это как всплывающее окно, но не полностью функциональное, как рамка.
Читайте также:  Дизайн формы css шаблоны

Разница между AWT и Swing

Иерархия

иерархия swing

Объяснение: Все компоненты в свинге, такие как JButton, JComboBox, JList, JLabel, унаследованы от класса JComponent, который можно добавить в классы контейнера.

Контейнеры – это окна, такие как рамка и диалоговые окна. Основные компоненты являются строительными блоками любого графического приложения. Такие методы, как setLayout, переопределяют макет по умолчанию в каждом контейнере. Контейнеры, такие как JFrame и JDialog, могут добавлять только компонент к себе. Ниже приведены несколько компонентов с примерами, чтобы понять, как мы можем их использовать.

JButton Class

Он используется для создания помеченной кнопки. Использование ActionListener приведет к некоторым действиям при нажатии кнопки. Он наследует класс AbstractButton и не зависит от платформы.

import javax.swing.*; public class example < public static void main(String args[]) < JFrame a = new JFrame("example"); JButton b = new JButton("click me"); b.setBounds(40,90,85,20); a.add(b); a.setSize(300,300); a.setLayout(null); a.setVisible(true); >>

пример кнопки

JTextField Class

Он наследует класс JTextComponent и используется для редактирования однострочного текста.

import javax.swing.*; public class example < public static void main(String args[]) < JFrame a = new JFrame("example"); JTextField b = new JTextField("edureka"); b.setBounds(50,100,200,30); a.add(b); a.setSize(300,300); a.setLayout(null); a.setVisible(true); >>

создание поля редактируемого текста

JScrollBar Class

Он используется для добавления полосы прокрутки, как горизонтальной, так и вертикальной.

import javax.swing.*; class example < example()< JFrame a = new JFrame("example"); JScrollBar b = new JScrollBar(); b.setBounds(90,90,40,90); a.add(b); a.setSize(300,300); a.setLayout(null); a.setVisible(true); >public static void main(String args[]) < new example(); >>

пример JScrollBar

JPanel Class

Он наследует класс JComponent и предоставляет пространство для приложения, которое может присоединить любой другой компонент.

import java.awt.*; import javax.swing.*; public class Example < Example()< JFrame a = new JFrame("example"); JPanel p = new JPanel(); p.setBounds(40,70,200,200); JButton b = new JButton("click me"); b.setBounds(60,50,80,40); p.add(b); a.add(p); a.setSize(400,400); a.setLayout(null); a.setVisible(true); >public static void main(String args[]) < new Example(); >>

компонент JPanel

JMenu Class

Он наследует класс JMenuItem и является компонентом выпадающего меню, которое отображается из строки меню.

import javax.swing.*; class Example < JMenu menu; JMenuItem a1,a2; Example() < JFrame a = new JFrame("Example"); menu = new JMenu("options"); JMenuBar m1 = new JMenuBar(); a1 = new JMenuItem("example"); a2 = new JMenuItem("example1"); menu.add(a1); menu.add(a2); m1.add(menu); a.setJMenuBar(m1); a.setSize(400,400); a.setLayout(null); a.setVisible(true); >public static void main(String args[]) < new Example(); >>

выпадающее меню

Вывод:

Класс JList

Он наследует класс JComponent, объект класса JList представляет список текстовых элементов.

import javax.swing.*; public class Example < Example()< JFrame a = new JFrame("example"); DefaultListModell = new DefaultListModel< >(); l.addElement("first item"); l.addElement("second item"); JList b = new JList< >(l); b.setBounds(100,100,75,75); a.add(b); a.setSize(400,400); a.setVisible(true); a.setLayout(null); > public static void main(String args[]) < new Example(); >>

Класс JList

Вывод:

JLabel Class

Используется для размещения текста в контейнере. Он также наследует класс JComponent.

import javax.swing.*; public class Example < public static void main(String args[]) < JFrame a = new JFrame("example"); JLabel b1; b1 = new JLabel("edureka"); b1.setBounds(40,40,90,20); a.add(b1); a.setSize(400,400); a.setLayout(null); a.setVisible(true); >>

размещение текста в контейнере

Вывод:

JComboBox Class

Он наследует класс JComponent и используется для отображения всплывающего меню выбора.

import javax.swing.*; public class Example< JFrame a; Example()< a = new JFrame("example"); string courses[] = < "core java","advance java", "java servlet">; JComboBox c = new JComboBox(courses); c.setBounds(40,40,90,20); a.add(c); a.setSize(400,400); a.setLayout(null); a.setVisible(true); > public static void main(String args[]) < new Example(); >>

отображения всплывающего меню java

Вывод:

Для размещения компонентов внутри контейнера мы используем менеджер макета. Ниже приведены несколько менеджеров макетов:

Макет границы

Менеджер границы

Менеджер по умолчанию для каждого JFrame – BorderLayout. Он размещает компоненты в пяти местах: сверху, снизу, слева, справа и по центру.

Макет потока

Макет потока

FlowLayout просто кладет компоненты в ряд один за другим, это менеджер компоновки по умолчанию для каждого JPanel.

GridBag Layout

GridBagLayout размещает компоненты в сетке

GridBagLayout размещает компоненты в сетке, что позволяет компонентам охватывать более одной ячейки.

Пример: фрейм чата

import javax.swing.*; import java.awt.*; class Example < public static void main(String args[]) < JFrame frame = new JFrame("Chat Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 400); JMenuBar ob = new JMenuBar(); JMenu ob1 = new JMenu("FILE"); JMenu ob2 = new JMenu("Help"); ob.add(ob1); ob.add(ob2); JMenuItem m11 = new JMenuItem("Open"); JMenuItem m22 = new JMenuItem("Save as"); ob1.add(m11); ob1.add(m22); JPanel panel = new JPanel(); // the panel is not visible in output JLabel label = new JLabel("Enter Text"); JTextField tf = new JTextField(10); // accepts upto 10 characters JButton send = new JButton("Send"); JButton reset = new JButton("Reset"); panel.add(label); // Components Added using Flow Layout panel.add(label); // Components Added using Flow Layout panel.add(tf); panel.add(send); panel.add(reset); JTextArea ta = new JTextArea(); frame.getContentPane().add(BorderLayout.SOUTH, panel); frame.getContentPane().add(BorderLayout.NORTH, tf); frame.getContentPane().add(BorderLayout.CENTER, ta); frame.setVisible(true); >>

чат на Java пример

Это простой пример создания GUI с использованием Swing в Java.

Средняя оценка 4.7 / 5. Количество голосов: 137

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

Видим, что вы не нашли ответ на свой вопрос.

Напишите комментарий, что можно добавить к статье, какой информации не хватает.

Источник

Trail: Creating a GUI With Swing

This trail tells you how to create graphical user interfaces (GUIs) for applications and applets, using the Swing components. If you would like to incorporate JavaFX into your Swing application, please see Integrating JavaFX into Swing Applications.

Getting Started with Swing is a quick start lesson. First it gives you a bit of background about Swing. Then it tells you how to compile and run programs that use Swing components.

Learning Swing with the NetBeans IDE is the fastest and easiest way to begin working with Swing. This lesson explores the NetBeans IDE’s GUI builder, a powerful feature that lets you visually construct your Graphical User Interfaces.

Using Swing Components tells you how to use each of the Swing components — buttons, tables, text components, and all the rest. It also tells you how to use borders and icons.

Concurrency in Swing discusses concurrency as it applies to Swing programming. Information on the event dispatch thread and the SwingWorker class are included.

Using Other Swing Features tells you how to use actions, timers, and the system tray; how to integrate with the desktop class, how to support assistive technologies, how to print tables and text, how to create a splash screen, and how to use modality in dialogs.

Laying Out Components Within a Container tells you how to choose a layout manager, how to use each of the layout manager classes the Java platform provides, how to use absolute positioning instead of a layout manager, and how to create your own layout manager.

Modifying the Look and Feel tells you how to specify the look and feel of Swing components.

Drag and Drop and Data Transfer tells you what you need to know to implement data transfer in your application.

Writing Event Listeners tells you how to handle events in your programs.

Performing Custom Painting gives you information on painting your own Swing components. It discusses painting issues specific to Swing components, provides an overview of painting concepts, and has examples of custom components that paint themselves.

Although this is the main trail for learning about GUIs, it isn’t the only trail with UI-related information.

  • 2D Graphics, which describes the 2D graphics features available in the JDK.
  • Sound, which discusses the sound capabilities available in the JDK.
  • Java Applets, which describes API available only to applets.
  • Essential Java Classes, which covers many topics, including properties and the standard I/O streams.
  • The JavaFX Documentation, which describes how to build UIs with JavaFX.
  • The Bonus trail contains Full-Screen Exclusive Mode API, a lesson that describes how to use API introduced in v1.4 to render graphics directly to the screen.

Источник

Lesson: Using Swing Components

This lesson gives you the background information you need to use the Swing components, and then describes every Swing component. It assumes that you have successfully compiled and run a program that uses Swing components, and that you are familiar with basic Swing concepts. These prerequisites are covered in Getting Started with Swing and Learning Swing with the NetBeans IDE.

Using Top-Level Containers

Discusses how to use the features shared by the JFrame , JDialog , and JApplet classes — content panes, menu bars, and root panes. It also discusses the containment hierarchy, which refers to the tree of components contained by a top-level container.

The JComponent Class

Tells you about the features JComponent provides to its subclasses — which include almost all Swing components — and gives tips on how to take advantage of these features. This section ends with API tables describing the commonly used API defined by JComponent and its superclasses, Container and Component .

Using Text Components

Describes the features and API shared by all components that descend from JTextComponent . You probably do not need to read this section if you are just using text fields (formatted or not) or text areas.

How to.

Sections on how to use each Swing component, in alphabetical order. We do not expect you to read these sections in order. Instead, we recommend reading the relevant «How to» sections once you are ready to start using Swing components in your own programs. For example, if your program needs a frame, a label, a button, and a color chooser, you should read How to Make Frames, How to Use Labels, How to Use Buttons, and How to Use Color Choosers.

Using HTML in Swing Components

Describes how to vary the font, color, or other formatting of text displayed by Swing components by using HTML tags.

Using Models

Tells you about the Swing model architecture. This variation on Model-View-Controller (MVC) means that you can, if you wish, specify how the data and state of a Swing component are stored and retrieved. The benefits are the ability to share data and state between components, and to greatly improve the performance of components such as tables that display large amounts of data.

Using Borders

Borders are very handy for drawing lines, titles, and empty space around the edges of components. (You might have noticed that the examples in this trail use a lot of borders.) This section tells you how to add a border to any JComponent .

Using Icons

Many Swing components can display icons. Usually, icons are implemented as instances of the ImageIcon class.

Solving Common Component Problems

This section discusses solutions to common component-related problems.

If you are interested in using JavaFX to create your GUI, see Using JavaFX Charts and Using JavaFX UI Controls.

Источник

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