Lesson 6

Swing components

Do I need to create a button by myself?


import javax.swing.*;
import java.awt.*;

public class MyWindow extends JFrame {

    private JPanel left;
    private JPanel right;
    private JTextField textField;

    public MyWindow() {
        super();
        this.setSize(1024, 768);

        setVisible(true);
        setLayout(new BorderLayout());
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        initComponents();
    }

    private void initComponents() {
        textField = new JTextField();
        left = new JPanel();
        right = new JPanel();
        left.setLayout(new BoxLayout(left, BoxLayout.Y_AXIS));
        right.setLayout(new FlowLayout());
        add(left, BorderLayout.WEST);
        add(right, BorderLayout.CENTER);
        add(textField, BorderLayout.NORTH);
        for (int i = 0; i < 20; i++) {
            createButton(i);
        }
    }

    private void createButton(int i) {
        JButton button = new JButton();
        button.setText("Click me " + i);
        button.addActionListener((e) -> {
            setTitle(textField.getText());
        });
        if (Math.random() > 0.5) {
            left.add(button);
        } else {
            right.add(button);
        }
    }
}
            
Task 0

Prepare a window with 2 text fields and 1 button.

When I click on the button, the window's title bar displays sum of numbers stored in text fields.

Task 1

Create a window with two panels: on the top and in a center of the window.

Top panel has 3 buttons. Center panel has one JLabel (it displays a text).

When I click on the button, I see the JLabel's text has changed.

Task 2

Create a clock with option to display time in 12 or 24 hour system.

User can change the format with one button.

An article (new tab)