19 June 2014

Java Swing

 Java Swing

The java swing package lets you make GUI components for your java applications and is platform independent.The Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older, platform dependent GUI toolkit.You can use the GUI components like button , textbox etc  from the library and  do not have to create the components from scratch.

the swing class hierarchy

java-swing-class-hierarchy
All components in swing are JComponent which can be added to container classes.

what are container classes ?

Container classes are classes that can have other components on it. So for creating a GUI, we need at least one Container object Three types of containers
  1. Panel : It is a pure container and is not a window in itself. The sole purpose of a Panel is to organize the components on to a window.
  2. Frame : It is a fully functioning window with its own title and icons.
  3. Dialog : It can be thought of as a pop-up window that pops out when message has to be displayed. It is not a fully functioning window like the Frame.
Assignment: To learn designing GUI in Java
Step 1) Copy the following code into an editor
?
1
2
3
4
5
6
7
8
9
10
11
import javax.swing.*;
class gui{
    public static void main(String args[]){
       JFrame frame = new JFrame("My First GUI");
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(300,300);
       JButton button = new JButton("Press");
       frame.getContentPane().add(button); // Adds Button to content pane of frame
       frame.setVisible(true);
    }
}
Step 2) Save , Compile and Run the code.
Step 3) Now lets Add a Button to our frame.  Copy following code into an editor
?
1
2
3
4
5
6
7
8
9
10
11
import javax.swing.*;
   class gui{
      public static void main(String args[]){
        JFrame frame = new JFrame("My First GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300,300);
       JButton button1 = new JButton("Press");
       frame.getContentPane().add(button1);
       frame.setVisible(true);
     }
}
Step 4) Execute the code. You will  get a big button  --
java-sswing-button
Step 5) How about adding two buttons. Copy the following code into an editor.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
import javax.swing.*;
class gui{
      public static void main(String args[]){
           JFrame frame = new JFrame("My First GUI");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           frame.setSize(300,300);
          JButton button1 = new JButton("Button 1");
          JButton button2 = new JButton("Button 2");
          frame.getContentPane().add(button1);
          frame.getContentPane().add(button2);
          frame.setVisible(true);
     }
}
Step 6)Save , Compile , & Run the program.
Step 7) Unexpected output = ? Buttons are getting overlapped.
Enter

No comments:

Post a Comment