chapter 11.2
TRANSCRIPT
CUSTOMIZING FRAME WINDOWS
Chapter 11.2:
Frames Frame is a window that is not contained inside
another window.
Frame is the basis to contain other user interface components in Java GUI applications.
The Frame class can be used to create windows. The Frame class contains rudimentary functionalities to support features found in any frame window.
For Swing GUI programs, use JFrame class to create windows.
Two Ways to Create a Window Using JFrame First approach
Declare & Create object of type JFrame Use various methods to manipulate window
Second approach Create class containing application program by extending
definition of class JFrame Utilizes mechanism of inheritance
Creating Frames
1) First approach:
import javax.swing.*;public class MyFrame
{ public static void main(String[] args) { JFrame frame = new JFrame(“MyFrame"); frame.setSize(400, 300); frame.setVisible(true); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); }
}
Creating Framesimport javax.swing.*;public class MyFrame { public static void main(String[] args) { JFrame frame = new JFrame(“MyFrame"); frame.setSize(400, 300); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
300
400setVisible() and setSize() – methods in Component class
setDefaultCloseOperation(EXIT_ON_CLOSE) - terminate when the frame isclosed
Creating Frames
2) Second approach:
import javax.swing.*;public class MyFrame extends JFrame{
public MyFrame() { setTitle(“MyFrame"); setSize(400, 300); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); }
public static void main(String[] args) { MyFrame myFrame = new MyFrame(); }
}
The Content Pane of a Frame The content pane is where we put GUI objects such as
buttons, labels, scroll bars, and others. We access the content pane by calling the frame’s
getContentPane method.
This gray area is the content pane of this frame.
This gray area is the content pane of this frame.
Changing the Background Color
Here's how we can change the background color of a content pane to blue:
Container contentPane = getContentPane();
contentPane.setBackground(Color.BLUE);
Placing GUI Objects on a Frame
There are two ways to put GUI objects on the content pane of a frame:Use a layout manager
○ FlowLayout○ BorderLayout○ GridLayout○ others
Use absolute positioning○ null layout manager
Placing a Button A JButton object a GUI component that represents a
pushbutton. Here's an example of how we place a button with
FlowLayout.
contentPane.setLayout(
new FlowLayout());
JButton okButton
= new JButton("OK");
JButton cancelButton
= new JButton("CANCEL");
contentPane.add(okButton);
contentPane.add(cancelButton);