Using Apache’s Xerces SAX parser

Download the Xerces Java parser at http://xml.apache.org/xerces2-j/index.html. Adjust your classpath and specify that you want to use the Xerces parser.

Programmatically:

import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import java.io.*;
 
public class Main 
{
   public static void main(String []args) {
      try {
         SAXParserFactory factory = new org.apache.xerces.jaxp.SAXParserFactoryImpl();    
         SAXParser parser = factory.newSAXParser();
 
         InputSource is = new InputSource(new FileReader("example.xml"));
         parser.parse(is, new DefaultHandler());
      }
      catch(ParserConfigurationException e) {
         e.printStackTrace();
      }
      catch(SAXException e) {
         e.printStackTrace();
      }
      catch(IOException e) {
         e.printStackTrace();
      }        
   }
}

Declaratively:

   java -Djavax.xml.parsers.SAXParserFactory=org.apache.xerces.jaxp.SAXParserFactoryImpl Main

Traversing a DOM tree using a TreeWalker in Java

(DOM Level 2!) TreeWalker allows you to navigate a DOM tree. You can specify the view on the tree with whatToShow flags and a NodeFilter (for an example on using a NodeFilter, check out How do I traverse a DOM tree using a NodeIterator).

Once you have a TreeWalker instance, you can navigate through the structure using various methods that speak for themselves. Check out the API docs for more information: TreeWalker, NodeFilter.

customers.xml (!!remove the space between ? and xml):

<? xml version="1.0" encoding="UTF-8"?>
<customers>
   <customer id="C12345">
      <name>Joris Van den Bogaert</name>
      <address>
         <addressline>Handelskaai 3</addressline>
         <zip>1000</zip>
         <location>Brussels</location>
         <country>BELGIUM</country>
      </address>
   </customer>
   <customer id="C23495">
      <name>John Doe</name>
      <address>
         <addressline>5, S 5th Ave.</addressline>
         <zip>59715</zip>
         <location>Bozeman, MT</location>
         <country>US</country>
      </address>
   </customer>
   <customer id="C03429">
      <name>John Babcock</name>
      <address>
         <addressline>73, Broad street</addressline>
         <zip>06418</zip>
         <location>Chester, CT</location>
         <country>US</country>
      </address>
   </customer>
   <customer id="C12345">
      <name>Dominique Bodard</name>
      <address>
         <addressline>21-23, Rue de Madrid</addressline>
         <zip>75008</zip>
         <location>Paris</location>
         <country>FRANCE</country>
      </address>
   </customer>
</customers>

Main.java:

import org.w3c.dom.*;
import org.w3c.dom.traversal.*;
  
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
 
import java.io.*;
   
