Java swing class method

Java Swing Components Set and Get Methods

Java Swing components have getters and setters methods used to get and set values, respectively. They are essential because they protect the user’s data, mainly when creating classes.

A getter method usually returns its value (component value) while a setter method sets (updates) its value.

This makes getters accessors since they allow users to access the values of the Java swing components. At the same time, setters are mutators since they are used to control changes made to the Java Swing components variable.

This article will discuss the setters and getters methods of Java Swing components used in a desktop application. We will use an application example to show how these methods are used in developing and implementing a desktop application in Java Swing.

Table of contents

Prerequisites

  • Preinstalled Java programming IDE eg. NetBeans installed.
  • Java Development Kit installed.
  • Basic knowledge of Java Swing.

Java swing graphical user interface

We define a class method in our project where we design the user interface. In this class, we add Java Swing components to our project.

We could use a drag and drop palette in NetBeans IDE as described in the article found here or hard code and declare the swing components.

In this article, we will declare, hard code and add the components to our project. The method below creates our user interface.

 public void sectionCreatingGUI() //This method creates UI   swingGetterSetters = new JFrame("Section Java Swing Getters and Setters");  swingGetterSetters.setLayout(null);  swingGetterSetters.setSize(700, 450);  swingGetterSetters.setVisible(true);  swingGetterSetters.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  title.setBounds(260, 10, 380, 20);  Fname.setBounds(120, 40, 300, 20);  fname.setBounds(320, 40, 320, 30);  Sname.setBounds(120, 70, 300, 20);  sname.setBounds(320, 70, 320, 30);  address.setBounds(120, 100, 300, 20);  adress.setBounds(320, 100, 320, 30);  PhoneNumber.setBounds(120, 130, 300, 20);  phoneNumber.setBounds(320, 130, 320, 30);  id.setBounds(120, 160, 300, 20);  idnumber.setBounds(320, 160, 320, 30);  submit.setBounds(540, 200, 100, 30);  sp.setBounds(120, 240, 520, 150);  swingGetterSetters.add(title);  swingGetterSetters.add(Fname);  swingGetterSetters.add(fname);  swingGetterSetters.add(Sname);  swingGetterSetters.add(sname);  swingGetterSetters.add(address);  swingGetterSetters.add(adress);  swingGetterSetters.add(PhoneNumber);  swingGetterSetters.add(phoneNumber);  swingGetterSetters.add(id);  swingGetterSetters.add(idnumber);  swingGetterSetters.add(submit);  submit.addActionListener(new ActionListener()   swingGetterSetters.add(sp);  > 

JLabel

We start by declaring our JLabel components as shown below:

 JLabel Fname = new JLabel();  JLabel Sname = new JLabel();  JLabel address = new JLabel();  JLabel PhoneNumber = new JLabel();  JLabel title = new JLabel();  JLabel id = new JLabel(); 

Setting the JLabel values-Setter method:

 //Setters for the JLabel, Sets the text displayed on the JLabel  Fname.setText("First Name");  Sname.setText("Second Name ");  address.setText("Address");  PhoneNumber.setText("Phone Number");  title.setText("CUSTOMER INFORMATION");  id.setText("ID Number"); 

Getter for the JLabel values- Gets the value of the JLabel variable and assigns the value to the string variable.

 String FnameLabelValue=Fname.getText();  String SnameLabelValue=Sname.getText();  String addressLabelValue=address.getText();  String PhoneNumberLabelValue=PhoneNumber.getText();  String idLabelValue=id.getText();  String titleLabelValue=title.getText();  String submitButtonValue=submit.getText(); 

JTextField

Declaration of the JTextField components — JTextField components allow the application to interact with the users.

 JTextField fname = new JTextField();  JTextField sname = new JTextField();  JTextField adress = new JTextField();  JTextField phoneNumber = new JTextField();  JTextField idnumber = new JTextField(); 

The user can input text values to the JTextField. As the user inputs text value, it sets the value of the JTextField variable component.

We can use a getter method to access this value input by the user, display it on JLabel, store it in a database, or display it in a JTable. In this article, we will display the values in a JTable.

Getter for JTextField component- We get the values of the JTextField and assign them to string variables which we display in a JTable

 //Here we define getters which will get the text entered by the user in the respective JTextField and set/initialize them to our string variables  String FirstName = fname.getText();  String SecondName = sname.getText();  String Address = adress.getText();  String IdNumber = idnumber.getText();  String Phonumber = phoneNumber.getText(); 

Displaying the values to a JTable

 //To ensure that we really got the values from the JTextField, we need to display them in the JTable  DefaultTableModel Table = (DefaultTableModel) customerData.getModel();  Table.addRow(new Object[]FirstName + " " + SecondName, Address, Phonumber, IdNumber>); 

JButton

The JButton swing component has a platform-independent implementation class method. When the button is pushed or clicked with a mouse it results in some action.

The event fires an action which could be getting the values of other components and displaying them or storing them in a database.

In this article, we will see the action event method of a JButton. It will display the values of the JTextField components to the JTable.

JButton declaration

 JButton submit = new JButton(); 

JButton Setter method

 submit.setText("SUBMIT"); //this sets the text value displayed on the JButton as the text in braces 

JButton getter method — This gets the value of the text set on the JButton.

 String submitButtonValue=submit.getText(); 

JButton Action Event

  • The inner class method defines the action event for the JButton. On click, the swingGetter() method is called.
 submit.addActionListener(new ActionListener()   @Override  public void actionPerformed(ActionEvent e)   swingGetter();  >  >);//The action event for the JButton 

Below is the whole swingGetter() method called in the Jbutton action event.

 public void swingGetter()   //Here we define getters which will get the text entered by the user in the respective JTextField and set/initialize them to our string variables  FirstName = fname.getText();  SecondName = sname.getText();  Address = adress.getText();  IdNumber = idnumber.getText();  Phonumber = phoneNumber.getText();  //To ensure that we really got the values from the JTextField, we need to display them in the JTable  DefaultTableModel Table = (DefaultTableModel) customerData.getModel();  Table.addRow(new Object[]FirstName + " " + SecondName, Address, Phonumber, IdNumber>);  //We need to empty the JTextField to allow more entry after the first, second etc. Thus, values will set the JTextField to null (empty) to allow next entry  fname.setText(null);  sname.setText(null);  adress.setText(null);  idnumber.setText(null);  phoneNumber.setText(null);  //End of swingGetter() method. We will call this method in JButton Action Event method above, the events here happens upon the click of the JButton  > 

Output

When we run our project, the graphical user interface will be displayed. This is to allow the user to enter values into the text field as shown in the figure below:

GUI

When the user clicks on the submit button after keying in the values in the text field, the values will be displayed in the table.

The text field is set to empty for subsequent entry as shown in figure 2 below:

output

Conclusion

From this article, we have learned the following:

  1. Java swing components declaration and user interface design.
  2. Setter and getter methods for: i. JLabel ii. JTextField iii. JButton
  3. JButton action event.
  4. How to display values to a JTable from JTextField using the getter method.

The code snippets used in this guide can be accessed at my GitHub Repo.

Peer Review Contributions by: Dawe-Daniel

Источник

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

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

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

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

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

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

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

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

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

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

Разница между 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

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

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

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

Источник

Читайте также:  Класс container в html
Оцените статью