SlideShare a Scribd company logo
1 of 21
Download to read offline
GETTING STARTED WITH GUI PROGRAMMING

By .Muhammad Shebl
OBJECTIVES
1.   To create user interfaces using frames.
2.   GUI components
3.   Adding Component
4.   To understand the role of layout managers
5.   Panels
6.   Actions
7.   Set & Get
FRAMES
 Frame is a window that is not contained
 inside another window.
 Frame is the basis to contain other user
 interface components in Java GUI
 applications.
 For Swing GUI programs, use JFrame class to
 create widows.
CREATING FRAMES
 import javax.swing.*;
 public class Main extends JFrame {
    public Main() {
         setSize(200, 150);
         setTitle("MUFIX");
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setLocationRelativeTo(null);
         setVisible(true);
    }

     public static void main(String[] args) {
        Main m=new Main();
     }
 }
CENTERING FRAMES
By default, a frame is displayed in the upper-left
 corner of the screen.
To display a frame at a specified location, you can
  use the setLocation(x,y) method in the JFrame
  class.     (0, 0)


                      Screen

                               (x, y)


                                             Frame
                                                       getHeight()   screenHeight




                                          getWidth()




                                        screenWidth
CREATING GUI OBJECTS
                                                 Label   Text    Check   Radio
                                                         field   Box     Button

                       Button

// Create a button with text OK
JButton jbtOK = new JButton("OK");



// Create a label with text "Enter your name: "
JLabel jlblName = new JLabel("Enter your name: ");

// Create a text field with text "Type Name Here"                  Combo
JTextField jtfName = new JTextField("Type Name Here");             Box

// Create a check box with text bold
JCheckBox jchkBold = new JCheckBox("Bold");

// Create a radio button with text red
JRadioButton jrbRed = new JRadioButton("Red");

// Create a combo box with choices red, green, and blue
JComboBox jcboColor = new JComboBox(new String[]{"Red", "Green", "Blue"});
LAYOUT MANAGERS
 The GUI components are placed in containers. Each
 container has a layout manager to arrange the GUI
 components within the container.
 Layout managers are set in containers using the
 setLayout(LayoutManager)     method in a container.
 ◦ FlowLayout

 ◦ GridLayout

 ◦ BorderLayout
FlowLayout MANAGER
The components are arranged in the container from
left to right in the order in which they were added.
When one row becomes filled, a new row is started.
container.setLayout(newFlowLayout(FlowLayout.LEFT,5,5));
FlowLayout             CONSTRUCTORS
 public FlowLayout(int align, int hGap, int vGap)
 Constructs a new FlowLayout with a specified alignment,
 horizontal gap, and vertical gap. The gaps are the distances in
 pixel between components.
 public FlowLayout(int alignment)
 Constructs a new FlowLayout with a specified alignment
 and a default gap of five pixels for both horizontal and
 vertical.
 public FlowLayout()
 Constructs a new FlowLayout with a default center alignment and
 a default gap of five pixels for both horizontal and vertical.
GridLayout MANAGER
 The GridLayout manager arranges components in a grid
 (matrix) formation with the number of rows and columns
 container.setLayout(newGridLayout(3,2,5,5));
GridLayout CONSTRUCTORS
 public GridLayout(int rows,int columns)

 Constructs a new GridLayout with the specified
 number of rows and columns.
 public GridLayout(int rows, int columns,
 int hGap, int vGap)
 Constructs a new GridLayout with the specified
 number of rows and columns, along with specified
 horizontal and vertical gaps between components.
BorderLayout MANAGER
  The BorderLayout manager divides the container
  into five areas: East, South, West, North, and Center.
container.setLayout(new BorderLayout(5,10));
container.add(jbtOK,BorderLayout.NORTH);
USING PANELS AS SUB-CONTAINERS
 Panels act as sub-containers for grouping user interface
  components.

 It is recommended that you place the user interface
  components in panels and place the panels in a frame. You
  can also place panels in a panel.

 To add a component to JFrame, you actually add it to the
  content pane of JFrame. But to add a component to a panel,
  you add it directly to the panel using the add method.
CREATING A JPanel
 You can use
   new JPanel()
  to create a panel with a default FlowLayout manager
          new JPanel(LayoutManager)
   to create a panel with the specified layout manager.

Use method add(Component)
to add a component to the panel.
For example :
      1. JPanel p = new JPanel();
      2. p.add(new JButton("OK"));
      3.     The following statement places panel p into fram   add(p);
