Swing (java)

Содержание:

Разработка калькулятора с помощью Java AWT

Здесь я покажу вам, как создать калькулятор с помощью AWT, где вы сможете выполнять основные математические операции. Ниже приведен скриншот того, как будет выглядеть ваш калькулятор.

Теперь, чтобы построить это, вам нужно ввести следующий код:

package edureka.awt;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class Calculator extends Frame implements ActionListener

{
    Label lb1,lb2,lb3;

    TextField txt1,txt2,txt3;

    Button btn1,btn2,btn3,btn4,btn5,btn6,btn7;

    public Calculator()
    {
        lb1 = new Label("Var 1");
        lb2 = new Label("Var 2");
        lb3 = new Label("Result");

        txt1 = new TextField(10);
        txt2 = new TextField(10);
        txt3 = new TextField(10);

        btn1 = new Button("Add");
        btn2 = new Button("Sub");
        btn3 = new Button("Multi");
        btn4 = new Button("Div");
        btn5 = new Button("Mod");
        btn6 = new Button("Reset");
        btn7 = new Button("Close");

            add(lb1);
            add(txt1);
            add(lb2);
            add(txt2);
            add(lb3);
            add(txt3);
            add(btn1);
            add(btn2);
            add(btn3);
            add(btn4);
            add(btn5);
            add(btn6);
            add(btn7);
            
            setSize(200,200);
            setTitle("Calculator");
            setLayout(new FlowLayout());
            //setLayout(new FlowLayout(FlowLayout.RIGHT));
            //setLayout(new FlowLayout(FlowLayout.LEFT));
            btn1.addActionListener(this);
            btn2.addActionListener(this);
            btn3.addActionListener(this);
            btn4.addActionListener(this);
            btn5.addActionListener(this);
            btn6.addActionListener(this);
            btn7.addActionListener(this);
            
    }
    public void actionPerformed(ActionEvent ae) {
        double a=0,b=0,c=0;
        try
        {
            a = Double.parseDouble(txt1.getText());
        }
        catch (NumberFormatException e) {
            txt1.setText("Invalid input");
        }
        try
        {
            b = Double.parseDouble(txt2.getText());
        }
        catch (NumberFormatException e) {
            txt2.setText("Invalid input");
        }
        if(ae.getSource()==btn1)
        {
            c = a + b;
            txt3.setText(String.valueOf(c));
        }
        if(ae.getSource()==btn2)
        {
            c = a - b;
            txt3.setText(String.valueOf(c));
        }
        if(ae.getSource()==btn3)
        {
            c = a * b;
            txt3.setText(String.valueOf(c));
        }
        if(ae.getSource()==btn4)
        {
            c = a / b;
            txt3.setText(String.valueOf(c));
        }
        if(ae.getSource()==btn5)
        {
            c = a % b;
            txt3.setText(String.valueOf(c));
        }
        if(ae.getSource()==btn6)
        {
            txt1.setText("0");
            txt2.setText("0");
            txt3.setText("0");
        }
        if(ae.getSource()==btn7)
        {
            System.exit(0);           
        }     
    }
    public static void main(String[] args)
    {
        Calculator calC = new Calculator();
        calC.setVisible(true);
        calC.setLocation(300,300);
    }
}

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

Java Swing Components

2.1 JFrame

In Java Swing, the most applications will be built inside a basic component , which creates a window to hold other components.

JFrameExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18

Note that we can initialize the frame with the string “Hello Swing”, which creates a blank frame with the title “Hello Swing” like the figure below. The function tells the frame what to do when the user closes the frame and reforms exit when the user closes the frame. The size of the frame could be set by width and height parameters. Notice that without the function with the parameter true, you won’t see anything on the screen. In order to see the GUI part, we need this function and set it to be true.

JFrame

2.2 JLabel

is an area to display a short string or an image or both. Normally we can add the into the we’ve built in the previous part and show different displays. With the following java code added following the creation of , a label with the text “I’m a JLabel” is created.

1
2

For the position of the label, it could be specified by , , , of which the position could set to be left, center, and right correspondently. The figure below shows that a label is set in the center of the window.

