Sie sind auf Seite 1von 10

Chapter Seven

Java GUIs
7.1 Introduction
A graphical user interface (GUI) presents a user-friendly mechanism for interacting with an
application. A GUI (pronounced "GOO-ee") gives an application a distinctive "look" and "feel."
Providing different applications with consistent, intuitive user interface components allows users to
be somewhat familiar with an application, so that they can learn it more quickly and use it more
productively.
7.2 Overview of Swing Components
Though it is possible to perform input and output using the JOptionPane dialogs presented and
some other classes, most GUI applications require more elaborate, customized user interfaces. The
remainder of this chapter discusses many GUI components that enable application developers to
create robust GUIs. Most Swing components are pure Java components they are written,
manipulated and displayed completely in Java. They are part of the Java Foundation Classes
(JFC)Java's libraries for cross-platform GUI development.
There are actually two sets of GUI components in Java. Before Swing was introduced in J2SE 1.2,
Java GUIs were built with components from the Abstract Window Toolkit (AWT) in package
java.awt. When a Java application with an AWT GUI executes on different Java platforms, the
application's GUI components display differently on each platform.
Together, the appearance and the way in which the user interacts with the application are known
as that application's look-and-feel. Swing GUI components allow you to specify a uniform look-
and-feel for your application across all platforms or to use each platform's custom look-and-feel.
An application can even change the look-and-feel during execution to enable users to choose their
own preferred look-and-feel.
Most Swing components are not tied to actual GUI components supported by the underlying
platform on which an application executes. Such GUI components are known as lightweight
components. For this reason, Swing GUI components are generally preferred.
Java Swing
In Swing, classes that represent GUI components have names beginning with the letter J. Some
examples are JButton, JLabel, and JSlider. Altogether there are more than 250 new classes and 75
interfaces in Swing.the following figure depicts the Java Swing class hierarchy

1
Swing contains components that you’ll use to build a GUI. Below you will find some of the
commonly used Swing components.

1. JPanel is Swing’s version of the AWT class Panel and uses the same default layout,
FlowLayout. JPanel is descended directly from JComponent.
2. JFrame is Swing’s version of Frame and is descended directly from that class. The
components added to the frame are referred to as its contents; these are managed by the
contentPane. To add a component to a JFrame, we must use its contentPane instead.
3. FlowLayout when used arranges swing components from left to right until there’s no more
space available. Then it begins a new row below it and moves
from left to right again. Each component in a FlowLayout gets as much space as it needs
and no more.
4. GridLayout is a layout manager that lays out a container’s components in a rectangular
grid. The container is divided into equal-sized rectangles,
and one component is placed in each rectangle.
5. JLabel descended from JComponent, is used to create text labels.
6. The abstract class AbstractButton extends class JComponent and provides a foundation for
a family of button classes, including JButton.
7. JTextField allows editing of a single line of text. New features include the ability to justify
the text left, right, or center, and to set the text’s font.
8. JPasswordField (a direct subclass of JTextField) you can suppress the display of input.
Each character entered can be replaced by an echo character.
This allows confidential input for passwords, for example. By default, the echo character is
the asterisk, *.

9. JTextArea allows editing of multiple lines of text. JTextArea can be used in conjunction
with class JScrollPane to achieve scrolling. The underlying JScrollPane can be forced to
always or never have either the vertical or horizontal scrollbar; JButton is a component the
user clicks to trigger a specific action.
10. JRadioButton is similar to JCheckbox, except for the default icon for each class. A set of
radio buttons can be associated as a group in which only
one button at a time can be selected.

11. JCheckBox is not a member of a checkbox group. A checkbox can be selected and
deselected, and it also displays its current state.

12. JComboBox is like a drop down box. You can click a drop-down arrow and select an option
from a list. For example, when the component has focus,
pressing a key that corresponds to the first character in some entry’s name selects that
entry. A vertical scrollbar is used for longer lists.

13. JMenubar can contain several JMenu’s. Each of the JMenu’s can contain a series of
JMenuItem ’s that you can select. Swing provides support for pull-down and popup menus.

Java Swing Example: Below is a java swing code for the traditional Hello World
program.Basically, the idea behind this Hello World program is to learn how to create a java
program, compile and run it.
2
import javax.swing.JFrame;
import javax.swing.JLabel;

public class HelloWorldFrame extends JFrame {


HelloWorldFrame() {
JLabel jlbHelloWorld = new JLabel("Hello World");
add(jlbHelloWorld);
this.setSize(100, 100);
setVisible(true);

public static void main(String args[]) {


new HelloWorldFrame();
}

}
}

JFrame
The components added to the frame are referred to as its contents; these are managed by the
contentPane. To add a component to a JFrame, we must use its contentPane instead.JFrame is a
Window with border, title and buttons. When JFrame is set visible, an event dispatching thread is
started. JFrame objects store several objects including a Container object known as the content
pane. To add a component to a JFrame, add it to the content pane.
Creating a JFrame Window
Step 1: Construct an object of the JFrame class.
Step 2: Set the size of the Jframe.
Step 3: Set the title of the Jframe to appear in the title bar (title bar will be blank if no title is set).
Step 4: Set the default close operation. When the user clicks the close button, the program stops
running.
Step 5: Make the Jframe visible.

JFrame Constructor
 JFrame() : Constructs a new frame that is initially invisible.
 JFrame(String title) : Creates a new, initially invisible Frame with the specified title.

FlowLayout

FlowLayout when used arranges swing components from left to right until there’s no more space
available. Then it begins a new row below it and moves from left to right again. Each component in
a FlowLayout gets as much space as it needs and no more.

Example:

import java.awt.FlowLayout;

import javax.swing.JButton;

import javax.swing.JCheckBox;

3
import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JTextField;

public class FlowLayoutDemo extends JFrame{

FlowLayoutDemo() {

super("FlowLayout Source Demo") ;

JPanel panel = new JPanel();

add(panel);

panel.setLayout(new FlowLayout());

panel.add(new JLabel("JLabel 1"));

panel.add(new JButton("JButton 2"));

panel.add(new JCheckBox("JCheckBox 3"));

panel.add(new JTextField("Long-Named JTextField 4"));

panel.add(new JButton("JButton 5"));

setVisible(true);

setSize(300,350); }

public static void main(String[] args) {

FlowLayoutDemo flowLayout= new FlowLayoutDemo();

flowLayout.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Output

4
GridLayout: is a layout manager that lays out a container’s components in a rectangular
grid. The container is divided into equal-sized rectangles, and one component is placed in each
rectangle.
GridLayout Constructor
GridLayout() : Creates a grid layout with a default of one column per component, in a single row.
GridLayout(int rows, int cols) : Creates a grid layout with the spe cified number of rows and
columns.

Example:

import java.awt.*;
import javax.swing.*;

public class GridLayoutDemo {

private static void createAndShowGUI() {

JFrame frame = new JFrame("GridLayout Source Demo");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set up the content pane and components in GridLayout

frame.setLayout(new GridLayout(3,2));

frame.add(new JLabel("JLabel 1"));

frame.add(new JButton("JButton 2"));

frame.add(new JCheckBox("JCheckBox 3"));

frame.add(new JTextField("Long-Named JTextField 4"));

frame.add(new JButton("JButton 5"));

frame.setSize(300,300);

frame.setVisible(true);

}
public static void main(String[] args) {
createAndShowGUI();
}
}

OutPut

5
JLabels
JLabel, descended from JComponent, is used to create text labels.A JLabel object provides text
instructions or information on a GUI; display a single line of read-only text, an image or both text
and image. We use a Swing JLabel when we need a user interface component that displays a
message or an image.

JLabel Constructor
 JLabel() : Creates a JLabel instance with no image and with an empty string for the title.
 JLabel(Icon image) :Creates a JLabel instance with the specified image.
 JLabel(String text) : Creates a JLabel instance with the specified text.

JTextField
JTextField allows editing/displaying of a single line of text. New features include the ability to
justify the text left, right, or center, and to set the text’s font. When the user types data into them
and presses the Enter key, an action event occurs. If the program registers an event listener, the
listener processes the event and can use the data in the text field at the time of the event in the
program. JTextField is an input area where the user can type in characters. If you want to let the
user enter multiple lines of text, you cannot use Jtextfield’s unless you create several of them. The
solution is to use JTextArea (Reading assignment), which enables the user to enter multiple
lines of text.

JTextField Constructor
 JTextField() : Constructs a new TextField.
 JTextField(String text): Constructs a new TextField initialized with the specified text.

JButton
The abstract class AbstractButton extends class JComponent and provides a foundation for a family
of button classes, including JButton. A button is a component the user clicks to trigger a specific
action.

JButton Constructor
 JButton() : Creates a button with no set text or icon.
 JButton(Action a) : Creates a button where properties are taken from the Action supplied.
 JButton(String text) : Creates a button with text.

JComboBox
JComboBox is like a drop down box — you can click a drop-down arrow and select an option from a
list. It generates ItemEvent. For example, when the component has focus, pressing a key that
corresponds to the first character in some entry’s name selects that entry. A vertical scrollbar is
used for longer lists.

JComboBox Constructor
 JComboBox() : Creates a JComboBox with a default data model.
 JComboBox(Object[] items) :Creates a JComboBox that contains the elements in the
specified array.
 JComboBox(Vector items) : Creates a JComboBox that contains the elements in the
specified Vector.

6
Example: desing a user interface as shown below and write a code to fire if we
clicked the save botton so as to concatenate all the student information and
display it at the bottom of the frame

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BasicContral extends JFrame {
TextField tFullName, tSID;
JCheckBox chlanguage;
JComboBox cYear, cSex;
JLabel lTitle, lFullName, lSID, lDepartment,lYear,lALL, lSex, lLanguageSkill;
JButton bSave, bclear;
BasicContral( String m) {
super("Example "+ m);
JPanel p1= new JPanel();
lTitle= new JLabel("Sudent Registration Form");
p1.add(lTitle);
add(p1, BorderLayout.NORTH);
Panel p= new Panel();
p.setLayout(new GridLayout(5,2));
add(p, BorderLayout.CENTER);
lFullName = new JLabel("Full Name");
p.add(lFullName);
tFullName= new TextField();
p.add(tFullName);
lSID = new JLabel("Student ID NO.");
p.add(lSID);
tSID = new TextField();
p.add(tSID);
lYear= new JLabel("Year");
String []year= {"I","II","III","V","Select"};
7
p.add(lYear);
cYear = new JComboBox(year);
p.add(cYear);
lSex = new JLabel("Sex");
p.add(lSex);
String sex[]= {"Male","Female","Select"};
cSex= new JComboBox(sex);
p.add(cSex );
bSave= new JButton("Save");
p.add(bSave);
lALL = new JLabel();
lALL.setSize(200,200);
JPanel p2= new JPanel();
p2.add(lALL);
lALL.setForeground(Color.red);
add(p2, BorderLayout.SOUTH);

bSave.addActionListener (new ActionListener() {

public void actionPerformed (ActionEvent e) {


try {
String s= tFullName.getText()+ " " + tSID.getText()+ " " +
cSex.getSelectedItem()+ " " +
cYear.getSelectedItem();
lALL.setText(s ); }
catch(Exception ex) {
System.out.println(ex);
}
}
}

);
p.add(bSave);
bclear= new JButton("Clear");

8
p.add(bclear);
bclear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tFullName.setText("");
tSID.setText("");
}
}
);
setSize(400,450);
setVisible(true);
}
public static void main(String[] args) {
BasicContral f= new BasicContral("Example");
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); }
public void windowClosing(WindowEvent we){
System.exit(0) ; }
}

