Java programming exercise Day08

Java programming exercise Day08

Check box control array

Example description

Check box control is often used in GUI program interface design. For example, many options can be added to the user's favorite program interface. If these options are entered through the GUI interface designer, it is very time-consuming, and the generated code is cumbersome and inconvenient to maintain.
This example realizes the user preference information selection interface through the check box control array, and the number of check boxes in the interface can be automatically adjusted according to the length of the string specifying the check box name.

design process

1. Create a CheckBoxArray form class in the project. Set the title of the form and add a label at the top of the interface to show "what are your hobbies:".

2. Write the getPanel() method to create a panel, and create a check box in the panel through the control array. The text of all check boxes is defined by the string array, and the number of check boxes is determined according to the length of the string array.

Test code

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

public class CheckBoxArray extends JFrame {
    //Create prompt label
    JLabel tip;
    //Create control array
    JCheckBox[] boxes;
    //Create panel container
    JPanel panel;
    //Create box
    Box box;
    Box box1;
    Box box2;


    //Create a form constructor
    public CheckBoxArray() {
        //Set form position and size
        setBounds(100, 100, 500, 400);
        //Set window title
        setTitle("Check box control array");
        //Set closing mode
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        //Set form visibility
        setVisible(true);

        tip = new JLabel("What are your hobbies:");

        JPanel panel = getPanel();

        box = Box.createVerticalBox();
        box1 = Box.createHorizontalBox();
        box2 = Box.createHorizontalBox();

        box1.add(tip);
        box2.add(panel);
        box.add(box1);
        box.add(box2);

        add(box);

    }

    //getPanel() method
    private JPanel getPanel(){
        if(panel == null){
            //Create panel objects
            panel = new JPanel();
            //Set up grid layout manager
            panel.setLayout(new GridLayout(0,4));
            //Create a control text array
            String[] labels = {"Football","Basketball","Magic","Table Tennis","watch movie","World of Warcraft","CS Team","badminton",
                    "Swimming","Mountain climbing","sing","Blog","Animal World","photograph","play the guitar","Read a newspaper","Drag racing","Go shopping",
                    "Go shopping","mahjong","read a book","Read materials on the Internet","Journalism","military","Gossip","health preservation","drink tea","League of Heroes"};
            //Create control array
            boxes = new JCheckBox[labels.length];
            //Traversal control array
            for (int i = 0; i < boxes.length; i++) {
                //Initializes the check box component in the array
                boxes[i] = new JCheckBox(labels[i]);
                panel.add(boxes[i]);//Add each check box to the panel
            }
        }
        return panel;
    }

    public static void main(String[] args) {
        new CheckBoxArray();
    }
}

Operation results

Invert a string with an array

Example description

This example uses the array inversion algorithm to reverse the string. Compared with the reserve() method of the StringBuilder class,
This example is more complex because the algorithms are completed by ourselves, but this example is more flexible. The instance is in the string
During the inversion process, the inversion steps are displayed. Developers can also add more business processes during the inversion process, such as controlling and displaying the progress bar, which cannot be realized by the reserve() method of StringBuilder class.

design process

1. Create the form class ArrayReverseString in the project. Add two text boxes to the form, a text field and an inversion button control.

2. Write the time processing method of the inversion button. In this method, the string entered by the user is converted into a character array, and then the array inversion algorithm is used to reverse the index of the array elements, and then the inverted character array is combined into a string and displayed in the text box control.

Test code

package com.zhang.exer.day08;

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

public class ArrayReverseString extends JFrame {
    //create label
    JLabel tip;
    //Create text box
    JTextField textField1;
    JTextField textField2;
    //Create text field
    JTextArea textArea;
    //Create button
    JButton reserve;
    //Create scroll panel
    JScrollPane jsp;


    //Create constructor
    public ArrayReverseString(){

        tip = new JLabel("Enter a string:");

        textField1 = new JTextField(5);
        textField2 = new JTextField(5);

        textArea = new JTextArea(10,10);

        reserve = new JButton("reversal");

        jsp = new JScrollPane(textArea);


        //Set form title
        setTitle("Invert a string with an array");
        //Set form position and size
        setBounds(250, 250, 450, 400);
        //Set form closing method
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        //Set form visibility
        setVisible(true);
        //Set the window to be non zoomable
        setResizable(false);
        //Set the layout mode to empty layout
        setLayout(null);
        //Set the position of each component
        tip.setBounds(20, 20,100,30);
        textField1.setBounds(150, 20,250,30);
        reserve.setBounds(20, 50,80,30);
        textField2.setBounds(150,50,250,30 );
        jsp.setBounds(75, 100,300,250);

        //Create event listener
        reserve.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String inputStr = textField1.getText();//Gets the string entered by the user
                char[] strArray = inputStr.toCharArray();//Extract character array
                textArea.setText("");//Clear text field
                for (int i = 0; i < strArray.length / 2; i++) {//Array inversion algorithm
                    char temp = strArray[i];//Swap array elements
                    strArray[i] = strArray[strArray.length-i-1];
                    strArray[strArray.length-i-1] = temp;
                    textArea.append("The first"+(i+1)+"Secondary cycle:\t");//Displays the cycle reversal process
                    for (char c:strArray) {
                        textArea.append(c+"");
                    }
                    textArea.append("\n");//Text field wrap
                }
                String outputStr = new String(strArray);//Convert a character array to a string
                textField2.setText(outputStr);//Displays the inverted string

            }
        });

        //Add the component to the window
        add(tip);
        add(textField1);
        add(textField2);
        add(reserve);
        add(jsp);


    }

    public static void main(String[] args) {
        new ArrayReverseString();
    }
}

Operation results

Keywords: Java IntelliJ IDEA array swing

Added by afatkidrunnin on Wed, 22 Dec 2021 06:42:54 +0200