0% found this document useful (0 votes)
45 views

Gui1 58

The document discusses Java Swing which provides GUI components for building desktop applications in Java, including commonly used classes like JFrame for windows, JButton for buttons, and how to add action listeners to buttons so that clicking them triggers a method to perform an action. It provides examples of creating simple GUI applications with Swing components like JFrame and JButton, and setting properties of the components as well as adding action listeners to buttons to perform actions when clicked.

Uploaded by

Ye Yint Aung
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Gui1 58

The document discusses Java Swing which provides GUI components for building desktop applications in Java, including commonly used classes like JFrame for windows, JButton for buttons, and how to add action listeners to buttons so that clicking them triggers a method to perform an action. It provides examples of creating simple GUI applications with Swing components like JFrame and JButton, and setting properties of the components as well as adding action listeners to buttons to perform actions when clicked.

Uploaded by

Ye Yint Aung
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Java-GUI

Java Swing
• Java Swing is a part of Java Foundation Classes (JFC) that is used to create
window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.

• Unlike AWT, Java Swing provides platform-independent and lightweight


components.

• The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
What is JFC?
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
Hierarchy of Java Swing classes
Commonly used Methods of Component class

Method Description

public void add(Component c) add a component on another


component.
public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager sets the layout manager for the


m) component.
public void setVisible(boolean b) sets the visibility of the component. It is
by default false.
JFrame
• javax.swing.JFrame class is a type of container which inherits the
java.awt.Frame class.
• JFrame works like the main window where components like labels, buttons,
textfields are added to create a GUI.
• Unlike Frame, JFrame has the option to hide or close the window with the help
of setDefaultCloseOperation(int) method.
There are two ways to create a frame:
• By creating the object of Frame class (association)
• By extending Frame class (inheritance)
Constructor Description
JFrame() It constructs a new frame that is initially
invisible.
JFrame(GraphicsConfiguration gc) It creates a Frame in the specified
GraphicsConfiguration of a screen device and a
blank title.
JFrame(String title) It creates a new, initially invisible Frame with
the specified title.
JFrame(String title, It creates a JFrame with the specified title and
GraphicsConfiguration gc) the specified GraphicsConfiguration of a screen
device.
Modifier and Type Method Description
protected void addImpl(Component comp, Object constraints, int index) Adds the specified child Component.
protected createRootPane() Called by the constructor methods to
JRootPane create the default rootPane.
protected void frameInit() Called by the constructors to init the
JFrame properly.
void setContentPane(Containe contentPane) It sets the contentPane property
static void setDefaultLookAndFeelDecorated(boolean Provides a hint as to whether or not
defaultLookAndFeelDecorated) newly created JFrames should have
their Window decorations (such as
borders, widgets to close the window,
title...) provided by the current look
and feel.
void setIconImage(Image image) It sets the image to be displayed as
the icon for this window.
void setJMenuBar(JMenuBar menubar) It sets the menubar for this frame.
void setLayeredPane(JLayeredPane layeredPane) It sets the layeredPane property.
JRootPane getRootPane() It returns the rootPane object for this
frame.
TransferHandler getTransferHandler() It gets the transferHandler property.
JRootPane
• JRootPane is a lightweight container used behind the scenes by JFrame, JDialog,
JWindow, JApplet, and JInternalFrame.

JButton
• The JButton class is used to create a labeled button

• declaration for javax.swing.JButton class.

public class JButton extends AbstractButton implements Accessible


Constructor Description

JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.


Commonly used Methods of AbstractButton class:
Methods Description
void setText(String s) It is used to set specified text on button
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the


button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.

void It is used to add the action listener


addActionListener(ActionListener a) to this object.
import javax.swing.*;
public class SimpleGUI {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame sets the position of the button.
f.setSize(400,500);//400 width and 500 height
f.setVisible(true);//making the frame visible
}
}
import javax.swing.*;
public class SimpleGUI{ Application Window
JFrame f;
SimpleGUI(){
f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setVisible(true);//making the frame visible
}
public static void main(String[] args) {
new SimpleGUI();
}
}
"How do I get the button to do something specific when the user clicks it?"

Need two things:

• A method to be called when the user clicks (the thing you want to happen as a

result of the button click).

• A way to know when to trigger that method. In other words, a way to know

when the user clicks the button.


How will we know when this method should run?
How will we know when the button is clicked.

First, the button needs to know that we care


1. Hey button, I
care about what
happens to you.
button object
Your code

2.User clicked me.

Second, the button needs a way to call us back


when a button clicked event occurs.
Event-handling
• In Java, the process of getting and handling a user event is called event-
handling. There are many different event types in Java, although most involve
GUI user actions.
• If the user clicks a button, that's an event. An event that says -The user wants
the action of this button to happen."

• A listener interface is the bridge between the listener and event source (the
button).
• Swing GUI components are event sources.
• An event source is an object that can turn user actions (click a mouse, type a
key, close a window) into events.
• An event is represented as an object. An object of some event class.
ActionListener Interface
• It is callback mechanism
• It is notified whenever you click on the button or menu item. It is notified
against ActionEvent. The ActionListener interface is found in
java.awt.event package.
• It has only one method:
public abstract void actionPerformed(ActionEvent e);
The actionPerformed() method is invoked automatically whenever you click on the
registered component.
import java.awt.event.*;
import javax.swing.*;
public class ButtonTest {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);