public class Main
{
   public static void main(String []args) {
      Document doc;
  
      try {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         doc = db.parse(new File("customers.xml")); 
 
         if (!doc.isSupported("Traversal", "2.0")) {
            System.out.println("Traversal not supported in your parser version");
            System.exit(1);
         }
 
         DocumentTraversal dt = (DocumentTraversal) doc;
         TreeWalker walker = dt.createTreeWalker(doc, 
                                                 NodeFilter.SHOW_ALL, 
                                                 null, 
                                                 true);
  
         outputNode(walker.getCurrentNode());  // #document
         outputNode(walker.nextNode());        // customers
         outputNode(walker.nextNode());        // #text
         outputNode(walker.nextNode());        // customer
         outputNode(walker.nextNode());        // #text
         outputNode(walker.nextNode());        // name
         outputNode(walker.lastChild());       // #text [Joris Van den Bogaert]
         outputNode(walker.nextNode());        // #text
         outputNode(walker.nextNode());        // address
         outputNode(walker.previousSibling()); // #text
         outputNode(walker.nextNode());        // address
         outputNode(walker.nextNode());        // #text
         outputNode(walker.parentNode());      // address
         outputNode(walker.nextNode());        // #text
         outputNode(walker.nextSibling());     // addressline
         outputNode(walker.nextNode());        // #text [Handelskaai 3]
         outputNode(walker.previousNode());    // addressline
         outputNode(walker.parentNode());      // address
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
 
   public static void outputNode(Node node) {
      System.out.print(node.getNodeName());
      if (node.getNodeType() == Node.TEXT_NODE && !node.getNodeValue().trim().equals("")) {
         System.out.print(" [" + node.getNodeValue() + "]");
      }
      System.out.println();
   } 
}

outputs:

#document
customers
#text
customer
#text
name
#text [Joris Van den Bogaert]
#text
address
#text
address
#text
address
#text
addressline
#text [Handelskaai 3]
addressline
address

Update rows from a database table

Check out the MySQL syntax for UPDATE here.

Here’s an example that modifes a value in the customer table. You need to create a Statement object from a Connection and invoke executeUpdate on it, passing it the SQL UPDATE command. It returns a ResultSet containing the database rows that match your query. You can then iterate over the rows with the next method. The first call to next will position the “cursor” to the first row. You can get a particular column in that row with the getXXX methods, specifying either the column index or the column name. Make sure the database column type and the resulting variable type match, or a proper conversion is done. If types don’t match, a Bad format SQLException is thrown.

Main.java:

import java.util.*;
import java.sql.*;
  
public class Main {
   public static void main(String []args) {
      try {
         Database db = new Database("org.gjt.mm.mysql.Driver",
                                    "jdbc:mysql://192.168.0.1/esus",
                                    "joris",
                                    "mypass");
         Connection con = db.getConnection();
         CustomerDAO custDAO = new CustomerDAO(con);
 
         printCollection(custDAO.getAllRows()); 
 
         Customer cust = custDAO.getCustomer("Joris Van den Bogaert");
         if (cust != null) {
            cust.setEmail("joris_vandenbogaert1@yahoo.com");
            custDAO.updateEmail(cust);
         }
  
         System.out.println();
         printCollection(custDAO.getAllRows()); 
         db.close();
      }
      catch(DatabaseException e) {
         e.printStackTrace();
      }
   }
 
   public static void printCollection(Collection c) {
      Iterator iter = c.iterator();
      while (iter.hasNext()) {
         System.out.println(iter.next());
      }
   }
}
 
class Customer
{
   private String name;
   private String email;
 
   public Customer() { }
 
   public Customer(String name, String email) {
      setName(name);
      setEmail(email);
   }
  
   public void setName(String name) {
      this.name = name;
   }
 
   public void setEmail(String email) {
      this.email = email;
   }
 
   public String getName() {
      return name;
   }
 
   public String getEmail() {
      return email;
   }
 
   public String toString() {
      return "Customer [name=" + getName() + ", email=" + getEmail() + "]";
   }
}
 
class Database
{
   Connection connection = null;
  
   public Database(String driver, String url, String user, String pass) 
                      throws DatabaseException 
   {
      try {
         Class.forName(driver).newInstance();
 
         connection = DriverManager.getConnection(url, user, pass);
      }
      catch(Exception e) {
         throw new DatabaseException(e.getMessage());
      }
   }
 
   public Connection getConnection() {
      return connection;
   }
 
   public void close() throws DatabaseException {
      try {
         connection.close();
      }
      catch(Exception e) {
         throw new DatabaseException(e.getMessage());
      }
   } 
}   
 
class DatabaseException extends Exception {
   public DatabaseException() {
   }
 
   public DatabaseException(String message) {
      super(message);
   }
}
 
class CustomerDAO 
{
   Connection connection = null;
 
   public CustomerDAO(Connection connection) {
      this.connection = connection;
   }
 
   public void updateEmail(Customer cust) throws DatabaseException {
      try {
         Statement stmt = connection.createStatement();
 
         stmt.executeUpdate("UPDATE customers SET email = '" + cust.getEmail() + "' " +
                            "WHERE name = '" + cust.getName() + "'");
         stmt.close();      
      }
      catch(SQLException e) {
         throw new DatabaseException(e.getMessage());
      }
   }
 
   public Customer getCustomer(String name) throws DatabaseException {
      try {
         Statement stmt = connection.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT * FROM customers " +
                                          "WHERE name='" + name + "'");
         if (rs.next()) {
            Customer cust = new Customer();
            cust.setName(rs.getString("name"));
            cust.setEmail(rs.getString("email"));
            return cust;
         }
      }
      catch(SQLException e) {
         throw new DatabaseException(e.getMessage());
      }
 
      return null;
   } 
 
   public Collection getAllRows() throws DatabaseException {
      try {
         ArrayList al = new ArrayList();
 
         Statement stmt = connection.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT * FROM customers");
         while (rs.next()) {
            Customer cust = new Customer();
            cust.setName(""+rs.getString("name"));
            cust.setEmail(rs.getString("email"));
            al.add(cust);
         }
         
         stmt.close();
 
         return al;
      }
      catch(SQLException e) {
         throw new DatabaseException(e.getMessage());
      }
   }
}

outputs:

Customer [name=Joris Van den Bogaert, email=joris1@esus.com]
Customer [name=Alicia Kolesnikova, email=alicia1@esus.com]

Customer [name=Joris Van den Bogaert, email=joris_vandenbogaert1@yahoo.com]
Customer [name=Alicia Kolesnikova, email=alicia1@esus.com]

Returning an image stored in mysql with a servlet

To answer this, I created a table images in a test database and stored the esus logo in it.

mysql> create table images (imageuid int(10) not null auto_increment, 
name varchar(30), data blob, length int(6), primary key(imageuid));
Query OK, 0 rows affected (0.12 sec) 
mysql> desc images;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| imageuid | int(10)     |      | PRI | NULL    | auto_increment |
| name     | varchar(30) | YES  |     | NULL    |                |
| length   | int(6)      | YES  |     | NULL    |                |
| data     | blob        | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+

To save an image in this table, use the following code and specify the image at command line. Use a JPG image, as the MIME content type for the servlet we’ll write will be image/jpeg.

Main.java:

import java.util.*;
import java.text.*;
import java.sql.*;
import java.io.*;  
 
public class Main {
   public static void main(String []args) throws Exception {
      try {
         if (args.length != 1) {
            System.out.println("Usage: java Main <img>");
            System.exit(1);
         }
 
         Class.forName("org.gjt.mm.mysql.Driver").newInstance();
         Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/testdb", 
                                                       "",
                                                       "");
 
         File file = new File(args[0]);
         FileInputStream fis=new FileInputStream(file);
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         byte buf[]=new byte[1024];
         int length=-1;
         while((length=fis.read(buf))!=-1) {
            baos.write(buf,0,length);
         }
 
         PreparedStatement insertStmt = conn.prepareStatement(
                                       "INSERT INTO images (name, length, data) " +
                                       "VALUES (?, ?, ?)");
         insertStmt.setString(1, file.getName());
         insertStmt.setInt(2, (int) file.length());
         insertStmt.setBytes(3, baos.toByteArray());
         insertStmt.execute();
 
         fis.close();
         baos.close();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}

The servlet that delivers the image to the browser looks just like any other one, except that the MIME content-type attribute is set to image/jpeg (use image/gif for GIF files). The rest of the code handles the reading of the image from the mysql table given its unique index.

Servlet GetImage.java:

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.sql.*;
import java.io.*;
 
public class GetImage extends HttpServlet {
 
