Text Field
import javax.swing.*;
class TextFieldExample {
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Java.");
t1.setBounds(50,100,200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150,200,30);
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Button
import javax.swing.*;
public class ButtonExample
{
public static void main(String[] args)
{
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Check Box
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample()
{
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}
Radio Button
import javax.swing.*;
public class RadioButtonExample
{
JFrame f;
RadioButtonExample()
{
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args)
{
new RadioButtonExample();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class JToggleButtonTest extends JFrame implements ItemListener {
private JToggleButton jtb;
JToggleButtonTest() {
setTitle("JToggleButton Test");
setLayout(new FlowLayout());
setJToggleButton();
setAction();
setSize(450, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void setJToggleButton() {
jtb = new JToggleButton("ON");
add(jtb);
}
private void setAction() {
jtb.addItemListener(this);
}
public void itemStateChanged(ItemEvent eve) {
if (jtb.isSelected())
jtb.setText("OFF");
else
jtb.setText("ON");
}
}
public class MainApp {
public static void main(String[] args) {
new JToggleButtonTest();
}
}
import java.awt.*;
import java.sql.*;
import javax.swing.*;
import java.awt.event.*;
public class UserLogin extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField textField;
private JPasswordField passwordField;
private JButton btnNewButton;
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
UserLogin frame = new UserLogin();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
});
}
public UserLogin() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(450, 190, 1014, 597);
setResizable(false);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Login");
lblNewLabel.setForeground(Color.BLACK);
lblNewLabel.setFont(new Font("Times New Roman", Font.PLAIN, 46));
lblNewLabel.setBounds(423, 13, 273, 93);
contentPane.add(lblNewLabel);
textField = new JTextField();
textField.setFont(new Font("Tahoma", Font.PLAIN, 32));
textField.setBounds(481, 170, 281, 68);
contentPane.add(textField);
textField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setFont(new Font("Tahoma", Font.PLAIN, 32));
passwordField.setBounds(481, 286, 281, 68);
contentPane.add(passwordField);
JLabel lblUsername = new JLabel("Username");
lblUsername.setForeground(Color.BLACK);
lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 31));
lblUsername.setBounds(250, 166, 193, 52);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setForeground(Color.BLACK);
lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 31));
lblPassword.setBounds(250, 286, 193, 52);
contentPane.add(lblPassword);
btnNewButton = new JButton("Login");
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 26));
btnNewButton.setBounds(545, 392, 162, 73);
btnNewButton.addActionListener(e -> loginUser());
contentPane.add(btnNewButton);
}
private void loginUser() {
String userName = textField.getText();
char[] password = passwordField.getPassword();
String passwordStr = new String(password); // Convert char[] to String
try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/swing_demo", "root", "aayushmysql4437")) {
// Show dialog that connection is successful
JOptionPane.showMessageDialog(btnNewButton, "Connection to database successful!");
// Prepare statement to check username and password
try (PreparedStatement st = connection.prepareStatement("SELECT name FROM Login WHERE name=? AND password=?")) {
st.setString(1, userName);
st.setString(2, passwordStr);
ResultSet rs = st.executeQuery();
if (rs.next()) {
dispose();
//UserHome ah = new UserHome(userName);
//ah.setTitle("Welcome");
//ah.setVisible(true);
JOptionPane.showMessageDialog(btnNewButton, "You have successfully logged in");
} else {
JOptionPane.showMessageDialog(btnNewButton, "Wrong Username & Password");
}
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
JOptionPane.showMessageDialog(btnNewButton, "Database connection error: " + sqlException.getMessage());
}
}
}
//TO compile :- javac UserLogin.java
//To Run :- java UserLogin
//Make sure that the JDBC mysql connector must be installed in pc and also set the environment variable then
//Server.java
// A Java program for a Server
import java.net.*;
import java.io.*;
public class Server
{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public Server(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Server server = new Server(5000);
}
}
Client.java
// A Java program for a Client
import java.io.*;
import java.net.*;
public class Client {
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public Client(String address, int port)
{
// establish a connection
try {
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new DataInputStream(System.in);
// sends output to the socket
out = new DataOutputStream(
socket.getOutputStream());
}
catch (UnknownHostException u) {
System.out.println(u);
return;
}
catch (IOException i) {
System.out.println(i);
return;
}
// string to read message from input
String line = "";
// keep reading until "Over" is input
while (!line.equals("Over")) {
try {
line = input.readLine();
out.writeUTF(line);
}
catch (IOException i) {
System.out.println(i);
}
}
// close the connection
try {
input.close();
out.close();
socket.close();
}
catch (IOException i) {
System.out.println(i);
}
}
public static void main(String args[])
{
Client client = new Client("127.0.0.1", 5000);
}
}
Remote Interface (Adder.java)
This file defines the remote interface.
java
Copy code
import java.rmi.*;
public interface Adder extends Remote {
public int add(int x, int y) throws RemoteException;
}
Remote Object Implementation (AdderRemote.java)
This file provides the implementation of the remote interface.
java
Copy code
import java.rmi.*;
import java.rmi.server.*;
public class AdderRemote extends UnicastRemoteObject implements Adder {
AdderRemote() throws RemoteException {
super();
}
public int add(int x, int y) {
return x + y;
}
}
Server Application (MyServer.java)
This file contains the server that registers the remote object.
java
Copy code
import java.rmi.*;
import java.rmi.registry.*;
public class MyServer {
public static void main(String args[]) {
try {
Adder stub = new AdderRemote();
Naming.rebind("Adder", stub);
System.out.println("Server ready.");
} catch (Exception e) {
System.out.println(e);
}
}
}
Client Application (MyClient.java)
This file contains the client that invokes the remote method.
java
Copy code
import java.rmi.*;
public class MyClient {
public static void main(String args[]) {
try {
Adder stub = (Adder) Naming.lookup("rmi://localhost:5000/Adder");
System.out.println("Result: " + stub.add(34, 4));
} catch (Exception e) {
System.out.println(e);
}
}
}
Steps to Compile and Run the RMI Program
Compile all Java files:
bash
Copy code
javac *.java
Generate Stub and Skeleton (if using an older Java version, otherwise this step is not needed):
bash
Copy code
rmic AdderRemote
Start the RMI Registry (in a terminal):
bash
Copy code
rmiregistry 5000
Run the Server (in another terminal):
bash
Copy code
java MyServer
Run the Client (in yet another terminal):
bash
Copy code
java MyClient
Text Field
import javax.swing.*;
class TextFieldExample {
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Java.");
t1.setBounds(50,100,200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150,200,30);
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Button
import javax.swing.*;
public class ButtonExample
{
public static void main(String[] args)
{
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Check Box
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample()
{
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}
Radio Button
import javax.swing.*;
public class RadioButtonExample
{
JFrame f;
RadioButtonExample()
{
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args)
{
new RadioButtonExample();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class JToggleButtonTest extends JFrame implements ItemListener {
private JToggleButton jtb;
JToggleButtonTest() {
setTitle("JToggleButton Test");
setLayout(new FlowLayout());
setJToggleButton();
setAction();
setSize(450, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void setJToggleButton() {
jtb = new JToggleButton("ON");
add(jtb);
}
private void setAction() {
jtb.addItemListener(this);
}
public void itemStateChanged(ItemEvent eve) {
if (jtb.isSelected())
jtb.setText("OFF");
else
jtb.setText("ON");
}
}
public class MainApp {
public static void main(String[] args) {
new JToggleButtonTest();
}
}
import java.awt.*;
import java.sql.*;
import javax.swing.*;
import java.awt.event.*;
public class UserLogin extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField textField;
private JPasswordField passwordField;
private JButton btnNewButton;
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
UserLogin frame = new UserLogin();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
});
}
public UserLogin() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(450, 190, 1014, 597);
setResizable(false);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Login");
lblNewLabel.setForeground(Color.BLACK);
lblNewLabel.setFont(new Font("Times New Roman", Font.PLAIN, 46));
lblNewLabel.setBounds(423, 13, 273, 93);
contentPane.add(lblNewLabel);
textField = new JTextField();
textField.setFont(new Font("Tahoma", Font.PLAIN, 32));
textField.setBounds(481, 170, 281, 68);
contentPane.add(textField);
textField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setFont(new Font("Tahoma", Font.PLAIN, 32));
passwordField.setBounds(481, 286, 281, 68);
contentPane.add(passwordField);
JLabel lblUsername = new JLabel("Username");
lblUsername.setForeground(Color.BLACK);
lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 31));
lblUsername.setBounds(250, 166, 193, 52);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setForeground(Color.BLACK);
lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 31));
lblPassword.setBounds(250, 286, 193, 52);
contentPane.add(lblPassword);
btnNewButton = new JButton("Login");
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 26));
btnNewButton.setBounds(545, 392, 162, 73);
btnNewButton.addActionListener(e -> loginUser());
contentPane.add(btnNewButton);
}
private void loginUser() {
String userName = textField.getText();
char[] password = passwordField.getPassword();
String passwordStr = new String(password); // Convert char[] to String
try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/swing_demo", "root", "aayushmysql4437")) {
// Show dialog that connection is successful
JOptionPane.showMessageDialog(btnNewButton, "Connection to database successful!");
// Prepare statement to check username and password
try (PreparedStatement st = connection.prepareStatement("SELECT name FROM Login WHERE name=? AND password=?")) {
st.setString(1, userName);
st.setString(2, passwordStr);
ResultSet rs = st.executeQuery();
if (rs.next()) {
dispose();
//UserHome ah = new UserHome(userName);
//ah.setTitle("Welcome");
//ah.setVisible(true);
JOptionPane.showMessageDialog(btnNewButton, "You have successfully logged in");
} else {
JOptionPane.showMessageDialog(btnNewButton, "Wrong Username & Password");
}
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
JOptionPane.showMessageDialog(btnNewButton, "Database connection error: " + sqlException.getMessage());
}
}
}
//TO compile :- javac UserLogin.java
//To Run :- java UserLogin
//Make sure that the JDBC mysql connector must be installed in pc and also set the environment variable then
//Server.java
// A Java program for a Server
import java.net.*;
import java.io.*;
public class Server
{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public Server(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Server server = new Server(5000);
}
}
Client.java
// A Java program for a Client
import java.io.*;
import java.net.*;
public class Client {
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public Client(String address, int port)
{
// establish a connection
try {
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new DataInputStream(System.in);
// sends output to the socket
out = new DataOutputStream(
socket.getOutputStream());
}
catch (UnknownHostException u) {
System.out.println(u);
return;
}
catch (IOException i) {
System.out.println(i);
return;
}
// string to read message from input
String line = "";
// keep reading until "Over" is input
while (!line.equals("Over")) {
try {
line = input.readLine();
out.writeUTF(line);
}
catch (IOException i) {
System.out.println(i);
}
}
// close the connection
try {
input.close();
out.close();
socket.close();
}
catch (IOException i) {
System.out.println(i);
}
}
public static void main(String args[])
{
Client client = new Client("127.0.0.1", 5000);
}
}
Remote Interface (Adder.java)
This file defines the remote interface.
java
Copy code
import java.rmi.*;
public interface Adder extends Remote {
public int add(int x, int y) throws RemoteException;
}
Remote Object Implementation (AdderRemote.java)
This file provides the implementation of the remote interface.
java
Copy code
import java.rmi.*;
import java.rmi.server.*;
public class AdderRemote extends UnicastRemoteObject implements Adder {
AdderRemote() throws RemoteException {
super();
}
public int add(int x, int y) {
return x + y;
}
}
Server Application (MyServer.java)
This file contains the server that registers the remote object.
java
Copy code
import java.rmi.*;
import java.rmi.registry.*;
public class MyServer {
public static void main(String args[]) {
try {
Adder stub = new AdderRemote();
Naming.rebind("Adder", stub);
System.out.println("Server ready.");
} catch (Exception e) {
System.out.println(e);
}
}
}
Client Application (MyClient.java)
This file contains the client that invokes the remote method.
java
Copy code
import java.rmi.*;
public class MyClient {
public static void main(String args[]) {
try {
Adder stub = (Adder) Naming.lookup("rmi://localhost:5000/Adder");
System.out.println("Result: " + stub.add(34, 4));
} catch (Exception e) {
System.out.println(e);
}
}
}
Steps to Compile and Run the RMI Program
Compile all Java files:
bash
Copy code
javac *.java
Generate Stub and Skeleton (if using an older Java version, otherwise this step is not needed):
bash
Copy code
rmic AdderRemote
Start the RMI Registry (in a terminal):
bash
Copy code
rmiregistry 5000
Run the Server (in another terminal):
bash
Copy code
java MyServer
Run the Client (in yet another terminal):
bash
Copy code
java MyClient