Java Swing Application to display the given message

Let us create a simple application to display the message in the text field to a separate screen.

What are the components you need?

  • ·       A frame
  • ·       A Panel
  • ·       Label
  • ·       Text field
  • ·       Submit button.

These the Swing components used in the program.

Let us implement the sample application.

Program implementation:

  • First, include the built-in packages javax.swing,java.awt,java.awt.event.
  • Create a public class with main() function.
  • Design the components as follows.
  • A frame ,A Panel , Label , Text field and a submit button. Let us make objects for each components.
  • Set the frame object’s heading as “Display the message”. Jpanel object p1 is created.
  • Label object is created with the message “Enter the message”. It makes the user to enter the message.
  • TextField object is declared with size of 15.
  • A button object is initialised with button name as “Submit”.
  • Let us make the components into a row. Set the layout as Flow layout.
  • Add the textfield,button and label into the panel.
  • When you enter the message in the text field and click the submit button,it calls this part of the program.
  • This part gets the string into msg variable.
  • It displays the message in a separate window.

Program:

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class SampleApp {

    public static void main(String[] args) {

        JFrame f1 = new JFrame("Display the Message");

        JPanel p1 = new JPanel();

        JLabel l1 = new JLabel("Enter the message:");

        JTextField txtField = new JTextField(15);

        JButton button1 = new JButton("Submit");

        p1.setLayout(new FlowLayout()); // Arranging all components in a row

        p1.add(l1);

        p1.add(txtField);

        p1.add(button1);

       //button event

        button1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                String msg = txtField.getText();

                JOptionPane.showMessageDialog(f1, "Hi, your message is : " + msg + "!");

            }

        });

        f1.add(p1);

        f1.setSize(250, 150);

        f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        f1.setVisible(true);

    }

}

Here is the output.

 

That’s all. A sample swing application is created here. Hope this code is useful to you.

No comments:

Post a Comment