Pages

Explore Advanced Java Concepts: Complete Code Examples & Learning Resources

Explore advanced Java programming with 20 practical code examples, covering GUI, JDBC, Servlets, and more. Enhance your skills today!
Advanced Java Programs

Advanced Java Programs

1. Login Form Using AWT Components


import java.awt.*;
import java.awt.event.*;

public class LoginFormAWT extends Frame implements ActionListener {
    TextField username, password;
    Label l1, l2, msg;
    Button login;

    LoginFormAWT() {
        setTitle("Login Form");
        setSize(300, 200);
        setLayout(new FlowLayout());

        l1 = new Label("Username:");
        l2 = new Label("Password:");
        username = new TextField(20);
        password = new TextField(20);
        password.setEchoChar('*');

        login = new Button("Login");
        login.addActionListener(this);

        add(l1); add(username);
        add(l2); add(password);
        add(login);

        msg = new Label();
        add(msg);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        msg.setText("Logged in as: " + username.getText());
    }

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

2. Form Using List and Choice


import java.awt.*;

public class ListChoiceFormAWT extends Frame {
    List languageList;
    Choice countryChoice;

    ListChoiceFormAWT() {
        setTitle("List and Choice Form");
        setSize(300, 200);
        setLayout(new FlowLayout());

        languageList = new List(3);
        languageList.add("Java");
        languageList.add("C++");
        languageList.add("Python");

        countryChoice = new Choice();
        countryChoice.add("India");
        countryChoice.add("USA");
        countryChoice.add("UK");

        add(new Label("Select Language:"));
        add(languageList);
        add(new Label("Select Country:"));
        add(countryChoice);

        setVisible(true);
    }

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

3. Simple Calculator Using GridLayout


import java.awt.*;
import java.awt.event.*;

public class CalculatorGridLayout extends Frame implements ActionListener {
    TextField display;
    Button[] numButtons;
    Button add, sub, mul, div, eq;
    double num1, num2, result;
    String operator;

    CalculatorGridLayout() {
        setTitle("Simple Calculator");
        setLayout(new GridLayout(4, 4));
        display = new TextField();
        add(display);

        numButtons = new Button[10];
        for (int i = 0; i < 10; i++) {
            numButtons[i] = new Button(String.valueOf(i));
            numButtons[i].addActionListener(this);
            add(numButtons[i]);
        }

        add = new Button("+"); add.addActionListener(this);
        sub = new Button("-"); sub.addActionListener(this);
        mul = new Button("*"); mul.addActionListener(this);
        div = new Button("/"); div.addActionListener(this);
        eq = new Button("="); eq.addActionListener(this);

        add(add); add(sub); add(mul); add(div); add(eq);

        setSize(300, 300);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        if (command.charAt(0) >= '0' && command.charAt(0) <= '9') {
            display.setText(display.getText() + command);
        } else if (command.equals("+") || command.equals("-") || command.equals("*") || command.equals("/")) {
            num1 = Double.parseDouble(display.getText());
            operator = command;
            display.setText("");
        } else if (command.equals("=")) {
            num2 = Double.parseDouble(display.getText());
            switch (operator) {
                case "+": result = num1 + num2; break;
                case "-": result = num1 - num2; break;
                case "*": result = num1 * num2; break;
                case "/": result = num1 / num2; break;
            }
            display.setText(String.valueOf(result));
        }
    }

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

4. Card Deck Using CardLayout


import java.awt.*;
import java.awt.event.*;

public class CardLayoutExample extends Frame implements ActionListener {
    CardLayout card;
    Button b1, b2, b3;
    Panel cardPanel;

    CardLayoutExample() {
        setTitle("CardLayout Example");
        card = new CardLayout(40, 30);
        cardPanel = new Panel();
        cardPanel.setLayout(card);

        b1 = new Button("Panel 1");
        b2 = new Button("Panel 2");
        b3 = new Button("Panel 3");

        Panel p1 = new Panel();
        p1.add(new Label("This is Panel 1"));
        Panel p2 = new Panel();
        p2.add(new Label("This is Panel 2"));
        Panel p3 = new Panel();
        p3.add(new Label("This is Panel 3"));

        cardPanel.add(p1, "Panel 1");
        cardPanel.add(p2, "Panel 2");
        cardPanel.add(p3, "Panel 3");

        add(cardPanel);
        setLayout(new FlowLayout());

        b1.addActionListener(this);
        b2.addActionListener(this);
        b3.addActionListener(this);

        add(b1);
        add(b2);
        add(b3);

        setSize(400, 400);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        card.next(cardPanel);
    }

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

5. Menu Bar with Submenu (AWT)

5. Menu Bar with Submenu (AWT)


import java.awt.*;
import java.awt.event.*;

public class MenuBarAWTExample extends Frame {
    MenuBar menuBar;
    Menu fileMenu, editMenu, viewMenu;
    MenuItem newItem, openItem, exitItem;