   public void doGet(
       HttpServletRequest request,
       HttpServletResponse response)
         throws ServletException, IOException {
 
     response.setContentType("image/jpeg");
 
     ServletOutputStream sos = response.getOutputStream();
 
     int imageuid = Integer.parseInt(getValues(request, "imageuid"));
     byte[] buf = getImageFromDB(imageuid);
 
     sos.write(buf);
 
     sos.flush();
  }
 
   public byte[] getImageFromDB(int imageuid) {
      byte[] buffer = null;
 
      try {
         Class.forName("org.gjt.mm.mysql.Driver").newInstance();
         Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/testdb", 
                                                       "",
                                                       "");
 
         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT name, length, data FROM images " +
                                          "where imageuid = " + imageuid);
      
         if (rs.next()) {
            String name = rs.getString("name");
            int length = rs.getInt("length");
            buffer = rs.getBytes("data");
         }
      }
      catch(Exception e) {
         e.printStackTrace();
      }
 
      return buffer;
   }
 
   public String getValues(HttpServletRequest request, String name) {
      String retVal = "";
 
      String values[] = request.getParameterValues(name);
      if (values == null) {
      }
      else if (values.length == 1) {
         retVal = values[0];
      }
      else {
         for (int i=0; i<values.length; i++) {
            retVal += values[i] + ", ";
         }
      }
 
      return retVal;
   }
}