JButton b=new JButton("Click Here"); 1. Hey button, I


care about what
b.setBounds(50,100,95,30); happens to you.
2.User clicked me.
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Java World");
}
});
f.add(b);
f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
JLabel
• a component for placing text in a container.
• used to display a single line of read only text.
• text can be changed by an application but a user cannot edit it directly.
• inherits JComponent class.
Constructor Description
JLabel() Creates a JLabel instance with no image and with an
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, Creates a JLabel instance with the specified text, image,
int horizontalAlignment) and horizontal alignment.
Methods Description
String getText() returns the text string that a label displays.

void setText(String text) It defines the single line of text this component
will display.

void setHorizontalAlignment(int It sets the alignment of the label's contents along


alignment) the X axis.

Icon getIcon() It returns the graphic image that the label


displays.
int getHorizontalAlignment() It returns the alignment of the label's contents
along the X axis.
MouseListener Interface
• It is notified whenever you change the state of mouse.
• It is notified against MouseEvent.
• It is found in java.awt.event package. It has five methods.
1.public abstract void mouseClicked(MouseEvent e);

2.public abstract void mouseEntered(MouseEvent e);

3.public abstract void mouseExited(MouseEvent e);

4.public abstract void mousePressed(MouseEvent e);

5.public abstract void mouseReleased(MouseEvent e);


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseListenerTest extends JFrame implements MouseListener{
JLabel l;
MouseListenerTest(){
addMouseListener(this);
l=new JLabel();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerTest();
}
}
MouseMotionListener Interface
• It is notified whenever you move or drag mouse.
• It is notified against MouseEvent.
• It is found in java.awt.event package. It has two methods.
1.public abstract void mouseDragged(MouseEvent e);
2.public abstract void mouseMoved(MouseEvent e);
import java.awt.*;
import java.awt.event.*;
public class MouseMotionListenerExample extends Frame implements MouseMotionListener{
MouseMotionListenerExample(){
addMouseMotionListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {}
public static void main(String[] args) {
new MouseMotionListenerExample(); }
}
Displaying image on the button:

import javax.swing.*;
public class ButtonTest{
ButtonTest(){
JFrame f=new JFrame("Button Example");
JButton b=new JButton(new ImageIcon(“c:\\icon.png"));
b.setBounds(100,100,100, 40);
f.add(b);
f.setSize(300,400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ButtonTest(); }
}
JDialog
• The JDialog control represents a top level window with a border and a title used
to take some form of input from the user. It inherits the Dialog class.

• Unlike JFrame, it doesn't have maximize and minimize buttons.


Constructor Description
JDialog() It is used to create a modeless dialog
without a title and without a specified
Frame owner.
JDialog(Frame owner) It is used to create a modeless dialog
with specified Frame as its owner and
an empty title.
JDialog(Frame owner, String title, boolean It is used to create a dialog with the
modal) specified title, owner Frame and
modality.

Modal means that no other window can be used or activated while the
corresponding JDialog is being displayed.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogTest {
private static JDialog d;
DialogTest() {
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogTest.d.setVisible(false);
} });
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogTest();
}
}
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogTest();
}
}
JTextField
• It is a text component that allows the editing of a single line text.
• It inherits JTextComponent class.

Constructor Description

JTextField() Creates a new TextField


JTextField(String text) Creates a new TextField initialized with the
specified text.
JTextField(String text, int columns) Creates a new TextField initialized with the
specified text and columns.
JTextField(int columns) Creates a new empty TextField with the
specified number of columns.
Methods Description
void addActionListener(ActionListener l) It is used to add the specified action
listener to receive action events from this
textfield.
Action getAction() It returns the currently set Action for this
ActionEvent source, or null if no Action is
set.
void setFont(Font f) It is used to set the current font.
void It is used to remove the specified action
removeActionListener(ActionListener l) listener so that it no longer receives
action events from this textfield.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LabelTest extends JFrame implements ActionListener{
JTextField tf; JLabel l; JButton b;
LabelTest(){
tf=new JTextField();
tf.setBounds(50,50, 150,20);
l=new JLabel();
l.setBounds(50,100, 250,20);
b=new JButton("Find IP");
b.setBounds(50,150,95,30);
b.addActionListener(this);
add(b);add(tf);add(l);

setSize(400,400);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try{
String host=tf.getText();
String ip=java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}catch(Exception ex){System.out.println(ex);}
}
public static void main(String[] args) {
new LabelTest();
}}
import javax.swing.*;
import java.awt.event.*;
public class TextFieldTest implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldTest(){
JFrame f= new JFrame();
tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20);
tf3=new JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new JButton("+");
b1=new JButton("+");
b1.setBounds(50,200,50,50);
b2=new JButton("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldTest();
}}
JTextArea
• a multi line region that displays text. It allows the editing of multiple line text.

Constructor Description
JTextArea() Creates a text area that displays no text initially.

