Constructor | Description |
---|---|
public JFrame() | Creates a JFrame window with no name. |
public JFrame(String name) | Creates a JFrame window with a name. |
Methods | Description |
---|---|
public void add(Component comp) | This method adds the component, comp, to the container JFrame. |
public void setLayout(LayoutManager object) | This method sets the layout of the components in a container, JFrame. |
public void remove(Component comp) | This method removes a component, comp, from the container, JFrame. |
public void setSize(int widthPixel, int heightPixel) | This method sets the size of a JFrame in terms of pixels. |
public void setDefaultCloseOperation(int operation) | This method sets the operation that will take place when a a user clicks on close(x) button of this JFrame. An operation may take any of the values- DO_NOTHING_ON_CLOSE HIDE_ON_CLOSE DISPOSE_ON_CLOSE EXIT_ON_CLOSE |
public void setVisble(boolean b) | This method set the visibility of JFrame using boolean value. |
import javax.swing.*;
//import java.awt.*;
class SwingEx implements Runnable
{
public static void main(String...ar)
{
SwingUtilities.invokeLater(new SwingEx());
}
public void run()
{
new A();
}
}
class A
{
JFrame frame;
JLabel label;
JButton button;
A()
{
frame = new JFrame("JFrame");
label = new JLabel("Hello there, how are you today? :-)");
button = new JButton("Button1");
//Adding JLabel and JButton to JFrame, which will added to BorderLayout.CENTER region of JFrame.
frame.add(label);
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(210,250);
frame.setVisible(true);
}
}
In the last code, two components i.e JLabel and JButton are added to top-level container, JFrame, without calling its setLayout() method.
These components are added to BorderLayout.CENTER region of JFrame.
Hence, only the last component added, i.e. JButton will be visible.
When you run the code, you are presented a window that only shown a button.
import javax.swing.*;
//import java.awt.*;
class SwingEx implements Runnable
{
public static void main(String...ar)
{
SwingUtilities.invokeLater(new SwingEx());
}
public void run()
{
new A();
}
}
class A
{
JFrame frame;
JLabel label;
JButton button;
A()
{
frame = new JFrame("JFrame");
label = new JLabel("Hello there, how are you today? :-)");
button = new JButton("Button1");
//Setting the layout of components in JFrame to FlowLayout
frame.setLayout(new FlowLayout());
frame.add(label);
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(210,250);
frame.setVisible(true);
}
}
When you run the code, you are presented a window that contains a top-level container, JFrame, which includes two components that are positioned in JFrame using FlowLayout manager -
Coming Next
-
JSP & Servlets