You can now use the reference to this servlet in an img src HTML tag:

<html>
<body>
<center><img src="http://localhost:8080/servlet/GetImage?imageuid=1"></center>
</body>
</html>

Creating an editable JList

Courtesy of Nobuo Tamemasa (http://www2.gol.com/users/tame/swing/examples/JTableExamples1.html)



EditableListExample.java:

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
 
/**
 * @version 1.0 12/24/98
 */
public class EditableListExample extends JFrame {
 
  public EditableListExample() {
    super(&quot;Editable List Example&quot;);
    
    String[] data = {&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;e&quot;,&quot;f&quot;,&quot;g&quot;};
    
    JList list = new JList( data );
    JScrollPane scrollList = new JScrollPane( list );
    scrollList.setMinimumSize(new Dimension(100,80));
    Box listBox = new Box(BoxLayout.Y_AXIS);
    listBox.add(scrollList);
    listBox.add(new JLabel(&quot;JList&quot;));
         
    DefaultTableModel dm = new DefaultTableModel();
    Vector dummyHeader = new Vector();
    dummyHeader.addElement(&quot;&quot;);
    dm.setDataVector(
      strArray2Vector(data),
      dummyHeader);
    JTable table = new JTable( dm );
    table.setShowGrid(false);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scrollTable = new JScrollPane( table );
    scrollTable.setColumnHeader(null);
    scrollTable.setMinimumSize(new Dimension(100,80));
    Box tableBox = new Box(BoxLayout.Y_AXIS);
    tableBox.add(scrollTable);
    tableBox.add(new JLabel(&quot;JTable&quot;));
    
    Container c = getContentPane();
    c.setLayout(new BoxLayout(c, BoxLayout.X_AXIS));
    c.add(listBox);
    c.add(new JSeparator(SwingConstants.VERTICAL));
    //c.add(new JLabel(&quot;test&quot;));
    //c.add(new JSeparator(SwingConstants.HORIZONTAL));
    c.add(tableBox);
    setSize( 220, 130 );
    setVisible(true);
  } 
   
  private Vector strArray2Vector(String[] str) {
    Vector vector = new Vector();
    for (int i=0;i&lt;str.length;i++) {
      Vector v = new Vector();
      v.addElement(str[i]);
      vector.addElement(v);
    }
    return vector;
  }

  public static void main(String[] args) {
    final EditableListExample frame = new EditableListExample();
    frame.addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent e ) {
        System.exit(0);
      }
    });
  }
}

Using the JDBCRealm

Tomcat supports Container Managed Security. You don’t need to package your Servlets or JSPs with ugly authentication code, let Tomcat do it for you!

A Realm is a simply a collection of usernames, passwords and roles. This Q/A deals with how to store this information in a database table and integrate it with Tomcat.

A user has a password and can have multiple roles. You can give access to a resource (or a set of resources, eg. *.jsp) by associating it with one or more roles.

For example: suppose you want all JSP’s under the subdirectory /protected to be accessible by only the users that have the (custom) role member. You can declaratively do this in web.xml:

<web-app>   
   <security-constraint>      
      <web-resource-collection>         
         <web-resource-name>admin</web-resource-name>         
         <url-pattern>/protected/*.jsp</url-pattern>      
      </web-resource-collection>      
      <auth-constraint>         
         <role-name>member</role-name>         
      </auth-constraint>   
   </security-constraint>   
</web-app>

So, where are the users/passwords that have the member role? That depends on the type of Realm you’re using. A MemoryRealm stores this information in a file (see TOMCAT-HOME/conf/tomcat-users.xml). A JDBCRealm uses a database.

So let’s create a web application with the protected directory protected. All members having either role silver or role gold are allowed to access the resources in that directory.

Here is how our new web.xml looks like:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<web-app>   
   <security-constraint>      
      <web-resource-collection>         
         <web-resource-name>admin</web-resource-name>         
         <url-pattern>/protected/*</url-pattern>      
      </web-resource-collection>      
      <auth-constraint>         
         <role-name>Silver</role-name>         
         <role-name>Gold</role-name>         
      </auth-constraint>   
   </security-constraint>
   
   <login-config>
      <auth-method>BASIC</auth-method>      
      <realm-name>Log In</realm-name>
   </login-config>
</web-app>

Note the login-config tag. It specifies how a user should authenticate. We use BASIC authentication which will cause a popup to appear whenever an unauthenticated user tries to access one of the protected resources:

Authentication information will be stored in a database and accessed with a JDBC driver. In this example, we use mysql with the driver MySQL Connector/J (formerly mm.mysql).
Download the JAR file (mm.mysql-2.0.4-bin.jar) and store it in [TOMCAT-HOME]/common/lib, if it will be only visible by your web applications or [TOMCAT-HOME]/server/lib if it’s used by Tomcat 4 as well.

Modify [TOMCAT-HOME]/conf/server.xml to configure Tomcat to use the database as an authentication mechanism. You can host the following tag in the Engine, Host or Context element, depending on the scope you want (inside Engine = share across all web applications and all virtual hosts, inside Host = share accross all web applications of that particular host, inside Context = use this Realm only for this web application).

      <Realm className="org.apache.catalina.realm.JDBCRealm" debug="00"
             driverName="org.gjt.mm.mysql.Driver"
             connectionURL="jdbc:mysql://localhost/esusdb"
             connectionName=""
             connectionPassword=""
             userTable="members"
             userNameCol="username"
             userCredCol="password"
             userRoleTable="memberroles"
             roleNameCol="role" /> 
  • driverName specifies the JDBC driver to be used (added previously to the lib directory).
  • connectionURL specifies the database URL to connect to.
  • connectionName and connectionPassword are needed if your database is password protected.
  • userTable specifies the table in your database in which authentication information is stored. It should contain a user per row, with the username/password stored in the columns specified in userNameCol and userCredCol.
  • userRoleTable specifies the table in your database that contains an association between the users and their roles. It should contain at least the columns specified in userNameCol and roleNameCol.

Now create the necessary mysql database tables:

C:mysqlbin>mysql
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 5 to server version: 3.23.47-nt
 
Type 'help;' or 'h' for help. Type 'c' to clear the buffer.
 
mysql> create database esusdb;
Query OK, 1 row affected (0.00 sec)
 
mysql> use esusdb;
Database changed
mysql> create table members (uid int(10) not null primary key, username varchar(
20) not null, password varchar(20) not null);
Query OK, 0 rows affected (0.00 sec)
 
mysql> create table memberroles (username varchar(20) not null, role varchar(10)
 not null, primary key (username, role));
Query OK, 0 rows affected (0.01 sec)
 
mysql> desc members;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| uid      | int(10)     |      | PRI | 0       |       |
| username | varchar(20) |      |     |         |       |
| password | varchar(20) |      |     |         |       |
+----------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
 
mysql> desc memberroles;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| username | varchar(20) |      | PRI |         |       |
| role     | varchar(10) |      | PRI |         |       |
+----------+-------------+------+-----+---------+-------+
2 rows in set (0.02 sec)
 
mysql>

…and insert some data:

 
mysql> insert into members values (1, 'John', '123456');
Query OK, 1 row affected (0.00 sec)
 
mysql> insert into members values (2, 'Lisa', '654321');
Query OK, 1 row affected (0.00 sec)
 
mysql> insert into memberroles values ('John', 'Gold');
Query OK, 1 row affected (0.00 sec)
 
mysql> insert into memberroles values ('Lisa', 'Silver');
Query OK, 1 row affected (0.00 sec)
 
mysql>

We have created two users: John with role Gold and Lisa with role Silver.

Our web application will use the JDBCRealm to connect to this database and authenticate users.
To create the example web application, create a directory structure as follows:

loginexample2
   |
   +- index.jsp
   |
   +--- protected
   |       |
   |       +- confidential.jsp
   |
   +--- WEB-INF
           |
           +- web.xml

Use the deployment descriptor web.xml that is shown above. The rest of the example JSP’s can be cut’n’pasted here:

loginexample2/index.jsp:

<html>
<body>
Access <a href="./protected/confidential.jsp">protected resource</a>
</body>
</html>

loginexample2/protected/confidential.jsp:

<html>
<body>
<%
   if (request.isUserInRole("Gold")) {
%>
   You have the GOLD role<br>
<% 
   }
   if (request.isUserInRole("Silver")) {
%>
   You have the SILVER role<br>
<%
   }
%>
<br> 
You have successfully accessed the protected resource!
</body>
</html>

Go to http://localhost:8080/loginexample2/index.jsp and try to access the protected resource. A popup window will show up. Notice that, once you’re logged in, you cannot log out, except by closing the browser window.

Using a RadioButton 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.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, 300, 200);
      shell.setText("SWT RadioButton Demonstration");
      shell.setLayout(new GridLayout());
 
      Group buttonGroup = new Group(shell, SWT.NONE);
      GridLayout gridLayout = new GridLayout();
      gridLayout.numColumns = 1;
      buttonGroup.setLayout(gridLayout);
      buttonGroup.setLayoutData(new GridData(GridData.FILL_VERTICAL));
      
      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.RADIO);
      button1.setText("orange");
      button1.addSelectionListener(selectionListener);
      Button button2 = new Button(buttonGroup, SWT.RADIO);
      button2.setText("pear");
      button2.addSelectionListener(selectionListener);
      Button button3 = new Button(buttonGroup, SWT.RADIO);
      button3.setText("apple");
      button3.addSelectionListener(selectionListener);
      
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      display.dispose();
   }
}

Creating an SWT FontDialog?

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.Color;
import org.eclipse.swt.graphics.FontData;
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.FontDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
 
public class Main { 
   static Display display;
   static Shell shell;
   static Color color;
    
   public static void main(String[] args) {
      display = new Display();
      shell = new Shell(display);
 
      // pos x, pos y, width, height
      shell.setBounds(200, 200, 400, 200);
      shell.setText("SWT FontDialog Demonstration");
      shell.setLayout(new GridLayout());
 
      final Group buttonGroup = new Group(shell, SWT.NONE);
      GridLayout gridLayout = new GridLayout();
      gridLayout.numColumns = 3;
      buttonGroup.setLayout(gridLayout);
      buttonGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
       
      final Button directoryDialogButton = new Button(buttonGroup, SWT.PUSH);
      directoryDialogButton.setText("Open FontDialog");
      Label label1 = new Label(buttonGroup, SWT.NONE);
      label1.setText("Font selected:");
      final Label label2 = new Label(buttonGroup, SWT.NONE);      
      label2.setText("");
 
      SelectionListener selectionListener = new SelectionAdapter () {
         public void widgetSelected(SelectionEvent event) {
            FontDialog dialog = new FontDialog (shell, SWT.MODELESS);
            dialog.setText("Select Font");
            FontData result = dialog.open();
            label2.setText("" + result);
            buttonGroup.layout();
         };
      };
       
      directoryDialogButton.addSelectionListener(selectionListener);
       
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      if (color != null && !color.isDisposed()) {
         color.dispose();
      }
      display.dispose();
   }
}

Creating a Styled Text(area)

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
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, 300, 200);
      shell.setText("SWT Text Demonstration");
      shell.setLayout(new GridLayout());
 
      shell.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
 
      StyledText styledText = new StyledText(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.WRAP);
      styledText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
       
      styledText.setText("Did you know..." +
                         "nn" +
                         "It is impossible to lick your elbow." +
                         "nnnnnnnnnnnnnnn" +
                         "Over 75% of people who read thisn" +
                         "will try to lick their elbow.");
  
      StyleRange boldStyle = new StyleRange(0, 20, null, null, SWT.BOLD);
      styledText.setStyleRange(boldStyle);
 
      Color foreColor = display.getSystemColor (SWT.COLOR_RED);
      StyleRange foreStyle = new StyleRange(20, 20, foreColor, null, SWT.NORMAL);
      styledText.setStyleRange(foreStyle);
       
      Color backColor = display.getSystemColor (SWT.COLOR_DARK_YELLOW);
      StyleRange backStyle = new StyleRange(40, 20, null, backColor, SWT.NORMAL);
      styledText.setStyleRange(backStyle);
 
      StyleRange foreBackStyle = new StyleRange(60, 20, foreColor, backColor, SWT.NORMAL);
      styledText.setStyleRange(foreBackStyle);
             
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
       
      display.dispose();
   }
}