EXAMPLE TESTING PANELS
EVENT AND EVENT SOURCE
 When you run Java GUI programs, the program
 interacts with the user and the events drive its
 execution. An event can be defined as a signal to
 the program that something has happened. Events
 are triggered either by external user actions, such
 as mouse movements, button clicks, and
 keystrokes, or by internal program activities, such
 as a timer. The program can choose to respond to or
 ignore an event.
ADDING EVENT
 JButton jbt = new JButton("OK");
 ActionListener listener = new
 OKListener();
 jbt.addActionListener(this );
SET & GET TEXT :
 getText()
 Returns the string from the text field.
 ex:txt1.getText();

 setText(String text)
Puts the given string in the text field.
 ex:txt1.setText(“MUFIX”);
QUESTIONS ?!!
TASK : CALCULATOR
Thank You

More Related Content

What's hot

Евгений Обрезков "Behind the terminal"
Евгений Обрезков "Behind the terminal"Евгений Обрезков "Behind the terminal"
Евгений Обрезков "Behind the terminal"Fwdays
 
The AWT and Swing
The AWT and SwingThe AWT and Swing
The AWT and Swingadil raja
 
DOT NET LAB PROGRAM PERIYAR UNIVERSITY
DOT NET LAB PROGRAM PERIYAR UNIVERSITY DOT NET LAB PROGRAM PERIYAR UNIVERSITY
DOT NET LAB PROGRAM PERIYAR UNIVERSITY GOKUL SREE
 
120 tips about_photoshop
120 tips about_photoshop120 tips about_photoshop
120 tips about_photoshopGalmher
 
Google Earth User Guide
Google Earth User GuideGoogle Earth User Guide
Google Earth User GuideF Blanco
 

What's hot (8)

Flash Tutorial
Flash TutorialFlash Tutorial
Flash Tutorial
 
Евгений Обрезков "Behind the terminal"
Евгений Обрезков "Behind the terminal"Евгений Обрезков "Behind the terminal"
Евгений Обрезков "Behind the terminal"
 
The AWT and Swing
The AWT and SwingThe AWT and Swing
The AWT and Swing
 
Maya
MayaMaya
Maya
 
DOT NET LAB PROGRAM PERIYAR UNIVERSITY
DOT NET LAB PROGRAM PERIYAR UNIVERSITY DOT NET LAB PROGRAM PERIYAR UNIVERSITY
DOT NET LAB PROGRAM PERIYAR UNIVERSITY
 
Lenguaje de programación
Lenguaje de programaciónLenguaje de programación
Lenguaje de programación
 
120 tips about_photoshop
120 tips about_photoshop120 tips about_photoshop
120 tips about_photoshop
 
Google Earth User Guide
Google Earth User GuideGoogle Earth User Guide
Google Earth User Guide
 

Viewers also liked

Emerald Ise, Powai - E-Brochure
Emerald Ise, Powai - E-BrochureEmerald Ise, Powai - E-Brochure
Emerald Ise, Powai - E-BrochureRiteshJuthani
 
20 de março início do outono
20 de março   início do outono20 de março   início do outono
20 de março início do outonoJesilaine Vinhais
 
Grace tech tool
Grace tech toolGrace tech tool
Grace tech tool20gball
 
Assedio moral nas escolas - SEPE
Assedio moral  nas escolas - SEPEAssedio moral  nas escolas - SEPE
Assedio moral nas escolas - SEPEAdriana De Moraes
 
Getting started with GUI programming in Java_2
Getting started with GUI programming in Java_2Getting started with GUI programming in Java_2
Getting started with GUI programming in Java_2Muhammad Shebl Farag
 
Cartilha do Servidor Estatutário do Município do RJ/ 2015
Cartilha do Servidor Estatutário do Município do RJ/ 2015Cartilha do Servidor Estatutário do Município do RJ/ 2015
Cartilha do Servidor Estatutário do Município do RJ/ 2015Adriana De Moraes
 
Módulo 01 - 9 ano- Matemática / Ens.Fundamental
Módulo 01 - 9 ano- Matemática  / Ens.FundamentalMódulo 01 - 9 ano- Matemática  / Ens.Fundamental
Módulo 01 - 9 ano- Matemática / Ens.FundamentalAdriana De Moraes
 
Avaliação eja 2° período
Avaliação eja 2° períodoAvaliação eja 2° período
Avaliação eja 2° períodoJesilaine Vinhais
 
Avaliação bimestral de ciências 2º e 3º ano - 1º bimestre
Avaliação bimestral de ciências   2º e 3º ano - 1º bimestreAvaliação bimestral de ciências   2º e 3º ano - 1º bimestre
Avaliação bimestral de ciências 2º e 3º ano - 1º bimestreJesilaine Vinhais
 