JTextArea(String s) Creates a text area that displays specified text


initially.
JTextArea(int row, int column) Creates a text area with the specified number
of rows and columns that displays no text
initially.
JTextArea(String s, int row, int Creates a text area with the specified number
column) of rows and columns that displays specified
text.
Methods Description
void setRows(int rows) It is used to set specified number of rows.

void setColumns(int cols) It is used to set specified number of columns.

void setFont(Font f) It is used to set the specified font.


void insert(String s, int position) It is used to insert the specified text on the
specified position.
void append(String s) It is used to append the given text to the end of
the document.
import javax.swing.*;
import java.awt.event.*;
public class TextAreaTest implements ActionListener{
JLabel l1,l2;
JTextArea area;
JButton b;
TextAreaTest() {
JFrame f= new JFrame();
l1=new JLabel();
l1.setBounds(50,25,100,30);
l2=new JLabel();
l2.setBounds(160,25,100,30);
area=new JTextArea();
area.setBounds(20,75,250,200);
b=new JButton("Count Words");
b.setBounds(100,300,120,30);
b.addActionListener(this);
f.add(l1);f.add(l2);f.add(area);f.add(b);
f.add(l1);f.add(l2);f.add(area);f.add(b);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
String text=area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
public static void main(String[] args) {
new TextAreaTest();
}
}
JPasswordField
• It is a text component specialized for password entry. It allows the editing of a
single line of text. It inherits JTextField class.
Constructor Description
JPasswordField() Constructs a new JPasswordField, with a default
document, null starting text string, and 0 column width.
JPasswordField(int columns) Constructs a new empty JPasswordField with the
specified number of columns.
JPasswordField(String text) Constructs a new JPasswordField initialized with the
specified text.
JPasswordField(String text, int Construct a new JPasswordField initialized with the
columns) specified text and columns.
import javax.swing.*;
import java.awt.event.*;
public class PasswordFieldTest {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Test");
final JLabel label = new JLabel();
label.setBounds(20,150, 200,50);
final JPasswordField value = new JPasswordField();
value.setBounds(100,75,100,30);
create a tool tip for any JComponent
JLabel l1=new JLabel("Username:"); with setToolTipText() method.
l1.setBounds(20,20, 80,30); For example, to add tool tip to PasswordField
JLabel l2=new JLabel("Password:"); , add only one line of code:
l2.setBounds(20,75, 80,30); value.setToolTipText("Enter your Password");
JButton b = new JButton("Login");
b.setBounds(100,120, 80,30);
final JTextField text = new JTextField();
text.setBounds(100,20, 100,30);
f.add(value); f.add(l1); f.add(label); f.add(l2); f.add(b); f.add(text);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Username " + text.getText();
data += ", Password: "
+ new String(value.getPassword());
label.setText(data);
}
});
}
}
JCheckBox
• It is used to create a checkbox.
• It is used to turn an option on (true) or off (false).
• Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".
• It inherits JToggleButton class.
Constructor Description
JJCheckBox() Creates an initially unselected check box
button with no text, no icon.
JChechBox(String s) Creates an initially unselected check box with
text.
JCheckBox(String text, boolean selected) Creates a check box with text and specifies
whether or not it is initially selected.
JCheckBox(Action a) Creates a check box where properties are
taken from the Action supplied.
Methods Description
AccessibleContext It is used to get the AccessibleContext
getAccessibleContext() associated with this JCheckBox.

protected String paramString() It returns a string representation of this


JCheckBox.

To change titlebar icon in java AWT and swing


• setIconImage() method of Frame class is used to change the icon of Frame or Window.
• It changes the icon which is displayed at the left side of Frame or Window.
• java.awt.Toolkit class is used to get instance of Image class in AWT and Swing.
Image icon = Toolkit.getDefaultToolkit().getImage(“c:\\icon.png");
f.setIconImage(icon);
import javax.swing.*;
import java.awt.event.*;
public class CheckBoxTest extends JFrame implements ActionListener{
JLabel l;
JCheckBox cb1,cb2,cb3;
JButton b;
CheckBoxTest(){
l=new JLabel("Food Ordering System");
l.setBounds(50,50,300,20);
cb1=new JCheckBox("Pizza @ 100");
cb1.setBounds(100,100,150,20);
cb2=new JCheckBox("Burger @ 30");
cb2.setBounds(100,150,150,20);
cb3=new JCheckBox("Tea @ 10");
cb3.setBounds(100,200,150,20);
b=new JButton("Order");
b.setBounds(100,250,80,30);
b.addActionListener(this);
add(l);add(cb1);add(cb2);add(cb3);add(b);
setSize(400,400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
float amount=0;
String msg="";
if(cb1.isSelected()){
amount+=100;
msg="Pizza: 100\n";
}
if(cb2.isSelected()){
amount+=30;
msg+="Burger: 30\n";
}
if(cb3.isSelected()){
amount+=10;
if(cb3.isSelected()){
amount+=10;
msg+="Tea: 10\n"; }
msg+="-----------------\n";
JOptionPane.showMessageDialog(this,msg+"Total: “
+amount);
}
public static void main(String[] args) {
new CheckBoxTest();
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy