Вы находитесь на странице: 1из 18

1.

JFrame
JFrame is a Swing’s top-level container that renders a window on screen. A frame is a base
window on which other components rely, such as menu bar, panels, labels, text fields, buttons,
etc. Almost every Swing application starts with JFrame window.

To create and display a JFrame, we need to do the following:

 Create a JFrame object.


 Make it visible.

To create a JFrame object, we can use the constructors of the JFrame class.

Constructor Description
JFrame() It constructs a new frame that is initially invisible.
It creates a Frame in the specified GraphicsConfiguration
JFrame(GraphicsConfiguration gc)
of a screen device and a blank title.
It creates a new, initially invisible Frame with the
JFrame(String title)
specified title.
JFrame(String title, It creates a JFrame with the specified title and the
GraphicsConfiguration gc) specified GraphicsConfiguration of a screen device.
Ex
JFrame frame = new JFrame("Swing"); // Create a JFrame object

In the above code we use the constructor which takes a string. The string value will be
displayed as the title for the JFrame.

Classes representing Swing components are in the javax.swing package, so is the JFrame class.

Show a JFrame

When we create a JFrame object, by default, it is not visible. We have to call its
setVisible(boolean visible) method to make it visible. true parameter makes the frame visible,
to hide the frame pass false to the setVisible method.

To Make the JFrame visible on the screen

frame.setVisible(true);
Exit a Swing application

We can define one of the four behaviors of a JFrame to determine what happens when the
JFrame is closed.

The constants are defined in the javax.swing.WindowsConstants interface.

The JFrame class implements the WindowsConstants interface. We can reference all these
constants using JFrame.CONSTANT_NAME syntax or we can use the
WindowsConstants.CONSTANT_NAME syntax.

The four constants are

 DO_NOTHING_ON_CLOSE
do not do anything when the user closes a JFrame.
 HIDE_ON_CLOSE
hides a JFrame when the user closes it. This is the default behavior. The JFrame is
invisible but the program is still running.
 DISPOSE_ON_CLOSE
hides and disposes of the JFrame when the user closes it. Disposing a JFrame releases
any resources used by it.
 EXIT_ON_CLOSE
exits the application. This option will exit the application.

We can set the default close behavior of a JFrame by passing one of the four constants to its
setDefaultCloseOperation() method.

The following code shows how to exit the application when the JFrame is closed

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JFrame Size

We need to set the size and position of your JFrame to show its content area.

The size of a frame is defined by its width and height in pixels and we can set them using
setSize(int width, int height) method.

The position is defined by the (x, y) coordinates in pixels of the top-left corner of the JFrame
with respect to the top-left corner of the screen.

By default, its position is set to (0, 0) and this is the reason the JFrame was displayed at the top-
left corner of the screen.
We can set the (x, y) coordinates of the JFrame using its setLocation(int x, int y) method.

To set its size and position in one step, use its setBounds(int x, int y, int width, int height)
method

EX

import java.awt.*;
import javax.swing.*;
public class JFrameDemo
{
public static void main(String args[])
{
JFrame f1=new JFrame("example frame");
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setSize(500,500);
f1.setVisible(true);
}
}
Output:

2.JButton:

A JButton is also known as a push button. The user presses or clicks a JButton to perform an
action.

Create JButton

JButton can display text and an icon. We can use constructors listed in the following table to
create a JButton.

Constructor Description
JButton() Creates a JButton without any label or icon.
JButton(String text) Creates a JButton and sets the specified text as its label.
JButton(Icon icon) Creates a JButton with an icon and no label.
JButton(String text, Icon icon) Creates a JButton with the specified label and icon.
JButton(Action action) Creates a JButton with an Action object.

We can create a JButton with its text as OK in the following code.

JButton closeButton = new JButton("OK");


import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

public class testswing extends JFrame

testswing()

JButton bt1 = new JButton("Yes"); //Creating a Yes Button.

JButton bt2 = new JButton("No"); //Creating a No Button.

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting close operation.

setLayout(new FlowLayout()); //setting layout using FlowLayout object

setSize(400, 400); //setting size of Jframe

add(bt1); //adding Yes button to frame.

add(bt2); //adding No button to frame.

setVisible(true);

public static void main(String[] args)

new testswing();

}
Output:

3.JLabel:

A JLabel represents a label, i.e. a display area for non-editable text.

A JLabel can display both text and images. It can even render HTML tags so that you can create
a JLabel that displays multicolors or multiline text.

The javax.swing.JLabel class has the following constructors.

Constructor Description
Creates a JLabel instance with no image and with an
JLabel()
empty string for the title.
JLabel(String s) Creates a JLabel instance with the specified text.
JLabel(Icon i) Creates a JLabel instance with the specified image.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image,
horizontalAlignment) and horizontal alignment.
EX

import javax.swing.*;

class LabelExample

public static void main(String args[])

JFrame f= new JFrame("Label Example");

JLabel l1,l2;

l1=new JLabel("First Label.");

l1.setBounds(50,50, 100,30);

l2=new JLabel("Second Label.");

l2.setBounds(50,100, 100,30);

f.add(l1); f.add(l2);

f.setSize(300,300);

f.setLayout(null);

f.setVisible(true);

Output:
4.JTextField:

A JTextField can handle one line of plain text. Its constructors accept a combination of the
following three values.

 A string - specifies the initial text. Default to null.


 The number of columns - specifies the width. Default to 0.
 A Document object - specifies the model.

The document model is an instance of the PlainDocument class.

The following table lists constructors of the JTextField class.