JLabel

2.3 JPanel

is a popular container to hold different components. It could be set and added by using the code similar to the following:

1
2

2.4 JButton

is an implementation of a “push” button. It can be pressed and configured to have different actions, using the event listener. For this part, we’ll discuss it in the last. In the following code, we added three buttons into the panel with different names on them: Button 1, Button 2, Button 3.

ButtonExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

In the example above, we set a label to be on the upside and a panel containing three buttons in the bottom. The result is shown in the figure below. Note that we have a function, which is used to set the layout of the components. Further inflammation can be found in my another article about BoxLayout, which used the a lot.

JButton

2.5 JRadioButton

Here, is quite different from . It’s a radio button that can be selected or deselected. Use with the object to create a group of buttons, in which only one button can be selected at a time.

RadioButtonExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

The code above creates a button group and have their radio button inside. We set the “Male” button to be chosen by default, by setting it to be true initially. And we can see figures below, showing that each time, only one button can be chosen.

JRadioButton1

JRadioButton2

2.6 JCheckBox

is used to create a checkbox, of which multiple checkboxes could be selected at the same time. That’s the main difference between . For , I’ve written another article on it with a detailed example, you can check it here.

2.7 JSlider

is a component that lets the users select a value by sliding a knob within a specified interval. For the knob, it always points to the point which matches the integer values within the interval. You can check my article on J here.

2.8 JTable

is used to create a regular two-dimensional table. The table can display data inside of it. In addition, the user can also edit the data. The following example shows that we created three columns: ID, Name, Age. In each column, we have set the data/information inside.

JTableExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

The table is shown below:

JTable

2.9 JComboBox

is a component to select a value from a drop-down list. You can choose one and only one element from the list. The following example shows how to create the drop-down list, from which different countries can be chosen: “Australia”, “China”, “England”, “Russia”, “United States”.

JComboBoxExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

The two figures below show that we can choose different countries.

JComboBox1

JComboBox2

2.10 JMenu

In this example, we have different settings on the menu. We have a File menu, which includes of save, quit submenu, and Edit menu, including copy, cut, paste submenu, and Help menu, containing try your best:)

The code below is to generate the menus:

JMenuExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

JMenu1

JMenu2

JMenu3

JMenu4

Что такое контейнерный класс?

Контейнерные классы – это классы, в которых могут быть другие компоненты. Поэтому для создания графического интерфейса нам нужен как минимум один контейнерный объект. Есть 3 типа контейнеров.

  1. Панель: это чистый контейнер, а не окно само по себе. Единственная цель панели состоит в том, чтобы организовать компоненты на окне.
  2. Рамка: это полностью функционирующее окно с его заголовком и значками.
  3. Диалог: его можно рассматривать как всплывающее окно, которое появляется, когда сообщение должно быть отображено. Это не полностью функционирующее окно, как Рамка.
import javax.swing.*;
class gui{
    public static void main(String args[]){
       JFrame frame = new JFrame("My First GUI");
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(300,300);
       JButton button = new JButton("Press");
       frame.getContentPane().add(button); // Adds Button to content pane of frame
       frame.setVisible(true);
    }
}

Пример: Чтобы научиться проектировать GUI в Java.

Шаг 1) Скопируйте следующий код в редактор

import javax.swing.*;
   class gui{
      public static void main(String args[]){
        JFrame frame = new JFrame("My First GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300,300);
       JButton button1 = new JButton("Press");
       frame.getContentPane().add(button1);
       frame.setVisible(true);
     }
}

Шаг 2) Сохраните, скомпилируйте и запустите код.

Шаг 3) Теперь давайте добавим кнопку в наш фрейм. Скопируйте следующий код в редактор

import javax.swing.*;
class gui{
      public static void main(String args[]){
           JFrame frame = new JFrame("My First GUI");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           frame.setSize(300,300);
          JButton button1 = new JButton("Button 1");
          JButton button2 = new JButton("Button 2");
          frame.getContentPane().add(button1);
          frame.getContentPane().add(button2);
          frame.setVisible(true);
     }
}

