Underlining a cell in a JTable

The easiest way is to use HTML in your text, check How do I create a JLabel with the text underlined?

But here’s a code sample that does not make use of the HTML feature. It underlines all Integers in the JTable whose values are between 1970 and 1980.

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   public Main() {
      super("Table example, Wines from Bordeaux");
 
      Object[][] tabledata = {
            { "Chateau Meyney, St. Estephe", 	   new Integer(1994), "$18.75"},
            { "Chateau Montrose, St. Estephe", 	   new Integer(1975), "$54.25" },
            { "Chateau Gloria, St. Julien", 	   new Integer(1993), "$22.99" },
            { "Chateau Beychevelle, St. Julien",   new Integer(1970), "$61.63" },
            { "Chateau La Tour de Mons, Margeaux", new Integer(1975), "$57.03" },
            { "Chateau Brane-Cantenac, Margeaux",  new Integer(1978), "$49.92" },
      };
 
      String columnheaders[] = { "Wine", "Vintage", "Price" };
 
      JTable table = new JTable(tabledata, columnheaders);
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
 
      UnderlineTableCellRenderer renderer = new UnderlineTableCellRenderer();
      table.setDefaultRenderer(Object.class, renderer);
      table.setRowHeight(30);
 
      JScrollPane scrollPane = new JScrollPane(table);
      getContentPane().add(scrollPane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      pack();
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}
 
class UnderlineTableCellRenderer extends DefaultTableCellRenderer 
{
   public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                                                  boolean hasFocus, int row, int column) {
      if (value instanceof Integer) {
         Integer amount = (Integer) value;
         if (amount.intValue() > 1970 && amount.intValue() < 1980) {
            return new UnderlinedJLabel("" + amount.intValue());
         }
      }
 
      return super.getTableCellRendererComponent
                      (table, value, isSelected, hasFocus, row, column);
   }
}
 
class UnderlinedJLabel extends JLabel
{
   public UnderlinedJLabel() {
   }
 
   public UnderlinedJLabel(Icon image) {
      super(image);
   }
 
   public UnderlinedJLabel(Icon image, int horizontalAlignment) {
      super(image, horizontalAlignment);
   }
 
   public UnderlinedJLabel(String text) {
      super(text);
   }
 
   public UnderlinedJLabel(String text, Icon icon, int horizontalAlignment) {
      super(text, icon, horizontalAlignment);
   }
 
   public UnderlinedJLabel(String text, int horizontalAlignment) {
      super(text, horizontalAlignment);
   }
 
   public void paint(Graphics g) {
      super.paint(g);
      underline(g);
   }
 
   protected void underline(Graphics g) {
      Insets insets = getInsets();
      FontMetrics fm = g.getFontMetrics();
      Rectangle textR = new Rectangle();
      Rectangle viewR = new Rectangle(
                                  insets.left, 
                                  insets.top, 
                                  getWidth() - (insets.right + insets.left), 
                                  getHeight() - (insets.bottom + insets.top));
  
      // compute and return location of the icons origin,
      // the location of the text baseline, and a possibly clipped
      // version of the compound label string.  Locations are computed 
      // relative to the viewR rectangle.
      String text = SwingUtilities.layoutCompoundLabel(
                         this,                        // this JLabel
                         fm,                          // current FontMetrics
                         getText(),                   // text
                         getIcon(),                   // icon
                         getVerticalAlignment(),      
                         getHorizontalAlignment(),
                         getVerticalTextPosition(),
                         getHorizontalTextPosition(), 
                         viewR,                       
                         new Rectangle(),             // don't care about icon rectangle
                         textR,                       // resulting text locations
                         getText() == null ? 0 : ((Integer)UIManager.get("Button.textIconGap")).intValue());
 
      // draw line
      int textShiftOffset = ((Integer) UIManager.get("Button.textShiftOffset")).intValue();
      g.fillRect(textR.x +
                 textShiftOffset - 4,
                 textR.y + fm.getAscent() + textShiftOffset + 2,
                 textR.width, 
                 1);
   }
}

Writing your own Tomcat Valve

You can extend from org.apache.catalina.valves.ValveBase and implement the method invoke. The following example just prints out is has been called and invokes the next Valve.

MyValve.java:

import javax.servlet.http.*;
import javax.servlet.*;
import java.util.*;
import java.io.*;
import org.apache.catalina.valves.*;
import org.apache.catalina.*;
 
public class MyValve extends ValveBase
{
   /**
    * The descriptive information related to this implementation.
    */
   private static final String info = "MyValve/1.0";
 
   /**
    * Return descriptive information about this Valve implementation.
    */
   public String getInfo() {
      return (info);
   }
 
   public void invoke(Request request, Response response, ValveContext context)
                             throws IOException, ServletException {
      // Skip logging for non-HTTP requests and responses
      if (!(request instanceof HttpRequest) ||
          !(response instanceof HttpResponse)) {
         context.invokeNext(request, response);
         return;
      }
 
      HttpRequest httpRequest   = (HttpRequest) request;
      HttpResponse httpResponse = (HttpResponse) response;
      HttpServletRequest httpServletRequest   = (HttpServletRequest) httpRequest.getRequest();
      HttpServletResponse httpServletResponse = (HttpServletResponse) httpResponse.getResponse();
 
      System.out.println("nnnMyValve invokednnn");
 
      // continue processing the request
      context.invokeNext(request, response);
   }
 
   public String toString() {
      StringBuffer sb = new StringBuffer();
      sb.append("MyValve[");
      if (container != null) {
         sb.append(container);
      }
      sb.append("]");
      return sb.toString();
   }
}

Compile it with catalina.jar and servlet.jar in your classpath and place it in /server/classes.

Making a flat SWT button

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
 
public class Main {
   public static void main(String[] args) {
      Display display = new Display();
      Shell shell = new Shell(display);
 
      // pos x, pos y, width, height
      shell.setBounds(200, 200, 400, 200);
      shell.setText("SWT Flat Button Demonstration");
      shell.setLayout(new GridLayout());
 
      Group buttonGroup = new Group(shell, SWT.NONE);
      GridLayout gridLayout = new GridLayout();
      gridLayout.numColumns = 3;
      buttonGroup.setLayout(gridLayout);
      buttonGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
  
      SelectionListener selectionListener = new SelectionAdapter () {
         public void widgetSelected(SelectionEvent event) {
            Button button = ((Button) event.widget);
            System.out.print(button.getText());
            System.out.println(" selected = " + button.getSelection());
         };
      };
       
      Button button1 = new Button(buttonGroup, SWT.PUSH | SWT.FLAT);
      button1.setText("orange");
      button1.addSelectionListener(selectionListener);
       
      Button button2 = new Button(buttonGroup, SWT.PUSH | SWT.FLAT);
      button2.setText("pear");
      button2.addSelectionListener(selectionListener);
 
      Button button3 = new Button(buttonGroup, SWT.PUSH | SWT.FLAT);
      button3.setText("apple"); 
      button3.addSelectionListener(selectionListener);
       
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      display.dispose();
   }
}

Creating a coolbar in SWT

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.CoolBar;
import org.eclipse.swt.widgets.CoolItem;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
 
public class Main {
   public static void main (String [] args) {
      Display display = new Display ();
      Shell shell = new Shell (display);
      shell.setLayout(new GridLayout());
 
      final CoolBar coolBar = new CoolBar(shell, SWT.BORDER);
      coolBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));  
 
      // create the first ToolBar
      ToolBar toolBar = new ToolBar(coolBar, SWT.NULL);
      ToolItem toolItem = new ToolItem(toolBar, SWT.PUSH);      
      toolItem.setImage(getImage("jpgIcon.gif"));
      toolItem = new ToolItem (toolBar, SWT.SEPARATOR);
      toolItem = new ToolItem(toolBar, SWT.PUSH);      
      toolItem.setImage(getImage("gifIcon.gif"));
      toolItem = new ToolItem (toolBar, SWT.SEPARATOR);
      toolItem = new ToolItem(toolBar, SWT.PUSH);      
      toolItem.setImage(getImage("tiffIcon.gif"));
      toolItem = new ToolItem (toolBar, SWT.SEPARATOR);
       
      CoolItem coolItem = new CoolItem(coolBar, SWT.NONE);
      Point size = toolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT);
      size = coolItem.computeSize(size.x, size.y);
      coolItem.setSize(size);
      coolItem.setMinimumSize(toolItem.getWidth(), size.y);
      coolItem.setControl(toolBar);
            
      // create the second ToolBar
      toolBar = new ToolBar(coolBar, SWT.BORDER);
      ToolItem item = new ToolItem (toolBar, SWT.DROP_DOWN);
      item.addSelectionListener(new DropDownSelectionListener(shell));
      item.setImage(getImage("jpgIcon.gif"));
      item = new ToolItem(toolBar, SWT.DROP_DOWN);
      item.addSelectionListener(new DropDownSelectionListener(shell));
      item.setImage(getImage("gifIcon.gif"));
      
      coolItem = new CoolItem(coolBar, SWT.NONE);
      size = toolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT);
      size = coolItem.computeSize(size.x, size.y);
      coolItem.setSize(size);
      coolItem.setMinimumSize(toolItem.getWidth(), size.y);
      coolItem.setControl(toolBar);
       
      // all the indices that will begin on a new row      
      coolBar.setWrapIndices(new int[] {0, 1});
 
      SelectionListener selectionListener = new SelectionAdapter () {
         public void widgetSelected(SelectionEvent event) {
            Button button = ((Button) event.widget);
            coolBar.setLocked(button.getSelection());
         };
      };
      
      Group buttonGroup = new Group(shell, SWT.NONE);
      GridLayout gridLayout = new GridLayout();
      gridLayout.numColumns = 1;
      buttonGroup.setLayout(gridLayout);
      buttonGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));      
      Button lockButton = new Button(buttonGroup, SWT.CHECK);
      lockButton.setText("Lock the CoolBar!");
      lockButton.addSelectionListener(selectionListener);
                 
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
   }
   
   public static Image getImage(String imageName) {
      ImageData source = new ImageData(Main.class.getResourceAsStream(imageName));
      ImageData mask = source.getTransparencyMask();
      Image image = new Image(null, source, mask);
      return image;
   }   
   
   
   static class DropDownSelectionListener extends SelectionAdapter {
      private Menu menu = null;
      private Shell shell;
      
      public DropDownSelectionListener(Shell shell) {
         this.shell = shell;
      }
      
      public void widgetSelected(SelectionEvent event) {
         System.out.println("Widget is clicked on!");
         if (menu == null) {
            // create menu if it doesn't exist already
            menu = new Menu(shell);
            MenuItem menuItem1 = new MenuItem(menu, SWT.NONE);
            menuItem1.setText("App #1");
            MenuItem menuItem2 = new MenuItem(menu, SWT.NONE);
            menuItem2.setText("App #2");
            MenuItem separatorItem = new MenuItem(menu, SWT.SEPARATOR);
            MenuItem menuItem3 = new MenuItem(menu, SWT.NONE);
            menuItem3.setText("Run...");
            
            menuItem1.addSelectionListener(new SelectionAdapter() {
               public void widgetSelected(SelectionEvent e) {
                  menu.setVisible(true);
               }
            });
         }
         
         // if user clicked on down arrow, show menu
         if (event.detail == SWT.ARROW) {
            System.out.println("... and it's the arrow!");
            if (menu.getVisible()) {
               menu.setVisible(false);
            } else { 
               final ToolItem toolItem = (ToolItem) event.widget;
               final ToolBar  toolBar = toolItem.getParent();
               
               Rectangle toolItemBounds = toolItem.getBounds();
               Point point = toolBar.toDisplay(new Point(toolItemBounds.x, toolItemBounds.y));
               menu.setLocation(point.x, point.y + toolItemBounds.height);
               menu.setVisible(true);
            }
         }
      }
   }   
} 

Get versioning information about a Java package

The following example creates a JAR file containing one class in the package com.esus.test with extra versioning information in the manifest file. The Main program prints out this info.

com/esus/test/TestClass.java:

package com.esus.test;
 
public class TestClass
{
   public void testMethod() {
      System.out.println("Hello world!");
   }
}

MANIFEST.MF:

Manifest-Version: 1.0
  
