Lab 11: Java Swing in Action

LAB OBJECTIVE: To gain the ability to create graphical user interface (GUI) components and build desktop applications.

javax.swing in Java

Provides a set of “lightweight” (all-Java language) components that, to the maximum degree possible, work the same on all platforms.

AWT components are platform dependent. Swing components are made in purely java and they are platform-independent. Swing components are called “lightweight” because they do not require a native OS object to implement their functionality. JDialog and JFrame are heavyweight because they do have a peer.

Swing Application in Java

// save as 
/\*Usually you will require both swing and awt packages
  even if you are working with just swings.
 \*/
import javax.swing.\*;
import java.awt.\*;
class SwingGui {
    public static void main(String args\[\]) {

        //Creating the Frame
        JFrame frame = new JFrame("Chat Frame for Rstians");
        frame.setDefaultCloseOperation(JFrame.EXIT\_ON\_CLOSE);
        frame.setSize(400, 400);

        //Creating the MenuBar and adding components
        JMenuBar mb = new JMenuBar();
        JMenu m1 = new JMenu("FILE");
        JMenu m2 = new JMenu("Help");
        mb.add(m1);
        mb.add(m2);
        JMenuItem m11 = new JMenuItem("Open");
        JMenuItem m22 = new JMenuItem("Save as");
        m1.add(m11);
        m1.add(m22);

        //Creating the panel at bottom and adding components
        JPanel panel = new JPanel(); // the panel is not visible in output
        JLabel label = new JLabel("Enter Text");
        JTextField tf = new JTextField(10); // accepts upto 10 characters
        JButton send = new JButton("Send");
        JButton reset = new JButton("Reset");
        panel.add(label); // Components Added using Flow Layout
        panel.add(tf);
        panel.add(send);
        panel.add(reset);

        // Text Area at the Center
        JTextArea ta = new JTextArea();

        //Adding Components to the frame.
        frame.add(BorderLayout.SOUTH, panel);
        frame.add(BorderLayout.NORTH, mb);
        frame.add(BorderLayout.CENTER, ta);
        frame.setVisible(true);
    }
}
/\*
F:\\coreJAVA\\image>javac SwingGui.java

F:\\coreJAVA\\image>java SwingGui
\*/

Output

(https://mgmt.rstforum.net/uploads/media-1701516651712.png)