Java Swing is one of the popular tools in Java that is useful to create window-based applications.

What will you learn?

  1. Java Swing and Java Frame to insert, update, and delete records from a database.
  2. Using Java Swing to sum two numbers and display output when you press the button.
  3. Java program to display output when the user presses any key from the keyboard.

Java Swing and Java Frame to insert, update, and delete records from a database

JLabel: It displays a single line of read-only text.

JTextArea: It displays a multiline text area field. You can also use JTextField which displays a single-line text area field.

JButton: It displays a button and you can also trigger this button i.e., perform certain actions.
I am writing the connection part code on the same page. You can also write this code on a separate page. All you have to do is just create the object of that connection class and use it.

package javaSwing;

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

public class Main extends Frame implements ActionListener {
  JLabel l1, l2, l3, l4, l5;
  JTextArea t1, t2, t3, t4;
  JButton b1, b2, b3;

  Main() {
    JFrame f = new JFrame();
    l1 = new JLabel(("ID: "));
    l1.setBounds(50, 10, 70, 50);

    t1 = new JTextArea();
    t1.setBounds(100, 25, 100, 20);

    l2 = new JLabel(("Name: "));
    l2.setBounds(50, 40, 70, 50);
    t2 = new JTextArea();
    t2.setBounds(100, 55, 100, 20);

    l3 = new JLabel(("Age: "));
    l3.setBounds(50, 70, 70, 50);
    t3 = new JTextArea();
    t3.setBounds(100, 85, 100, 20);

    l4 = new JLabel(("Address: "));
    l4.setBounds(50, 100, 70, 50);
    t4 = new JTextArea();
    t4.setBounds(100, 115, 100, 20);

    b1 = new JButton("Insert: ");
    b1.setBounds(10, 150, 100, 40);
    b1.addActionListener(this);

    b2 = new JButton("Update: ");
    b2.setBounds(90, 150, 100, 40);
    b2.addActionListener(this);

    b3 = new JButton("Delete: ");
    b3.setBounds(180, 150, 100, 40);
    b3.addActionListener(this);

    l5 = new JLabel("");
    l5.setBounds(50, 200, 200, 50);

    f.add(l1);
    f.add(t1);
    f.add(l2);
    f.add(t2);
    f.add(l3);
    f.add(t3);
    f.add(l4);
    f.add(t4);
    f.add(b1);
    f.add(b2);
    f.add(b3);
    f.add(l5);

    f.setSize(300, 300);
    f.setLayout(null);
    f.setVisible(true);
    f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    String s1 = t1.getText(); //id
    String s2 = t2.getText(); //name
    String s3 = t3.getText(); //age
    String s4 = t4.getText(); //address

    Connection conn = setconnection();
    if (e.getSource() == b1) {
      try {
        Statement st = conn.createStatement();
        st.executeUpdate("insert into Stu_Table(id,name,age,address) " +
          "values('" + s1 + "','" + s2 + "','" + s3 + "','" + s4 + "')");
      } catch (SQLException e1) {
        System.out.println(e1);
      }
      l5.setText("Data inserted");
    }
    if (e.getSource() == b2) {
      try {
        Statement st = conn.createStatement();
        st.executeUpdate("update Stu_Table set name='" + s2 + "',age='" + s3 + "',address='" + s4 + "'" +
          " where id='" + s1 + "'");
      } catch (SQLException e2) {
        System.out.println(e2);
      }
      l5.setText("Data updated");
    }
    if (e.getSource() == b3) {
      try {
        Statement st = conn.createStatement();
        st.executeUpdate("delete from Stu_Table where id='" + s1 + "'");
      } catch (SQLException e3) {
        System.out.println(e3);
      }
      l5.setText("Data deleted");
    }

  }

  public static Connection setconnection() {
    String databaseURL = "jdbc:mysql://localhost:3306/Student_DB";
    String user = "root";
    String password = "";
    Connection conn = null;

    try {
      Class.forName("com.mysql.cj.jdbc.Driver");
      try {
        conn = DriverManager.getConnection(databaseURL, user, password);
        System.out.println("Connected to the database");
      } catch (SQLException e) {
        System.out.println(e);
      }
    } catch (ClassNotFoundException e) {
      System.out.println("Class not found exception");
    }
    return conn;
  }

  public static void main(String[] args) {
    // write your code here
    new Main();

  }
}

Using Java Swing to sum two numbers and display output when you press the button

Create a program that adds two numbers using swing components. For both input and output, use text fields. The output should be shown by the programmer when a user clicks a button.

Remember, you have to display output when you press the button. Next question you might have to display output when you press any key from the keyboard. So, these two are different questions. I have covered both of these questions. This is the post where I will show you the sum of two numbers and display the output when you press the button.

You are asked to use Java Swing to solve this question. Java Swing is a very popular tool to create window-based applications.

// Create a program that adds two numbers using swing components.
// For both input and output, use text fields.
// The output should be shown by the programmer when a user clicks a button.

package javaSwing;

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

public class Main extends Frame implements ActionListener {
    JLabel l1,l2;
    JTextArea t1,t2,t3;
    JButton b1;
    Main(){
        JFrame f=new JFrame();
        l1=new JLabel("First num: ");
        l1.setBounds(20,10,100,20);
        //don't need to remember this coordinate
        //because in our coming videos, we will use layout manager (GridLayout) which is very easy to use
       
        t1 = new JTextArea();
        t1.setBounds(120,10,100,20);

        l2=new JLabel("Second num: ");
        l2.setBounds(20,40,100,20);
        t2 = new JTextArea();
        t2.setBounds(120,40,100,20);

        b1=new JButton("Sum: ");
        b1.setBounds(20,70,80,20);
        b1.addActionListener(this);
        t3=new JTextArea();
        t3.setBounds(120,70,100,20);

        f.add(l1);f.add(t1);
        f.add(l2);f.add(t2);
        f.add(b1);f.add(t3);

        f.setSize(250,200);
        f.setLayout(null);
        f.setVisible(true);
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==b1){
            int firstnum = Integer.parseInt(t1.getText());
            int secondnum = Integer.parseInt(t2.getText());
            int sum = firstnum+secondnum;
            t3.setText(Integer.toString(sum));
        }
    }
    public static void main(String[] args) {
        // write your code here
    new Main();
    }
}

Java program to display output when the user presses any key from the keyboard

Create a Java program that uses swing components to find the sum of two numbers. For input and output, use text fields. If you press any key on the keyboard, your application should display output. To handle events, use a key adapter.

Remember: you have to press any key from the keyboard to display the output. It is not okay to display the output when you press a button. That is a different question.

We can use KeyAdapter and KeyEvent for this purpose.

package swing;

import java.awt.GridLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.*;  //JLabel, JTextField, JFrame

public class Java_project extends KeyAdapter {
	JLabel l1,l2,l3,l4;
	JTextField t1,t2,t3,t4;
	JFrame f = new JFrame();
	Java_project(){
		l1 = new JLabel("First num: ");
		t1 = new JTextField();
		l2 = new JLabel("Second num: ");
		t2 = new JTextField();
		l3 = new JLabel("Press any key from keyboard: ");
		t3 = new JTextField();
		t3.addKeyListener(this);
		l4 = new JLabel("Output: ");
		t4 = new JTextField();
		f.add(l1);f.add(t1);
		f.add(l2);f.add(t2);
		f.add(l3);f.add(t3);
		f.add(l4);f.add(t4);

		f.setSize(250,150);
		f.setLayout(new GridLayout(4,2));
		f.setLocationRelativeTo(null);
		f.setVisible(true);
		f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
	}
	
	public void keyPressed(KeyEvent e) {
		int firstnum = Integer.parseInt(t1.getText());
		int secondnum = Integer.parseInt(t2.getText());
		int sum = firstnum + secondnum;
		t3.setText(null);
	    t4.setText(Integer.toString(sum));
	}
	
	public static void main(String[] args) {
		new Java_project();	
	}
}

Note: In the above video, I have displayed output in the dialogue box and in this code, I have displayed output in the text field, this is what the question asks us to do.

Conclusion:

In this way, you can open a GUI window and perform operations like CRUD, adding two integer values, and displaying out on pressing a button or key from a keyboard.

I hope this post is very helpful to you. Don't hesitate to ask me in the comment section if you have any queries. I will reply as soon as possible. Thanks.