Módulo 01 - 8 ano / Ens.Fundamental
Módulo 01 - 8 ano / Ens.Fundamental  Módulo 01 - 8 ano / Ens.Fundamental
Módulo 01 - 8 ano / Ens.Fundamental Adriana De Moraes
 
Borang kaji selidik sek
Borang kaji selidik sekBorang kaji selidik sek
Borang kaji selidik sekNona Naza
 

Viewers also liked (15)

Emerald Ise, Powai - E-Brochure
Emerald Ise, Powai - E-BrochureEmerald Ise, Powai - E-Brochure
Emerald Ise, Powai - E-Brochure
 
NYC Venues
NYC VenuesNYC Venues
NYC Venues
 
20 de março início do outono
20 de março   início do outono20 de março   início do outono
20 de março início do outono
 
Grace tech tool
Grace tech toolGrace tech tool
Grace tech tool
 
Political.pptpspsls
Political.pptpspslsPolitical.pptpspsls
Political.pptpspsls
 
Lecture17aam
Lecture17aamLecture17aam
Lecture17aam
 
ponovna povezava
ponovna povezavaponovna povezava
ponovna povezava
 
Assedio moral nas escolas - SEPE
Assedio moral  nas escolas - SEPEAssedio moral  nas escolas - SEPE
Assedio moral nas escolas - SEPE
 
Getting started with GUI programming in Java_2
Getting started with GUI programming in Java_2Getting started with GUI programming in Java_2
Getting started with GUI programming in Java_2
 
Cartilha do Servidor Estatutário do Município do RJ/ 2015
Cartilha do Servidor Estatutário do Município do RJ/ 2015Cartilha do Servidor Estatutário do Município do RJ/ 2015
Cartilha do Servidor Estatutário do Município do RJ/ 2015
 
Módulo 01 - 9 ano- Matemática / Ens.Fundamental
Módulo 01 - 9 ano- Matemática  / Ens.FundamentalMódulo 01 - 9 ano- Matemática  / Ens.Fundamental
Módulo 01 - 9 ano- Matemática / Ens.Fundamental
 
Avaliação eja 2° período
Avaliação eja 2° períodoAvaliação eja 2° período
Avaliação eja 2° período
 
Avaliação bimestral de ciências 2º e 3º ano - 1º bimestre
Avaliação bimestral de ciências   2º e 3º ano - 1º bimestreAvaliação bimestral de ciências   2º e 3º ano - 1º bimestre
Avaliação bimestral de ciências 2º e 3º ano - 1º bimestre
 
Módulo 01 - 8 ano / Ens.Fundamental
Módulo 01 - 8 ano / Ens.Fundamental  Módulo 01 - 8 ano / Ens.Fundamental
Módulo 01 - 8 ano / Ens.Fundamental
 
Borang kaji selidik sek
Borang kaji selidik sekBorang kaji selidik sek
Borang kaji selidik sek
 

Similar to Getting started with GUI programming in Java_1

Similar to Getting started with GUI programming in Java_1 (20)

Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
 
Java swing
Java swingJava swing
Java swing
 
ch20.pptx
ch20.pptxch20.pptx
ch20.pptx
 
Chap1 1 4
Chap1 1 4Chap1 1 4
Chap1 1 4
 
L11cs2110sp13
L11cs2110sp13L11cs2110sp13
L11cs2110sp13
 
Swing
SwingSwing
Swing
 
Chap1 1 1
Chap1 1 1Chap1 1 1
Chap1 1 1
 
Chap1 1.1
Chap1 1.1Chap1 1.1
Chap1 1.1
 
Abstract Window Toolkit
Abstract Window ToolkitAbstract Window Toolkit
Abstract Window Toolkit
 
CORE JAVA-2
CORE JAVA-2CORE JAVA-2
CORE JAVA-2
 
java swing
java swingjava swing
java swing
 
Java Graphics Programming
Java Graphics ProgrammingJava Graphics Programming
Java Graphics Programming
 
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdfimport java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)
 
Chap1 1.4
Chap1 1.4Chap1 1.4
Chap1 1.4
 
14a-gui.ppt
14a-gui.ppt14a-gui.ppt
14a-gui.ppt
 
Groovy-er desktop applications with Griffon
Groovy-er desktop applications with GriffonGroovy-er desktop applications with Griffon
Groovy-er desktop applications with Griffon
 
Groovy-er Desktop Applications With Griffon
Groovy-er Desktop Applications With GriffonGroovy-er Desktop Applications With Griffon
Groovy-er Desktop Applications With Griffon
 

Recently uploaded

Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 

Recently uploaded (20)

Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 

