Java Swing
Java Swing
JAVA PROGRAMMING
Swing Components
• Computer programs usually are more user friendly (and more fun to
use) when they contain user interface (UI) components.
• UI components are buttons, text fields, and other components with
which the user can interact.
• Swing components are UI elements such as dialog boxes and
buttons; you can usually recognize their names because they
begin with J.
• To use the Swing UI components and methods, insert the following
statement at the beginning of your program:
import javax.swing.*
JFrame Class
• A container is a type of component that holds other components so
you can treat a group of them as a single entity.
• A container takes the form of a window that you can drag, resize,
minimize, restore, and close.
• The Swing component JFrame, both allow you to create more useful
objects.
JFrame Class constructors
• JFrame() constructs a new frame that initially is invisible and has no title.
setBounds(int, int, int, int) Overrides the default behavior for the JFrame
to be positioned in the upper-left corner of the
computer screen’s desktop; the first two
arguments are the horizontal and vertical
positions of the JFrame’s upper-left corner on
the desktop, and the final two arguments set
the width and height
JFrame usage:
• Three constants are defined in the FlowLayout class that specify how
components are positioned in each row of their container. These
constants are FlowLayout.LEFT, FlowLayout.RIGHT, and
FlowLayout.CENTER.
FlowLayout usage:
or
myFrame.SetLayout(new FlowLayout();
Example:
import javax.swing.*;
import java.awt.*;
public class JFrame6 {
public static void main(String[] args) {
final int FRAME_WIDTH = 250;
final int FRAME_HEIGHT = 100;
To give a JLabel object a new font, you can create a Font object, as
in the following:
You can use the setFont() method to assign the Font to a JLabel with a
statement such as:
myFrame.setFont(myFont);
JTextField Class
• A JTextField is a component into which a user can type a single line
of text data.
• Typically, a user types a line into a JTextField and then presses Enter
on the keyboard or clicks a button with the mouse to enter the
data
JTextField Constructors
myFrame.add(response);
Some Methods of JTextField
response.setText("Thank you");
JButton(String text, Icon icon) creates a button with initial text and an icon
of type Icon or ImageIcon.
} Output: