Saturday 15 October 2016

Swing Component Classes



·         The most commonly used Swing component classes are:
JButton
JCheckBox
JComboBox
JLabel
JList
JRadioButton
JScrollPane
JTabbedPane
JTable
JTextField
JToggleButton
JTree
These component classes are all lightweight, which means that they are all derived from JComponent. The ButtonGroup class, which encapsulates a mutually exclusive set of swing buttons, and ImageIcon, which encapsulates a graphics image. Both are defined by Swing and packaged in javax.swing.

v JLabel and ImageIcon:
*      JLabel is Swing’s easiest to use component. It can be used to display text and/or icon. It is a passive component in that it does not respond to user input. It defines several constructors. Some of them are as follows:
JLabel(Icon icon)
JLabel(String str)
JLabel(String str,Icon icon,int align)
Here, str and icon are the text and icon used for the label. The align argument specifies the horizontal alignment of the text and/or icon within the dimensions of the label. It must be one of the following values: LEFT, RIGHT, CENTER, LEADING, or TRAILING. These constants are defined in the SwingConstants interface.
*      icons are specified by the object of type Icon, which is an interface defined by swing. The easiest way to obtain an icon is to use the ImageIcon class. ImageIcon class implements Icon and encapsulates an Image. The commonly used constructor for ImageIcon class is as follows:
ImageIcon(String filename)
                                    It obtains the image in the file named filename.
*      The icon and text associated with the Label can be obtained by the following methods:
Icon getIcon()
String getText()
*      The icon and text associated with a Label can be set by these methods:
void setIcon(Icon icon)
void setText(String str)
*      Example:
import java.awt.*;
import javax.swing.*;
public class MyLabel extends JApplet
{
  public void init()
  {
   try
  {
    SwingUtilities.invokeAndWait(new Runnable() {
      public void run()
      {
          makeGUI();
      }
    });
  } catch(Exception e){
           System.out.println("Sorry some error occured "+e);
        }
 }
 private void makeGUI()
 {
   ImageIcon ic=new ImageIcon("icon1.png");
   JLabel l1=new JLabel("My Icon",ic,JLabel.CENTER);
   add(l1);
  }
}

                                                    Output:

No comments:
Write comments