Building Guis in Java: Running Even When The Jframe Is Closed
Building Guis in Java: Running Even When The Jframe Is Closed
GUIs
Containers
To build a GUI, elements called containers such as frames and panels are needed. These containers
let you show and organize other GUI elements onscreen.
Panel
A panel is rectangular area that can contain various GUI elements.
However, a panel cannot stand alone. It has to be placed in another container such as a frame
or within another panel.
import java.awt.*;
import javax.swing.*;
panel1.setBackground(Color.YELLOW);
panel2.setBackground(Color.GREEN);
panel1.add(label1);
panel2.add(label2);
panel1.add(panel2);
frame1.setContentPane(panel1);
frame1.pack();
frame1.show();
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Note: When the class Sample1GUI is executed using the command prompt, Java will still be
running even when the JFrame is closed.
Intermediate Programming LAB 2
GUIs
Program Analysis:
1. The java.awt.* package contains classes that will be used for background colors.
2. The javax.swing.* package contains classes that will be used for GUI elements.
3. JFrame is used to create a frame; JPanel is used to create panels.
4. JLabel is a GUI elements that can contain texts and graphics.
5. The command frame1.setContentPAne(panel1) will place panel1 within JFrame frame1 and
make it the JPanel that will contain other elements that we wish to add to JFrame.
6. The pack() method automatically resizes the JFrame to show the elements that are
contained within it.
7. When a JFrame is created, it already resides in the memory of the computer. The show()
method makes JFrame visible.
import java.awt.*;
import javax.swing.*;
textpanel1.setBackground(Color.white);
textpanel2.setBackground(Color.white);
textpanel1.add(label1);
textpanel1.add(text1);
textpanel2.add(label2);
textpanel2.add(text2);
FormPanel.setLayout(new GridLayout(3,1));
FormPanel.add(textpanel1);
FormPanel.add(textpanel2);
FormPanel.add(button1);
frame2.setContentPane(FormPanel);
frame2.pack();
Intermediate Programming LAB 3
GUIs
frame2.show();
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setResizable(false);
}
}
Program Analysis:
1. The setLayout() method tells Java that the JPanel FormPanel will be divided into grids.
2. The setResizable(false) method makes resizing the JFrame created impossible.