"Swing "

Awt/Swing Related Notes

1 )   What is AWT ?

AWT stands for "Abstract Window Toolkit (AWT)" is Java's original platform
-independent windowing, graphics, and user-interface widget toolkit.
AWT widgets provided a thin level of abstraction over the underlying native
user-interface. For example, creating an AWT check box would cause AWT directly
to call the underlying native subroutine that created a check box.
So Look and Feel of the AWTs would vary based on Operating System, for instance
the AWT checkBox does appear in same way on Windows and Apple OS.

2 )   What is the differance between EventModel 1.0 and EventModel 1.1 ? Or "Delegation Event Model" ?

Event Model 1.0 :
The model for event processing in version 1.0 of the AWT is based on inheritance. In order
for a program to catch and process GUI events, it must subclass GUI components and override
either action() or handleEvent() methods.
 Returning "true" from one of these methods consumes
the event so it is not processed further; otherwise the event is propagated sequentially up
the GUI hierarchy until either it is consumed or the root of the hierarchy is reached.
The inheritance model does not lend itself well to maintaining a clean separation between the
application model and the GUI because application code must be integrated directly into the subclassed
 components at some level.
Event Model 1.1 (Delegation Model Overview) :
Event types are encapsulated in a class hierarchy rooted at java.util.EventObject. An event is
propagated from a "Source" object to a "Listener" object by invoking a method on the listener
and passing in the instance of the event subclass which defines the event type generated.

3 )   What are high level Containers ?

Some of the High level containers are here.
 JComponent, Panel, ScrollPane, Window
Next level containers are here
Dialog, Frame, JWindow   these extend  Window

4 )   AWT/Swing Adapter VS Listener ?


Many listener interfaces have more than one callback method. An example is java.awt.FocusListener
that has two methods; focusGained(java.awt.FocusEvent event) and focusLost(java.awt.FocusEvent event).
When creating a listener class that implements the interface the Java compiler insists that all
of the interface methods are implemented
, which often results in many empty methods being created to
satisfy its requirements when only one or some of its methods actually contain code. The following
statement shows a FocusListener being used to perform some logic when a Java bean gains focus. However,
an empty focusLost method must be provided.
To avoid having many empty listener methods for many listeners, Adapter classes are provided.
These implement the listener interface, and provide empty no-op implementation of its methods. 

5 )    How to write Button ActionPerformed as Anonymous Class ?

Anonymous inner classes allow you to work with local classes without having to name them.
 They are frequently used for event handling of graphical components.
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      System.out.println("Button clicked.");

6 )   What are layout available in AWT/Swing ?

There are the List Of Layout managers available in AWT and SpringLayout, BoxLayout are
introduced in Swing.

7 )   What is the default layout of the Panel ?

The default layout of Panel is FlowLayout.

8 )    AWT VS SWING ?

Awt is a Java interface to native system GUI code present in your OS.It will not work the same on every system, although it tries.
Swing provides a native look and feel that emulates the look and feel of several platforms, and also supports a pluggable look and feel that allows applications to have a look and feel unrelated to the underlying platform.
The pluggable look and feel lets you design a single set of GUI components that can automatically have the look and feel of any OS platform (Microsoft Windows, Solaris, Macintosh, etc.). It also makes it easier to make global changes to your Java programs that provide greater accessibility (like picking a hi-contrast color scheme or changing all the fonts in all dialogs, etc.).
AWT components do not support features like icons and tool-tips, Trees etc.,

9 )   What is MVC ?


  • Swing MVC
    Sample Img 9
The Swing library makes heavy use of the Model/View/Controller software design pattern,which
conceptually decouples the data being viewed from the user interface controls through which
it is viewed. MVC architecture calls for a visual application to be broken up into three
separate parts:
A model that represents the data for the application.
The view that is the visual representation of that data.
A controller that takes user input on the view and translates that to changes in the model.

10 )   JComboBox ?


Vector v = new Vector();
private javax.swing.JComboBox valueComboBox = new JComboBox(v);
        valueComboBox.setPreferredSize(new java.awt.Dimension(150, 21));
        valueComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
   ComboBoxModel cbm = valueComboBox.getModel();

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
        filterPanel.add(valueComboBox, gridBagConstraints);

11 )    What is the JRootPane ?


  • JRootPane
    Sample Img 11

Five are Swing container classes that delegate their contents to a JRootPane instance.
Four heavyweight containers JFrame, JDialog, JWindow, and JApplet.

One lightweight container: JInternalFrame.
You could get the ContentPane as follows.
public class testFrame extends javax.swing.JFrame {
 private void initComponents() {
   getContentPane().add(jToolBar1, java.awt.BorderLayout.NORTH);
   getContentPane().add(AppPanel, java.awt.BorderLayout.CENTER);

12 )    What are the different panes available ?


  • null
    Sample Img 12
In general, you don't directly create a JRootPane object. Instead, you get a JRootPane
(whether you want it or not!) when you instantiate JInternalFrame or one of the top-level
Swing containers, such as JApplet, JDialog, and JFrame.
Using Top-Level Containers tells you the basics of using root panes — getting the
content pane, setting its layout manager, and adding Swing components to it. This
section tells you more about root panes, including the components that make up
a root pane and how you can use them.

13 )    JTable and JTableModel ?

Table Model :
As we know in MVC architecture Model holds the data, and the methods to manipulate that,
in same manner the JTableModel also holds the table data, and the methodslike
setValueAt(), isCellEditable() , getRowCount() 
etc., which manage that data.

public class YourAppDefaultTableModel extends DefaultTableModel {
  public YourAppDefaultTableModel(Object[][] rowData, Object[] columnNames) {
  public YourAppDefaultTableModel(Object[][] rowData, Object[] columnNames, boolean hasHeader) {
    this.hasHeader = hasHeader;
  public Object getValueAt(int row, int col)
    int rowIndex = row;
    if (indexes != null && indexes.length > 0 && row < indexes.length)
      rowIndex = indexes[row];
    return super.getValueAt(rowIndex, col);
  public void setValueAt(Object value, int row, int col)
    int rowIndex = row;
    if (indexes != null && indexes.length > 0 && row < indexes.length)
      rowIndex = indexes[row];
    super.setValueAt(value, rowIndex, col);
 public boolean isCellEditable(int row, int col) {

            return false;
  public void setDataValue(Object[][] data, JTable table){
   this.dataVector = convertToVector(data);
   int col1, col2;
   col1 = table.convertColumnIndexToModel(0);
   col2 = table.convertColumnIndexToModel(1);
  public void setDataValue(Object[][] data) {
   this.dataVector = convertToVector(data);
JTable : 
JTable table = new JTable(new YourAppDefaultTableModel());

14 )   Swing Table CellRenders ?

You can think of the renderer as a configurable ink stamp that the table uses to
stamp appropriately formatted data onto each cell.
 When the user starts to edit
a cell's data, a cell editor takes over the cell, controlling the cell's editing
To choose the renderer that displays the cells in a column, a table first determines
whether you specified a renderer for that particular column.
Here are some data type which could be rendered as follows.
Boolean — rendered with a check box.
Number — rendered by a right-aligned label.
You have to override "DefaultTableCellRenderer.getTableCellRendererComponent()"
CellRenderer  Example :
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
 public class YourOwnJTableCellColorRenderer extends

 private static final long serialVersionUID = 1L;
 private int color = 0;
private int colorPrevious = 0;
private boolean hasHeader = false;
private String tooltip = "";
public static Color TABLE_ALTERNATING_ROW_COLOR = new Color(236,236,244);
public static Color TABLE_GROUP_ROW_COLOR = new Color(236,236,244);
public static Color TABLE_SUMMARY_ROW_COLOR = Color.lightGray;
 public YourOwnJTableCellColorRenderer (boolean hasHeader){
this.hasHeader = hasHeader;
public YourOwnJTableCellColorRenderer (){
public Component getTableCellRendererComponent(
 JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component comp = super.getTableCellRendererComponent(table,value,isSelected,false,row,column);
if(row == 0 && hasHeader){
}else if(row%2==0){
} else{
if (table.isCellEditable(row, column)) {
if(table.getEditorComponent() instanceof JComboBox){
((JComboBox)table.getEditorComponent()).setBorder(new LineBorder(Color.lightGray,2));
((JComboBox)table.getEditorComponent()).getComponent(1).setFont(new Font("SansSerif", 1, 11));
Color back = getBackground();
boolean colorMatch = (back != null) && (back.equals(table.getBackground()))
 && table.isOpaque() && (color == colorPrevious);
colorPrevious = color;
return comp;
public String getTooltip() {
return tooltip;
public void setTooltip(String tooltip) {
this.tooltip = tooltip;

15 )   Swing Table Cell Editor ?


  • Swing Table CellEditor  ?
    Sample Img 15
Setting up a combo box as an editor is simple, as the following example shows.
 The bold line of code sets up the combo box as the editor for a specific column.
TableColumn sportColumn = table.getColumnModel().getColumn(2);
JComboBox comboBox = new JComboBox();
comboBox.addItem("Chasing toddlers");
comboBox.addItem("Speed reading");
comboBox.addItem("Teaching high school");
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));

16 )    Jtree ?


TreeNode rootNode = createNodes();
tree = new JTree(rootNode);

private TreeNode createNodes() {
            DefaultMutableTreeNode root;
            DefaultMutableTreeNode grandparent;
            DefaultMutableTreeNode parent;
            root = new DefaultMutableTreeNode("San Francisco");
            grandparent = new DefaultMutableTreeNode("Potrero Hill");
            parent = new DefaultMutableTreeNode("Restaurants");
            dummyParent = parent;
            return root;

17 )   JTree Collapse and Expand example ?

You need to implment "TreeExpansionListener" and register your Jtree.
TreeExpansionListener implementation:
public class YourOwnTreeExpansionListener implements TreeExpansionListener{
    public void treeCollapsed(TreeExpansionEvent te){
      for(int i=0; i<expandedNodes.size(); i++){
    public void treeExpanded(TreeExpansionEvent te){
        boolean has=false;
        for(int i=0; i<expandedNodes.size(); i++){
JTree :
  public class YourOwnTree extends JTree {
   public YourOwnTree(YourController rc) {
        this.rc = rc;

18 )    jtree renderer and editor ?

class QueryTreeRenderer extends DefaultTreeCellRenderer {
    public Component getTreeCellRendererComponent(
                        JTree tree,
                        Object value,
                        boolean sel,
                        boolean expanded,
                        boolean leaf,
                        int row,
                        boolean hasFocus) {

        Object obj = ((DefaultMutableTreeNode)value).getUserObject();
          JLabel leafNode = new JLabel();
          leafNode.setToolTipText("This is a Test Node");
          return leafNode;

19 )   SwingUtilities invokeLater

You can call invokeLater() from any thread to request the event-dispatching threadto
run certain code. You must put this code in the run() method of a Runnableobject and
specify the Runnable object as the argument to
// Called from non-UI thread
private void runQueries() {
  for (int i = 0; i < noQueries; i++) {
private void updateProgress(final int queryNo) {
  SwingUtilities.invokeLater(new Runnable() {
    public void run() {
      // Here, we can safely update the GUI
      // because we'll be called from the
      // event dispatch thread
      statusLabel.setText("Query: " + queryNo);