Шаг 4) Выполнив код, вы получите большую кнопку.

Шаг 5) Как насчет добавления двух кнопок? Скопируйте следующий код в редактор.

import javax.swing.*;
class gui{
      public static void main(String args[]){
           JFrame frame = new JFrame("My First GUI");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           frame.setSize(300,300);
          JButton button1 = new JButton("Button 1");
          JButton button2 = new JButton("Button 2");
          frame.getContentPane().add(button1);
          frame.getContentPane().add(button2);
          frame.setVisible(true);
     }
}

Шаг 6) Сохраните, скомпилируйте и запустите программу.

Шаг 7) Неожиданный вывод =? Кнопки перекрываются.

Менеджер макетов используется для компоновки (или упорядочивания) компонентов JAVA GUI внутри контейнера. Существует много менеджеров макетов, но наиболее часто используемые из них-

Java BorderLayout – BorderLayout помещает компоненты в пять областей: верхнюю, нижнюю, левую, правую и центральную. Это менеджер макетов по умолчанию для каждого Java JFrame.

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

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

Шаг 8) Как насчет создания фрейма чата, как показано ниже?

Попробуйте написать код, прежде чем смотреть на программу ниже.

//Usually you will require both swing and awt packages
// even if you are working with just swings.
import javax.swing.*;
import java.awt.*;
class gui {
    public static void main(String args[]) {

        //Creating the Frame
        JFrame frame = new JFrame("Chat Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        //Creating the MenuBar and adding components
        JMenuBar mb = new JMenuBar();
        JMenu m1 = new JMenu("FILE");
        JMenu m2 = new JMenu("Help");
        mb.add(m1);
        mb.add(m2);
        JMenuItem m11 = new JMenuItem("Open");
        JMenuItem m22 = new JMenuItem("Save as");
        m1.add(m11);
        m1.add(m22);

        //Creating the panel at bottom and adding components
        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(tf);
        panel.add(send);
        panel.add(reset);

        // Text Area at the Center
        JTextArea ta = new JTextArea();

        //Adding Components to the frame.
        frame.getContentPane().add(BorderLayout.SOUTH, panel);
        frame.getContentPane().add(BorderLayout.NORTH, mb);
        frame.getContentPane().add(BorderLayout.CENTER, ta);
        frame.setVisible(true);
    }
}

References

Sources

  • Matthew Robinson, Pavel Vorobiev: Swing, Second Edition, Manning, ISBN 1-930110-88-X
  • David M. Geary: Graphic Java 2, Volume 2: Swing, Prentice Hall, ISBN 0-13-079667-0
  • John Zukowski: The Definitive Guide to Java Swing, Third Edition, Apress, ISBN 1-59059-447-9
  • James Elliott, Robert Eckstein, Marc Loy, David Wood, Brian Cole: Java Swing, O’Reilly, ISBN 0-596-00408-7
  • Kathy Walrath, Mary Campione, Alison Huml, Sharon Zakhour: The JFC Swing Tutorial: A Guide to Constructing GUIs, Addison-Wesley Professional, ISBN 0-201-91467-0
  • Joshua Marinacci, Chris Adamson: Swing Hacks, O’Reilly, ISBN 0-596-00907-0

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

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);
    }
}

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

Оцени статью

Оценить

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

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

Помогите улучшить статью.

Спасибо за ваши отзыв!

Файлы к книге

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

В книге около 150 примеров! Я постарался осветить все самое важное в Swing самыми простыми кусочками кода, которые тем не менее все являются настоящими программами

Примеры отсортированы по главам — когда вы распакуете архив, то увидите, что в нем находится 14 каталогов. В каждом из них хранятся примеры для своей главы — от второй до пятнадцатой (первая глава дает вводные и теоретические сведения, так что в ней примеров нет). Работать с примерами очень и очень просто — заходите в каталог той главы, с который вы сейчас работаете — все тексты примеров из нее, включая инструменты из пакета , там есть (тоже относится к значкам и другим файлам, если они требуются для работы примеров). Смело набирайте , и выполняйте тот пример, на котором вы остановились. Запуск изученных примеров и “кручение” их винтиков позволяет вам обрести мастерство намного быстрее.

