Successfully reported this slideshow.

Lecture9 oopj


Published on

  • Be the first to comment

Lecture9 oopj

  1. 1. Introduction to SwingThis chapter explorer the javax.swing package. Thejavax package is a java extension package.The javax.swing package contains lots of classes forswing components such as Buttons, checkboxes, choiceand many more.The swing components are said lightweightcomponents .Moreover, the swing components have better GUI thanAWT components. For example, in swing buttoncomponent can display both the caption and also aimage on it, which is not possible in AWT button.JApplet classThe JApplet class is a subclass of the Applet class. Anapplet must extend the JApplet which users a swingcomponent. To add a component in the JApplet, you tocall the add () method.JComponent classThe JComponent class is a subclass of container class.This class has many subclasses such as JButton, JLabeland JCheckBox etc.
  2. 2. Example:import java.awt.*;import javax.swing.*;/*<applet code="swing1.class" width=500height=500></applet>*/public class swing1 extends JApplet{ public void init() { Container content = getContentPane(); content.setBackground(; content.setLayout(new FlowLayout()); content.add(new JButton("Button 1")); content.add(new JButton("Button 2")); content.add(new JButton("Button 3")); }}Example:import java.awt.*; //import normal applet classesimport java.awt.event.*; //import event listeners
  3. 3. import javax.swing.*; //import swing componentsimport javax.swing.JApplet; //import swing appletinterface/*<applet code="swingdemo.class" width=500height=500></applet>*/public class swingdemo extends JApplet implementsActionListener{ public void init() { //initiallize the applet getContentPane().add(label1,BorderLayout.NORTH); pane1.setLayout(new GridLayout(1,2)); pane1.add(but1); pane1.add(but2); getContentPane().add(pane1,BorderLayout.SOUTH); but1.addActionListener(this); but2.addActionListener(this); } public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if(source == but1)
  4. 4. label1.setVisible(true); else label1.setVisible(false); } private JLabel label1 = new JLabel("Hello JavaSwing World"); private JPanel pane1 = new JPanel(); private JButton but1 = new JButton("ON"); private JButton but2 = new JButton ("OFF");}