ID Constructor/Description
JTextField()
1 Creates a JTextField with default values for initial text, number of
columns, and document.
JTextField(Document document, String text, int columns)
2 Creates a JTextField with the specified document as its model, text as its
initial text, and columns as its number of columns.
JTextField(int columns)
3
Creates a JTextField with the specified columns as its number of columns.
JTextField(String text)
4
Creates a JTextField with the specified text as its initial text.
JTextField(String text, int columns)
5 Creates a JTextField with the specified text as its initial text and columns
as its number of columns.
Ex

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

public class MyTextField extends JFrame

public MyTextField()

JTextField jtf = new JTextField(10); //creating JTextField.

add(jtf); //adding JTextField to frame.

setLayout(new FlowLayout());

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setSize(400, 400);

setVisible(true);

public static void main(String[] args)

new MyTextField();

Output:
4.JComboBox:
import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

public class Test extends JFrame

String name[] = {"Abhi","Adam","Alex","Ashkay"}; //list of name.

public Test()

JComboBox jc = new JComboBox(name); //initialzing combo box with list of name.

add(jc); //adding JComboBox to frame.

setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setSize(400, 400);

setVisible(true);

public static void main(String[] args)

new Test();

Output:

5.JTextArea

A JTextArea can handle multiline plain text.

A JTextArea does not provide scrolling by itself, we need to put JTextField to a JScrollPane to
have scrolling capability.

We can set the number of rows and columns for a JTextArea to set its preferred size.

The following table lists the constructors of the JTextArea Class.


ID Constructor/Description
JTextArea()
1 Creates a JTextArea with a default model, initial string as null, and
rows/columns as zero.
JTextArea(Document doc)
2 Creates a JTextArea with the specified doc as its model. Its initial string is set
to null, and rows/columns to zero.
JTextArea(Document doc, String text, int rows, int columns)
3 Creates a JTextArea with all its properties (model, initial text, rows, and
column) as specified in its arguments.
JTextArea(int rows, int columns)
4 Creates a JTextArea with a default model, initial string as null, and the
specified rows/columns.
JTextArea(String text)
5 Creates a JTextArea with the specified initial text. A default model is set and
rows/columns are set to zero.
JTextArea(String text, int rows, int columns)
6 Creates a JTextArea with the specified text, rows, and columns. A default
model is used.

The following code shows how to create JTextArea using different initial values.

To Create a blank JTextArea

JTextArea emptyTextArea = new JTextArea();

To create a JTextArea with 10 rows and 50 columns

JTextArea commentsTextArea = new JTextArea(10, 50);

To Create a JTextArea with 10 rows and 50 columns with an initial text of "Enter resume here"

JTextArea resumeTextArea = new JTextArea("Enter resume here", 10, 50);

To add the scrolling capability to a JTextArea, we add it to a JScrollPane.

The following code shows how to make a JTextArea scrollable

JTextArea resumeTextArea = new JTextArea("Enter resume here", 10, 50);


JScrollPane sp = new JScrollPane(resumeTextArea);
Container contentPane = myFrame.getContentPane();
import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}}
Output:

6.JPasswordField:

A JPasswordField is a JTextField and it hides the characters typed in.

We can set our own echo character by using its setEchoChar(char newEchoChar) method.
The JPasswordField class has the same set of constructors as the JTextField class.

We combine the initial text, the number of columns, and a Document object to create a
JPasswordField object.

To create a password field 10 characters wide

JPasswordField passwordField = new JPasswordField(10);

import javax.swing.*;

public class PasswordFieldExample {

public static void main(String[] args) {

JFrame f=new JFrame("Password Field Example");

JPasswordField value = new JPasswordField();

JLabel l1=new JLabel("Password:");

l1.setBounds(20,100, 80,30);

value.setBounds(100,100,100,30);

f.add(value); f.add(l1);

f.setSize(300,300);

f.setLayout(null);

f.setVisible(true);

Output:
7.JScrollPane

import java.awt.FlowLayout;

import javax.swing.JFrame;

import javax.swing.JScrollPane;

import javax.swing.JtextArea;

public class JScrollPaneExample

private static final long serialVersionUID = 1L;

private static void createAndShowGUI() {

final JFrame frame = new JFrame("Scroll Pane Example"); // Create and set up the window.

frame.setSize(500, 500); // Display the window.

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout()); // set flow layout for the frame
JTextArea textArea = new JTextArea(20, 20);

JScrollPane scrollableTextArea = new JScrollPane(textArea);

scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALW
AYS);

scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

frame.getContentPane().add(scrollableTextArea);

public static void main(String[] args) {

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run()

createAndShowGUI();

);

Output:
8. JPanel:
A panel in swing is similar to Panel in AWT, is a lightweight container that is designed to group a
set of components, including other panels. It is visually represented as window that does not
contain a title bar, menu bar or border. It is simplest of all the containers. Its default layout
manager is FlowLayout.

Panels are represented by objects created from JPanel class by calling the constructor.

public JPanel ()

After the panel has been created, other components can be added to JPanel object by calling its
add (component) method inherited from the Container class. The following code fragment
demonstrates creating a panel and adding two buttons to it.

JPanel p = new JPanel();

p. add (new JButton ("OK")) ;

p. add (new JButton ("Cancel") ) ;

import java.awt.*;

import javax.swing.*;
public class PanelExample {

PanelExample()

JFrame f= new JFrame("Panel Example");

JPanel panel=new JPanel();

panel.setBounds(40,80,200,200);

panel.setBackground(Color.gray);

JButton b1=new JButton("Button 1");

b1.setBounds(50,100,80,30);

b1.setBackground(Color.yellow);

JButton b2=new JButton("Button 2");

b2.setBounds(100,100,80,30);

b2.setBackground(Color.green);

panel.add(b1); panel.add(b2);

f.add(panel);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

public static void main(String args[])

new PanelExample();

}
}

Output:

Вам также может понравиться