Если вы обнаружите в примерах ошибки, в архиве будет чего-либо не хватать, или что-то не будет компилироваться, сообщите мне. Заранее спасибо.

Как и было обещано во введении книги, здесь вы сможете скачать архив JAR со всеми инструментами из пакета . Данный архив легко подключить к вашим программам (с помощью CLASSPATH или просто добавив его в директорию EXT вашего пакета JDK) и таким образов применять полюбившиеся вам инструменты из книги (если конечно такие найдутся). В архиве находятся следующие компоненты и инструменты:

  • BoxLayoutUtils
  • GUITools
  • XMLMenuLoader
  • CheckBoxList
  • CheckBoxTree
  • AutoCompleteTextField
  • Модели компонентов для доступа к базам данных
  • Редакторы для JComboBox
  • Отображающие объекты для списков и таблиц

Почему здравый смысл важнее паттернов, а Active Record не так уж и плох

Так уж вышло, что разработчики, особенно молодые, любят паттерны, любят спорить о том, какой паттерн нужно применять здесь или там. Спорить до хрипоты: это фасад или прокси, а может даже синглтон. А если у вас не чистая, гексагональная архитектура, то некоторые разработчики готовы сжечь на костре Святой Инквизиции.
При этом они забывают, что паттерны — это лишь возможные решения

У паттернов, также как и у любых принципов, есть границы применимости, и важно их понимать. Дорога в ад вымощена слепым и религиозным следованием пусть даже и авторитетным словам

А наличие во фреймворке нужных паттернов никак не гарантирует их правильного и осознанного применения.

JNI и Delphi. Использование Java методов при помощи JNI

Recovery Mode

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

Как мы видим в событии клика на кнопку будет исполняться просто код для удаления файла.
На Java все выглядит ясно и просто, но как же это будет выглядеть на Delphi с использованием JNI. На самом деле все проще чем кажется.
Для этого нам нужно разобрать заглянуть и в класс File, который находится по адресу java.io.File. Из этого класса нам нужно:

Организовываем взаимодействие между ПК и ЦАП/АЦП при помощи ПЛИС

Из песочницы

В современном цифровом мире необходимость ЦАП/АЦП (цифро-аналоговых преобразователей/аналого-цифровых преобразователей) не подвергается сомнению: они используются для обработки сигналов разнообразных датчиков, в звуковой аппаратуре, ТВ-тюнерах, платах видеовхода, видеокамерах и т.д.
Однако использование или отладка ЦАП/АЦП могут быть затруднены поставленными производителем аппаратуры ограничениями, например, на используемое ПО или на способы управления устройством. Это наводит на мысль о проектировании собственной модели взаимодействия.
В этой статье мы рассмотрим возможность организации взаимодействия между ПК и ЦАП/АЦП при помощи ПЛИС.

Особенности AWT в Java

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

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 GridBagLayout

It is the more sophisticated of all layouts. It aligns components by placing them within a grid of cells, allowing components to span more than one cell.

Step 8) How about creating a chat frame like below?

Try to code yourself before looking at the program below.

//Usually you will require both swing and awt packages
// even if you are working with just swings.
import javax.swing.*;
import java.awt.*;
class gui {
    public static void main(String args[]) {

        //Creating the Frame
        JFrame frame = new JFrame("Chat Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        //Creating the MenuBar and adding components
        JMenuBar mb = new JMenuBar();
        JMenu m1 = new JMenu("FILE");
        JMenu m2 = new JMenu("Help");
        mb.add(m1);
        mb.add(m2);
        JMenuItem m11 = new JMenuItem("Open");
        JMenuItem m22 = new JMenuItem("Save as");
        m1.add(m11);
        m1.add(m22);

        //Creating the panel at bottom and adding components
        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(tf);
        panel.add(send);
        panel.add(reset);

        // Text Area at the Center
        JTextArea ta = new JTextArea();

        //Adding Components to the frame.
        frame.getContentPane().add(BorderLayout.SOUTH, panel);
        frame.getContentPane().add(BorderLayout.NORTH, mb);
        frame.getContentPane().add(BorderLayout.CENTER, ta);
        frame.setVisible(true);
    }
}

Introduction

In Java swing, is used to position all its components, with setting properties, such as the size, the shape, and the arrangement. Different layout managers could have varies in different settings on their components. In this article, we’ll go through the most-common-used layout manager and with examples showing the differences among each other. In these examples, components will only contain buttons. For other components, you can go to my previous article Java swing tutorials for beginners.

The following layout managers are the ones that’ll be discussed in this article:

  • FlowLayout
  • BorderLayout
  • CardLayout
  • BoxLayout
  • GridLayout
  • GridBagLayout
  • GroupLayout
  • SpringLayout

For the following example parts on different Layout managers, Java 8 and Eclipse IDE (version Mars 4.5.0) are used.

Метка

Класс java.awt.Label предоставляет текстовую строку с описанием, видимую в графическом интерфейсе. Объект метки AWT – это компонент для размещения текста в контейнере. Класс Label имеет три конструктора:

// Construct a Label with the given text String, of the text alignment
public Label(String strLabel, int alignment); 

//Construct a Label with the given text String
public Label(String strLabel);

//Construct an initially empty Label
public Label();

Этот класс также предоставляет 3 константы:

public static final LEFT; // Label.LEFT

public static final RIGHT;  // Label.RIGHT

public static final CENTER; // Label.CENTER

Ниже я перечислил открытые методы, предоставляемые этим классом:

public String getText();

public void setText(String strLabel);

public int getAlignment();

//Label.LEFT, Label.RIGHT, Label.CENTER 
public void setAlignment(int alignment);

JAVA Swing Table Example

This Example demonstrates how to create a table using Swing in eclipse.

Prerequisite

This example is developed on Eclipse therefore a compatible Eclipse IDE is required to be installed on the system.
We also need WindowBuilder tool to be installed on Eclipse IDE for the easiness of the work. To learn how to install WindowBuilder tool please visit the Setup section 2.1 of the following link click here.

2.1 JAVA Swing Table

Create a new JAVA project lets say swing_1

Go to src→ right click→ New→ Other→ WindowBuilder→ select Swing Designer→ Application Window

JAVA Swing Table

JAVA Swing Table

Enter the name of the application(eg. SwingTableExample ) and click finish.

This will create SwingTableExample.java file and will provide Source and Design tab.

What is a container class?

Container classes are classes that can have other components on it. So for creating a GUI, we need at least one container object. There are 3 types of containers.

  1. Panel: It is a pure container and is not a window in itself. The sole purpose of a Panel is to organize the components on to a window.
  2. Frame: It is a fully functioning window with its title and icons.
  3. Dialog: It can be thought of like a pop-up window that pops out when a message has to be displayed. It is not a fully functioning window like the Frame.

What is GUI in Java?

GUI (Graphical User Interface) In Java gives programmers an easy-to-use visual experience to build Java applications. It is mainly made of graphical components like buttons, labels, windows, etc. through which the user can interact with the applications. Swing GUI in Java plays an important role in building easy interfaces.

Java GUI Example

Example: To learn to design GUI in JavaStep 1) Copy the following code into an editor

import javax.swing.*;
class gui{
    public static void main(String args[]){
       JFrame frame = new JFrame("My First GUI");
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(300,300);
       JButton button = new JButton("Press");
       frame.getContentPane().add(button); // Adds Button to content pane of frame
       frame.setVisible(true);
    }
}

Step 2) Save, Compile, and Run the code.Step 3) Now let’s Add a Button to our frame.  Copy following code into an editor

import javax.swing.*;
   class gui{
      public static void main(String args[]){
        JFrame frame = new JFrame("My First GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300,300);
       JButton button1 = new JButton("Press");
       frame.getContentPane().add(button1);
       frame.setVisible(true);
     }
}

Step 4) Execute the code. You will  get a big button

Step 5) How about adding two buttons? Copy the following code into an editor.

import javax.swing.*;
class gui{
      public static void main(String args[]){
           JFrame frame = new JFrame("My First GUI");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           frame.setSize(300,300);
          JButton button1 = new JButton("Button 1");
          JButton button2 = new JButton("Button 2");
          frame.getContentPane().add(button1);
          frame.getContentPane().add(button2);
          frame.setVisible(true);
     }
}

Step 6) Save , Compile , and Run the program.Step 7) Unexpected output =? Buttons are getting overlapped.

Java Layout Manger

The Layout manager is used to layout (or arrange) the GUI java components inside a container.There are many layout managers, but the most frequently used are-

Java GridBagLayout

It is the more sophisticated of all layouts. It aligns components by placing them within a grid of cells, allowing components to span more than one cell.

Step 8) How about creating a chat frame like below?

Try to code yourself before looking at the program below.

//Usually you will require both swing and awt packages
// even if you are working with just swings.
import javax.swing.*;
import java.awt.*;
class gui {
    public static void main(String args[]) {

        //Creating the Frame
        JFrame frame = new JFrame("Chat Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        //Creating the MenuBar and adding components
        JMenuBar mb = new JMenuBar();
        JMenu m1 = new JMenu("FILE");
        JMenu m2 = new JMenu("Help");
        mb.add(m1);
        mb.add(m2);
        JMenuItem m11 = new JMenuItem("Open");
        JMenuItem m22 = new JMenuItem("Save as");
        m1.add(m11);
        m1.add(m22);

        //Creating the panel at bottom and adding components
        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(tf);
        panel.add(send);
        panel.add(reset);

        // Text Area at the Center
        JTextArea ta = new JTextArea();

        //Adding Components to the frame.
        frame.getContentPane().add(BorderLayout.SOUTH, panel);
        frame.getContentPane().add(BorderLayout.NORTH, mb);
        frame.getContentPane().add(BorderLayout.CENTER, ta);
        frame.setVisible(true);
    }
}

Java GUI Example

Example: To learn to design GUI in JavaStep 1) Copy the following code into an editor

import javax.swing.*;
class gui{
    public static void main(String args[]){
       JFrame frame = new JFrame("My First GUI");
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(300,300);
       JButton button = new JButton("Press");
       frame.getContentPane().add(button); // Adds Button to content pane of frame
       frame.setVisible(true);
    }
}

Step 2) Save, Compile, and Run the code.Step 3) Now let’s Add a Button to our frame.  Copy following code into an editor

import javax.swing.*;
   class gui{
      public static void main(String args[]){
        JFrame frame = new JFrame("My First GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300,300);
       JButton button1 = new JButton("Press");
       frame.getContentPane().add(button1);
       frame.setVisible(true);
     }
}

Step 4) Execute the code. You will  get a big button

Step 5) How about adding two buttons? Copy the following code into an editor.

import javax.swing.*;
class gui{
      public static void main(String args[]){
           JFrame frame = new JFrame("My First GUI");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           frame.setSize(300,300);
          JButton button1 = new JButton("Button 1");
          JButton button2 = new JButton("Button 2");
          frame.getContentPane().add(button1);
          frame.getContentPane().add(button2);
          frame.setVisible(true);
     }
}

Step 6) Save , Compile , and Run the program.Step 7) Unexpected output =? Buttons are getting overlapped.

В диких условиях. Итоги проектов Школы программистов в эпоху самоизоляции

За четыре месяца занятий были прочитаны 54 лекции на двух потоках бекэнд и фронтенд, проведены несколько крутых практикумов с live-coding’ом. Проверены сотни заданий, на все вопросы получены две сотни ответов. Тут пришел 2020 год и сразу после того как мы сняли с елок гирлянды, всем нам самим пришлось нарядиться в маски и надеть перчатки. А теперь по порядку:

Десятая Школа Программистов hh.ru стала особенной. Юбилей, огромное количество планов, неиссякаемый поток учеников, неугасающая мотивация наших преподавателей и организаторов. Мы приложили максимум усилий, чтобы этот выпуск стал образцовым.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *