Clouds
Home

Core Java

Java Fundamentals 1

Java Fundamentals 2

Java Fundamentals 3

Java Swing

Java Applet

Java Memory & Performance

Java Swing Interview Questions


What is the difference between AWT and Swing?

Swing provides a richer set of components than AWT. They are 100% Java-based.

There are a few other advantages to Swing over AWT:

  • Swing provides both additional components like JTable, JTree etc and added functionality to AWT-replacement components.
  • Swing components can change their appearance based on the current "look and feel" library thatís being used.
  • Swing components follow the Model-View-Controller (MVC) paradigm, and thus can provide a much more flexible UI.
  • Swing provides "extras" for components, such as: icons on many components, decorative borders for components, tool tips for components etc.
  • Swing components are lightweight (less resource intensive than AWT).
  • Swing provides built-in double buffering (which means an off-screen buffer [image] is used during drawing and then the resulting bits are copied onto the screen. The resulting image is smoother, less flicker and quicker than drawing directly on the screen).
  • Swing provides paint debugging support for when you build your own component i.e.-slow motion rendering.

Swing also has a few disadvantages:

  • If youíre not very careful when programming, it can be slower than AWT (all components are drawn).
  • Swing components that look like native components might not behave exactly like native components.

How will you go about building a Swing GUI client?

The steps involved in building a Swing GUI are:
  • Firstly, you need a container like a Frame, a Window, or an Applet to display components like panels, buttons, text areas etc. The job of a container is to hold and display components. A container is also a component (note: uses a composite design pattern). A JPanel is a container as well.

    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    public class MyFrame extends JFrame {
      public static void main(String[] args) {
        JFrame frame = new JFrame("Frame Title");
        ...// rest of the code to follow
      }
    }


  • Create some components such as panels, buttons, text areas etc.

    //create a component to add to the frame
    final JTextArea comp = new JTextArea(); JButton btn = new JButton("click");


  • Add your components to your display area and arrange or layout your components using the LayoutManagers. You can use the standard layout managers like FlowLayout, BorderLayout, etc. Complex layouts can be simplified by using nested containers for example having JPanels within JPanels and each JPanel can use its own LayoutManager. You can create components and add them to whichever JPanels you like and JPanels can be added to the JFrameís content pane.

    // Add the component to the frame's content pane;
    // by default, the content pane has a border layout
    frame.getContentPane().add(comp, BorderLayout.CENTER);
    frame.getContentPane().add(btn, BorderLayout.SOUTH);


  • Attach listeners to your components. Interacting with a Component causes an Event to occur. To associate a user action with a component, attach a listener to it. Components send events and listeners listen for events. Different components may send different events, and require different listeners. The listeners are interfaces, not classes.

    //Anonymous inner class registering a listener
    // as well as performing the action logic.
    btn.addActionListener( new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        comp.setText("Button has been clicked");
      }
    });


  • Show the frame.

    // set the frame size and Show the frame
    int width = 300;
    int height = 300;
    frame.setSize(width, height);
    frame.setVisible(true);


Explain the Swing Action architecture?

The Swing Action architecture is used to implement shared behavior between two or more user interface components. For example, the menu items and the tool bar buttons will be performing the same action no matter which one is clicked. Another distinct advantage of using actions is that when an action is disabled then all the components, which use the Action, become disabled.
Design Pattern: The javax.swing.Action interface extends the ActionListener interface and is an abstraction of a command that does not have an explicit UI component bound to it. The Action architecture is an implementation of a command design pattern. This is a powerful design pattern because it allows the separation of controller logic of an application from its visual representation. This allows the application to be easily configured to use different UI elements without having to re-write the control or call-back logic.
Defining action classes:

class FileAction extends AbstractAction {
    //Constructor
    FileAction(String name) {
      super(name);
    }
    public void actionPerformed(ActionEvent ae){
      //add action logic here
    }
}


To add an action to a menu bar:

JMenu fileMenu = new JMenu("File");
FileAction newAction = new FileAction("New");
JMenuItem item = fileMenu.add(newAction);
item.setAccelarator(KeyStroke.getKeyStroke(ĎNí, Event.CTRL_MASK));


To add action to a toolbar

private JToolBar toolbar = new JToolBar(); toolbar.add(newAction);

So, an action object is a listener as well as an action.

How does Swing painting happen? How will you improve the painting performance?

If you want to create your own custom painting code or troubleshoot your Swing components, then you need to understand the basic concept of Swing painting.
  • Swing GUI painting starts with the highest component that needs to be repainted and works it way down the hierarchy of components. This painting process is coordinated by the AWT painting system, but Swing repaint manager and double-buffering code, which means an off-screen buffer [image] is used during drawing and then the resulting bits are copied onto the screen. The resulting image is smoother, less flicker and quicker than drawing directly on the screen.
  • Swing components generally repaint themselves whenever necessary. For example when you invoke the setTextt() on a component etc. This happens behind the scenes using a callback mechanism by invoking the repaint() method. If a componentís size or position needs to change then the call to revalidate() method precedes the call to repaint() method.
  • Like event handling code, painting code executes on the event-dispatching thread. So while an event is being handled, no painting will occur and similarly while painting is happening no events will take place.
  • You can provide your own painting by overriding the paintComponent() method. This is one of 3 methods used by JComponents to paint themselves.

    public class MyFramePainting extends JFrame {
      public static void main(String[] args) {
        JFrame frame = new JFrame("Frame Title");
        MyPanel panel = new MyPanel();
        panel.setOpaque(true); //if opaque (i.e. solid) then Swing painting system
        //does not waste time painting behind the component.
        panel.setBackground(Color.white);
        panel.setLayout(new FlowLayout());
        ...//add to contentPane, display logic etc
      }
    }

    public class MyPanel extends JPanel implements MouseListener{
      Color col = Color.blue;
      public void paintComponent(Graphics gr){
        super.paintComponent(gr);
        gr.setColor(col);
        gr.drawLine(5,5, 200,200);
      }
      public MyPanel(){
        addMouseListener(this); //i.e the Panel itself
      }
      public void mouseClicked(MouseEvent ev){
        col = Color.red;
        repaint(); //invokes paintComponent(). Never invoke paintComponent() method directly
      }
      ...//other mouse events like onMousePressed etc
    }


By default, the paintComponent() method paints the background if the component is opaque, then it performs any custom painting. The other two methods are paintBorder(Graphics g) and paintChildren(Graphics g),which tells to paint any border and paint any components contained by this component respectively. You should not invoke or override these two methods.

How will you improve the painting performance?

  • On components with complex output, the repaint() method should be invoked with arguments which define only the clip rectangle that needs updating (rectangle origin is on top left corner). Note: No paintXXXX() methods (including paint() method) should not be explicitly invoked. Only repaint() method can be explicitly invoked (which implicitly calls paintComponent() method) and only paintComponent() should be overridden if required.

    public void mouseClicked(MouseEvent ev){
      col = Color.red;
      repaint(0,0,50,50); //invokes paintComponent with a rectangle. The origin is at top left.
    }


  • You should never turn off double buffering for any Swing components.
  • The Swing painting efficiency can be optimized by the following two properties:
    opaque: If the opaque (i.e. solid) property is set to true with myComponent.setOpaque(true) then the Swing painting system does not have to waste time trying to paint behind the component hence improves performance.
    optimizedDrawingEnabled: This is a read only property (isOptimizedDrawingEnabled()) in JComponent, so the only way components can change the default value is to subclass and override this method to return the desired value. Itís always possible that a non-ancestor component in the containment tree could overlap your component. In such a case the repainting of a single component within a complex hierarchy could require a lot of tree traversal to ensure 'correct' painting occurs.
    true: The component indicates that none of its immediate children overlap. false: The component makes no guarantees about whether or not its immediate children overlap

    Explain the Swing event dispatcher mechanism?

    Swing components can be accessed by the Swing event dispatching thread. A few operations are guaranteed to be thread-safe but most are not. Generally the Swing components should be accessed through this eventdispatching thread. The event-dispatching thread is a thread that executes drawing of components and eventhandling code. For example the paint() and actionPerformed() methods are automatically executed in the eventdispatching thread. Another way to execute code in the event-dispatching thread from outside event-handling or drawing code, is using SwingUtilities invokeLater() or invokeAndWait() method. Swing lengthy initialization tasks (e.g. I/O bound and computationally expensive tasks), should not occur in the event-dispatching thread because this will hold up the dispatcher thread. If you need to create a new thread for example, to handle a job thatís computationally expensive or I/O bound then you can use the thread utility classes such as SwingWorker or Timer without locking up the event-dispatching thread.
    • SwingWorker: creates a background thread to execute time consuming operations.
    • Timer: creates a thread that executes at certain intervals.
    However after the lengthy initialization the GUI update should occur in the event dispatching thread, for thread safety reasons. We can use invokeLater() to execute the GUI update in the event-dispatching thread. The other scenario where invokeLater() will be useful is that the GUI must be updated as a result of non-AWT event.

    What do you understand by MVC as used in a JTable?

    MVC stands for Model View Controller architecture. Swing "J" components (e.g. JTable, JList, JTree etc) use a modified version of MVC. MVC separates a model (or data source) from a presentation and the logic that manages it.
    • Component (e.g. JTable, JTree, and JList): coordinates actions of model and the UI delegate. Each generic component class handles its own individual view-and-controller responsibilities.
    • Model (e.g. TableModel): charged with storing the data.
    • UIDelegate: responsible for getting the data from model and rendering it to screen. It delegates any look-andfeel aspect of the component to the UI Manager.

    Explain layout managers?

    Layout managers are used for arranging GUI components in windows. The standard layout managers are:
    • FlowLayout: Default layout for Applet and Panel. Lays out components from left to right, starting new rows if necessary.
    • BorderLayout: Default layout for Frame and Dialog. Lays out components in north, south, east, west and center. All extra space is placed on the center.
    • CardLayout: stack of same size components arranged inside each other. Only one is visible at any time. Used in TABs.
    • GridLayout: Makes a bunch of components equal in size and displays them in the requested number of rows and columns.
    • GridBagLayout: Most complicated but the most flexible. It aligns components by placing them within a grid of cells, allowing some components to span more than one cell. The rows in the grid arenít necessarily all the same height, similarly, grid columns can have different widths as well.
    • BoxLayout: is a full-featured version of FlowLayout. It stacks the components on top of each other or places them in a row.
    Complex layouts can be simplified by using nested containers for example having panels within panels and each panel can use its own LayoutManager. It is also possible to write your own layout manager or use manual positioning of the GUI components.
    Design pattern: The AWT containers like panels, dialog boxes, windows etc do not perform the actual laying out of the components. They delegate the layout functionality to layout managers. The layout managers make use of the strategy design pattern, which encapsulates family of algorithms for laying out components in the containers. If a particular layout algorithm is required other than the default algorithm, an appropriate layout manager can be instantiated and plugged into the container. For example, panels by default use the FlowLayout but it can be changed by executing:

    panel.setLayout(new GridLayout(4,5));

    This enables the layout algorithms to vary independently from the containers that use them. This is one of the key benefits of the strategy pattern.

    Explain the Swing delegation event model?

    In this model, the objects that receive user events notify the registered listeners of the user activity. In most cases the event receiver is a component.
    • Event Types: ActionEvent, KeyEvent, MouseEvent, WindowEvent etc.
    • Event Processors: JButton, JList etc.
    • EventListeners: ActionListener, ComponentListener, KeyListener etc.


    Java Applet >>>


    Home Clouds