This is a Java Program to Display a Message in a New Frame
Problem Description
We have to write a program in Java such that it creates a frame with a button. When the button is clicked, a message is displayed in a new frame.
Expected Input and Output
For displaying a message in a new frame, we can have the following different sets of input and output.
1. To View the Original Frame :
On every execution of the program, it is expected that a frame with a button is created.
2. To View the Message in a New Frame :
On click of the button, it is expected that "!!! Hello !!!" message is displayed in a new frame.
Problem Solution
1. Create the original frame and add a button to it.
2. Add ActionListener to the button.
3. Display the original frame.
4. When the button is clicked, create a new frame and add a message to the frame.
5. Display the new frame.
Program/Source Code
Here is source code of the Java Program to display a message in a new frame. The program is successfully compiled and tested using javac compiler on Fedora 30. The program output is also shown below.
/* Java Program to Display a Message in a New Frame */ import javax.swing.*; import java.awt.event.*; import java.awt.*; class Message implements ActionListener { //Function to create the original frame public static void main(String args[]) { //Create a frame JFrame frame = new JFrame("Original Frame"); frame.setSize(300,300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create an object Message obj = new Message(); //Create a button to view message JButton button = new JButton("View Message"); frame.add(button); button.addActionListener(obj); //View the frame frame.setVisible(true); } //Function to create a new frame with message public void actionPerformed(ActionEvent e) { //Create a new frame JFrame sub_frame = new JFrame("Sub Frame"); sub_frame.setSize(200,200); //Display the message JLabel label = new JLabel("!!! Hello !!!"); sub_frame.add(label); //View the new frame sub_frame.setVisible(true); } }
Program Explanation
1. To create a frame, use the JFrame class.
2. To create a button, use the JButton class.
3. Add ActionListener to the button.
Runtime Test Cases
Here’s the run time test cases to display message a in new frame for different input cases.
Test case 1 – To View the Original Frame.
Test case 2 – To View the Message in New Frame.