JMenu
Swing provides support for pull-down and popup menus. A JMenubar can contain several JMenus.
Each of the JMenus can contain a series of JMenuItems that you can select.
How Menu’s are Created?
1. First, a JMenubar is created
2. Then, we attach all of the menus to this JMenubar.
3. Then we add JMenuItems to the JMenus.
4. The JMenubar is then added to the frame. By default, each JMenuItem added to a JMenu is
enabled, that is, it can be selected.

JMenu Source Code

import java.awt.*;
import java.awt.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JFrame;

public class JMenuDemo extends JFrame implements ActionListener{


JTextArea jtAreaOutput;
JMenuBar mainMenuBar;
9
JMenu menu1, menu2, submenu;
JMenuItem New,subMenuItem;
JMenuDemo()
{
super("Microsoft Word");
mainMenuBar = new JMenuBar();
menu1 = new JMenu("File");
menu1.setMnemonic(KeyEvent.VK_F);
mainMenuBar.add(menu1);
New = new JMenuItem("New");
New.addActionListener(this);
menu1.add(New);
menu1.addSeparator();
// Sub Menu follows a seperator
submenu = new JMenu("Send To:");
submenu.setMnemonic(KeyEvent.VK_D);
subMenuItem = new JMenuItem("My Document");
subMenuItem.addActionListener(this);
submenu.add(subMenuItem);
menu1.add(submenu);
// Build second menu in the menu bar.
menu2 = new JMenu("Edit");
menu2.setMnemonic(KeyEvent.VK_E);
mainMenuBar.add(menu2);

// return mainMenuBar;
JPanel jplContentPane = new JPanel();
jplContentPane.setLayout(new FlowLayout());
jtAreaOutput = new JTextArea(5, 30);
jplContentPane.add(jtAreaOutput);
add(jplContentPane);
setSize(400, 300);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
JMenuItem source = (JMenuItem) (e.getSource());
String s = "Menu Item source: " + source.getText();
jtAreaOutput.setText(s);
}
public static void main(String[] args) {
JMenuDemo frame= new JMenuDemo();
frame.setJMenuBar(frame.mainMenuBar);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output

10

Das könnte Ihnen auch gefallen