    MenuBarAWTExample() {
        setTitle("Menu Bar Example");
        setSize(400, 300);
        
        menuBar = new MenuBar();

        fileMenu = new Menu("File");
        newItem = new MenuItem("New");
        openItem = new MenuItem("Open");
        exitItem = new MenuItem("Exit");

        fileMenu.add(newItem);
        fileMenu.add(openItem);
        fileMenu.add(exitItem);

        editMenu = new Menu("Edit");
        viewMenu = new Menu("View");

        menuBar.add(fileMenu);
        menuBar.add(editMenu);
        menuBar.add(viewMenu);

        setMenuBar(menuBar);

        setVisible(true);
    }

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

6. Swing Applet with ScrollPane and JComboBox

6. Swing Applet with ScrollPane and JComboBox


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

public class ScrollComboBoxApplet extends JApplet {
    public void init() {
        String[] languages = { "English", "Marathi", "Hindi", "Sanskrit" };
        JComboBox comboBox = new JComboBox<>(languages);

        JTextArea textArea = new JTextArea(5, 20);
        JScrollPane scrollPane = new JScrollPane(textArea);

        add(comboBox, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
    }
}

7. JTree Example

7. JTree Example


import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;

public class JTreeExample extends JFrame {
    public JTreeExample() {
        setTitle("JTree Example");

        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
        DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child 1");
        DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child 2");

        root.add(child1);
        root.add(child2);

        JTree tree = new JTree(root);
        add(new JScrollPane(tree));

        setSize(300, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

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

8. JTable Example

8. JTable Example


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

public class JTableExample extends JFrame {
    public JTableExample() {
        setTitle("JTable Example");

        String[][] data = {
            { "1", "John", "25" },
            { "2", "Anna", "30" },
            { "3", "Paul", "28" }
        };

        String[] columnNames = { "ID", "Name", "Age" };

        JTable table = new JTable(data, columnNames);
        add(new JScrollPane(table), BorderLayout.CENTER);

        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

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

9. JProgressBar Example

9. JProgressBar Example


import javax.swing.*;

public class JProgressBarExample extends JFrame {
    JProgressBar progressBar;

    JProgressBarExample() {
        setTitle("JProgressBar Example");
        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);

        add(progressBar);

        setSize(400, 100);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);

        fillProgressBar();
    }

    private void fillProgressBar() {
        int i = 0;
        try {
            while (i <= 100) {
                progressBar.setValue(i);
                Thread.sleep(100);
                i += 5;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

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

10. Handling Key Events in Applet

10. Handling Key Events in Applet


import java.awt.*;
import java.awt.event.*;

public class KeyEventApplet extends Applet implements KeyListener {
    String msg = "";

    public void init() {
        addKeyListener(this);
    }

    public void keyPressed(KeyEvent ke) {
        msg = "Key Pressed: " + ke.getKeyChar();
        repaint();
    }

    public void keyReleased(KeyEvent ke) {
        msg = "Key Released: " + ke.getKeyChar();
        repaint();
    }

    public void keyTyped(KeyEvent ke) {
        msg = "Key Typed: " + ke.getKeyChar();
        repaint();
    }

    public void paint(Graphics g) {
        g.drawString(msg, 20, 50);
    }
}

11. Handling Mouse Events with MouseListener


import java.awt.*;
import java.awt.event.*;

public class MouseEventExample extends Frame implements MouseListener {
    String msg = "";

    MouseEventExample() {
        addMouseListener(this);
        setSize(300, 300);
        setVisible(true);
    }

    public void mouseClicked(MouseEvent e) {
        msg = "Mouse Clicked";
        repaint();
    }

    public void mouseEntered(MouseEvent e) {
        msg = "Mouse Entered";
        repaint();
    }

    public void mouseExited(MouseEvent e) {
        msg = "Mouse Exited";
        repaint();
    }

    public void mousePressed(MouseEvent e) {
        msg = "Mouse Pressed";
        repaint();
    }

    public void mouseReleased(MouseEvent e) {
        msg = "Mouse Released";
        repaint();
    }

    public void paint(Graphics g) {
        g.drawString(msg, 50, 50);
    }

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

12. Login Form Using JTextField and JPasswordField (Swing)


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

public class LoginFormExample extends JFrame implements ActionListener {
    JTextField usernameField;
    JPasswordField passwordField;

    LoginFormExample() {
        setTitle("Login Form");
        setLayout(new GridLayout(3, 2));

        JLabel usernameLabel = new JLabel("Username:");
        JLabel passwordLabel = new JLabel("Password:");

        usernameField = new JTextField();
        passwordField = new JPasswordField();

        JButton loginButton = new JButton("Login");
        loginButton.addActionListener(this);

        add(usernameLabel);
        add(usernameField);
        add(passwordLabel);
        add(passwordField);
        add(loginButton);

        setSize(300, 150);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        String username = usernameField.getText();
        String password = new String(passwordField.getPassword());
        System.out.println("Username: " + username);
        System.out.println("Password: " + password);
    }

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

13. Handling KeyPressed, KeyReleased, KeyTyped in Applet


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class KeyEventApplet extends Applet implements KeyListener {
    String msg = "";

    public void init() {
        addKeyListener(this);
        setFocusable(true);
        requestFocus();
    }

    public void keyPressed(KeyEvent e) {
        msg = "Key Pressed: " + e.getKeyChar();
        repaint();
    }

    public void keyReleased(KeyEvent e) {
        msg = "Key Released: " + e.getKeyChar();
        repaint();
    }

    public void keyTyped(KeyEvent e) {
        msg = "Key Typed: " + e.getKeyChar();
        repaint();
    }

    public void paint(Graphics g) {
        g.drawString(msg, 20, 50);
    }
}

14. Handling MouseMotionListener Events


import java.awt.*;
import java.awt.event.*;

public class MouseMotionListenerExample extends Frame implements MouseMotionListener {
    String msg = "";

    MouseMotionListenerExample() {
        addMouseMotionListener(this);
        setSize(400, 300);
        setVisible(true);
    }

    public void mouseDragged(MouseEvent e) {
        msg = "Mouse Dragged at: " + e.getX() + ", " + e.getY();
        repaint();
    }

    public void mouseMoved(MouseEvent e) {
        msg = "Mouse Moved at: " + e.getX() + ", " + e.getY();
        repaint();
    }

    public void paint(Graphics g) {
        g.drawString(msg, 50, 50);
    }

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

15. Use of WindowAdapter Class


import java.awt.*;
import java.awt.event.*;

public class WindowAdapterExample extends Frame {
    WindowAdapterExample() {
        setTitle("Window Adapter Example");
        setSize(300, 200);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            }
        });
        setVisible(true);
    }

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

16. Arithmetic Operations in Applet


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class ArithmeticApplet extends Applet implements ActionListener {
    TextField num1, num2, result;
    Button addButton, subButton;

    public void init() {
        num1 = new TextField(5);
        num2 = new TextField(5);
        result = new TextField(5);
        result.setEditable(false);
        
        addButton = new Button("Add");
        subButton = new Button("Subtract");
        
        add(num1);
        add(num2);
        add(addButton);
        add(subButton);
        add(result);
        
        addButton.addActionListener(this);
        subButton.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
        int number1 = Integer.parseInt(num1.getText());
        int number2 = Integer.parseInt(num2.getText());

        if (e.getSource() == addButton) {
            result.setText(String.valueOf(number1 + number2));
        } else if (e.getSource() == subButton) {
            result.setText(String.valueOf(number1 - number2));
        }
    }
}

17. Use of InetAddress Class


import java.net.*;

public class InetAddressExample {
    public static void main(String[] args) {
        try {
            InetAddress ip = InetAddress.getLocalHost();
            System.out.println("Current IP address: " + ip.getHostAddress());
            System.out.println("Host Name: " + ip.getHostName());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

18. Use of URL and URLConnection


import java.io.*;
import java.net.*;

public class URLConnectionExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://www.example.com");
            URLConnection urlConnection = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

19. Database Interaction with JDBC


import java.sql.*;

public class JDBCExample {
    public static void main(String[] args) {
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "username", "password");
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM users");

            while (rs.next()) {
                System.out.println("User ID: " + rs.getInt("id"));
                System.out.println("Username: " + rs.getString("username"));
            }
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

20. Servlet Program for Authentication


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        PrintWriter out = response.getWriter();
        response.setContentType("text/html");

        if ("admin".equals(username) && "admin123".equals(password)) {
            out.println("

Login Successful

"); } else { out.println("

Invalid Credentials

"); } } }

Post a Comment

Solved Manual

© CAMPUS ACADEMY . All rights reserved. DMCA.com Protection Status

Ads

Capstone Project Offer!

Grab the best Capstone Projects to showcase your skills and stand out!

Limited Time Special Offer - Hurry Up!