JFrame Example
This JFrame example displays an untitled JFrame containing a label. The JFrame would be displayed in the upper left of the screen. It can be displayed in other parts of the screen, as shown in a later example. An import declaration for swing in this and other programs informs the compiler which package to look in for relevant classes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// JFrame Example
import javax.swing.*;
class JFrameExample {
public static void main(String[] args) {
JFrame jframe = new JFrame();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.getContentPane().add(new JLabel("bonbon"));
jframe.setSize(100,100);
jframe.setVisible(true);
}
}
8 This constructs a JFrame, which is a window that can contain the components you choose to put in it.
At this stage of execution the JFrame is not yet visible to the user.
10 You would normally have this line in your program since it enables the user to close the JFrame and exit the program.
12 The first part of the statement invokes the method getContentPane() which provides the content pane (actually a container) to which you add components.
The second part of the statement adds a label to the content pane.
14-15 These statements set the size of the JFrame and make it visible.