Name: com/esus/test/
Specification-Title: Test Specification
Specification-Vendor: Esus, Inc.
Specification-Version: 1.0
Implementation-Vendor: Esus, Inc.
Implementation-Title: Test Reference Implementation
Implementation-Version: 1.5

Note that you can specify this versioning information not only on package level (com/esus/test) but also on the top of the file. If no version information is found about a specific package, this general version information is returned.

To create this JAR file:

C:\myjars>dir
 Volume in drive C has no label.
 Volume Serial Number is 3C7A-79F5
 
 Directory of C:myjars
 
01/19/2003  06:55 PM    <DIR>          .
01/19/2003  06:55 PM    <DIR>          ..
01/19/2003  05:13 PM    <DIR>          com
01/19/2003  06:41 PM               268 MANIFEST.MF
               1 File(s)            268 bytes
               3 Dir(s)  34,651,611,136 bytes free
  
C:\myjars>jar cfm test.jar MANIFEST.MF com

Add test.jar to your classpath and run the following program to retrieve version information.

Main.java:

import com.esus.test.*;
 
public class Main
{
   public static void main(String []args) {
      Package pckg = TestClass.class.getPackage();
 
      System.out.println(pckg.getSpecificationTitle());
      System.out.println(pckg.getSpecificationVendor());
      System.out.println(pckg.getSpecificationVersion());
      System.out.println(pckg.getImplementationTitle());
      System.out.println(pckg.getImplementationVendor());
      System.out.println(pckg.getImplementationVersion());
   }
}

outputs:

Test Specification
Esus, Inc.
1.0
Test Reference Implementation
Esus, Inc.
1.5

Writing a Hello World JFace application

Main.java:

import org.eclipse.jface.window.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.*;
 
public class Main extends ApplicationWindow 
{
   public Main() {
      super(null);
   }
   
   protected Control createContents(Composite parent) {
      Label label = new Label(parent, SWT.PUSH);
      label.setText("Hello, world!");
      return label;
   }
   
   public static void main(String []args) {
      Main main = new Main();
      main.setBlockOnOpen(true);
      main.open();
      
      Display.getCurrent().dispose();
   }
}

What is autoboxing?

Autoboxing is the automatic conversion between primitive types and reference types. It eliminates the need to explicitely create wrapper objects for primitive types.

Main.java:

public class Main
{
   public static void main(String []args) {
      Integer n1 = 20;   // no need to "new Integer", is done automatically
   
      System.out.println(n1);
      
      int n2 = n1;
       // no need to do "n1.intValue()"
 
      System.out.println(n2);
   }
}

This means that you don’t need to create wrapper objects anymore to use primitives in collection classes.

Main.java:

import java.util.*;
 
public class Main
{
   public static void main(String []args) {
      // allow only integers to be added to the arraylist
      ArrayList<Integer> arrayList = new ArrayList<Integer>();
      
      arrayList.add(10);
      arrayList.add(20);
      arrayList.add(30);
   
      for (int i=0; i<arrayList.size(); i++) {
         System.out.println(arrayList.get(i));
      }
   }
}

How long has the VM been running

In JDK 1.5, use the RuntimeMBean management class in the java.lang.management package.

Main.java:

import java.lang.management.*;
import java.util.*;
 
public class Main
{
   public static void main(String []args) {
      RuntimeMBean mbean = ManagementFactory.getRuntimeMBean();
      while (true) {
         long uptime = mbean.getUptime();
          
         System.out.println("VM has been running for " + uptime + " ms.");
         try { Thread.sleep(1500); } catch(Exception e) { }
      }
   }
}

outputs:

VM has been running for 50 ms.
VM has been running for 1552 ms.
VM has been running for 3054 ms.
VM has been running for 4557 ms.
VM has been running for 6059 ms.
. . .

Loading properties from an XML file in JDK 1.5

ReadProps.java:

import java.util.*;
import java.io.*;

public class ReadProps
{
   public static void main(String []args) {
      Properties props = new Properties();
       
      try {
         props.loadFromXML(new FileInputStream(new File("config.xml")));
      }
      catch(IOException e) { 
         e.printStackTrace();
      }
       
      System.out.println(props);
   }
}