1. As in the AWT, starting point for graphical applications.
2. One of few Swing components that is built on an underlying "heavyweight" window.
3. Main differences in use compared to Frame:
- Components go in the "content pane", not directly in the frame. Changing other properties (layout manager, background color, etc.) also apply to the content pane. Access content pane via
getContentPane
, or if you want to replace the content pane with your container (e.g. a JPanel
), use setContentPane
. JFrames
close automatically when you click on the close button (unlike AWT Frames
). However, closing the last JFrame does not result in your program exiting Java. So your "main" JFrame
still needs a WindowListener
. - You get Java (Metal) look by default, so you have to explicitly switch if you want native look.
4. JFrame Example: Source Code
This shows the steps required to imitate what you would get in the AWT if you popped up a simple
Frame
, set the layout manager to
FlowLayout
, and dropped three buttons into it.
JFrameExample.java (Download source code)
import java.awt.*;
import javax.swing.*;
public class JFrameExample {
public static void main(String[] args) {
WindowUtilities.setNativeLookAndFeel();
JFrame f = new JFrame("This is a test");
f.setSize(400, 150);
Container content = f.getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(new JButton("Button 1"));
content.add(new JButton("Button 2"));
content.add(new JButton("Button 3"));
f.addWindowListener(new ExitListener());
f.setVisible(true);
}
}
Note: also requires
WindowUtilities.java, shown earlier.
ExitListener.java (Download source code)
import java.awt.*;
import java.awt.event.*;
public class ExitListener extends WindowAdapter {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
}
5. JFrame Example: Result
http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JFrame.html
No comments:
Post a Comment