Getting started with GUI programming in Java_1

  • 1. GETTING STARTED WITH GUI PROGRAMMING By .Muhammad Shebl
  • 2. OBJECTIVES 1. To create user interfaces using frames. 2. GUI components 3. Adding Component 4. To understand the role of layout managers 5. Panels 6. Actions 7. Set & Get
  • 3. FRAMES  Frame is a window that is not contained inside another window.  Frame is the basis to contain other user interface components in Java GUI applications.  For Swing GUI programs, use JFrame class to create widows.
  • 4. CREATING FRAMES import javax.swing.*; public class Main extends JFrame { public Main() { setSize(200, 150); setTitle("MUFIX"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { Main m=new Main(); } }
  • 5. CENTERING FRAMES By default, a frame is displayed in the upper-left corner of the screen. To display a frame at a specified location, you can use the setLocation(x,y) method in the JFrame class. (0, 0) Screen (x, y) Frame getHeight() screenHeight getWidth() screenWidth
  • 6. CREATING GUI OBJECTS Label Text Check Radio field Box Button Button // Create a button with text OK JButton jbtOK = new JButton("OK"); // Create a label with text "Enter your name: " JLabel jlblName = new JLabel("Enter your name: "); // Create a text field with text "Type Name Here" Combo JTextField jtfName = new JTextField("Type Name Here"); Box // Create a check box with text bold JCheckBox jchkBold = new JCheckBox("Bold"); // Create a radio button with text red JRadioButton jrbRed = new JRadioButton("Red"); // Create a combo box with choices red, green, and blue JComboBox jcboColor = new JComboBox(new String[]{"Red", "Green", "Blue"});
  • 7. LAYOUT MANAGERS  The GUI components are placed in containers. Each container has a layout manager to arrange the GUI components within the container.  Layout managers are set in containers using the setLayout(LayoutManager) method in a container. ◦ FlowLayout ◦ GridLayout ◦ BorderLayout
  • 8. FlowLayout MANAGER The components are arranged in the container from left to right in the order in which they were added. When one row becomes filled, a new row is started. container.setLayout(newFlowLayout(FlowLayout.LEFT,5,5));
  • 9. FlowLayout CONSTRUCTORS  public FlowLayout(int align, int hGap, int vGap) Constructs a new FlowLayout with a specified alignment, horizontal gap, and vertical gap. The gaps are the distances in pixel between components.  public FlowLayout(int alignment) Constructs a new FlowLayout with a specified alignment and a default gap of five pixels for both horizontal and vertical.  public FlowLayout() Constructs a new FlowLayout with a default center alignment and a default gap of five pixels for both horizontal and vertical.
  • 10. GridLayout MANAGER  The GridLayout manager arranges components in a grid (matrix) formation with the number of rows and columns container.setLayout(newGridLayout(3,2,5,5));
  • 11. GridLayout CONSTRUCTORS  public GridLayout(int rows,int columns) Constructs a new GridLayout with the specified number of rows and columns.  public GridLayout(int rows, int columns, int hGap, int vGap) Constructs a new GridLayout with the specified number of rows and columns, along with specified horizontal and vertical gaps between components.
  • 12. BorderLayout MANAGER  The BorderLayout manager divides the container into five areas: East, South, West, North, and Center. container.setLayout(new BorderLayout(5,10)); container.add(jbtOK,BorderLayout.NORTH);
  • 13. USING PANELS AS SUB-CONTAINERS  Panels act as sub-containers for grouping user interface components.  It is recommended that you place the user interface components in panels and place the panels in a frame. You can also place panels in a panel.  To add a component to JFrame, you actually add it to the content pane of JFrame. But to add a component to a panel, you add it directly to the panel using the add method.
  • 14. CREATING A JPanel  You can use  new JPanel() to create a panel with a default FlowLayout manager  new JPanel(LayoutManager) to create a panel with the specified layout manager. Use method add(Component) to add a component to the panel. For example : 1. JPanel p = new JPanel(); 2. p.add(new JButton("OK")); 3. The following statement places panel p into fram add(p);
  • 16. EVENT AND EVENT SOURCE  When you run Java GUI programs, the program interacts with the user and the events drive its execution. An event can be defined as a signal to the program that something has happened. Events are triggered either by external user actions, such as mouse movements, button clicks, and keystrokes, or by internal program activities, such as a timer. The program can choose to respond to or ignore an event.
  • 17. ADDING EVENT  JButton jbt = new JButton("OK");  ActionListener listener = new OKListener(); jbt.addActionListener(this );
  • 18. SET & GET TEXT :  getText() Returns the string from the text field. ex:txt1.getText();  setText(String text) Puts the given string in the text field. ex:txt1.setText(“MUFIX”);