Applying CSS to an HTML rendered JLabel

You can set a StyleSheet on an HTMLEditorKit. It is shared by all HTMLEditorKit instances.

This example shows you how to set the margins, colors and size of any h1 used to render HTML in your Swing components.

Main.java:

import javax.swing.text.html.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
   
public class Main extends JFrame {
   public Main(StyleSheet s) {
      getContentPane().setLayout(new FlowLayout());
  
      HTMLEditorKit kit = new HTMLEditorKit();
      kit.setStyleSheet(s);
 
      final JLabel label = new JLabel("<html><h1>Socrates</h1></html>");
      getContentPane().add(label);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(300, 300);
   }
 
   public static StyleSheet loadStyleSheet(InputStream is) throws IOException
   {
      StyleSheet s = new StyleSheet();
      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      s.loadRules(br, null);
      br.close();
  
      return s;
   }
  
   public static void main(String[] args) throws Exception {
      StyleSheet s = loadStyleSheet(new FileInputStream("default.css"));
 
      (new Main(s)).show();
   }
}

default.css:

h1 {
   font-size:	24pt;
   font-weight:	bold;
   color:	red;
   margin-top:  10;
   margin-bottom:	10
}

Renaming a file using the JNDI file service provider

Here’s an example:

import javax.naming.event.*;
import javax.naming.*;
import java.util.*;
import java.io.*;
  
public class Main
{
   public static void main(String []args) {
      try {
         Properties properties = new Properties();
         properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
         properties.put(Context.PROVIDER_URL, "file:///");
 
         InitialContext ctx = new InitialContext(properties);
 
         Context context = (Context) ctx.lookup("c:\temp\");
 
         context.rename("test.txt", "test1.txt");
 
         ctx.close(); 
      }
      catch(NamingException ne) {
         ne.printStackTrace();
      }
   }
}

Creating a subdirectory using the JNDI file system provider

Use the method createSubcontext. The following example creates a subdirectory jnditest in c:temp. If the subdirectory already exists, a javax.naming.NameAlreadyBoundException is thrown.

Main.java:

import javax.naming.*;
import java.util.*;
  
public class Main
{
   public static void main(String []args) {
      try {
         Properties properties = new Properties();
         properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
         properties.put(Context.PROVIDER_URL, "file:///");
 
         Context ctx = new InitialContext(properties);
 
         // List the objects 
         Object object = ctx.lookup("c:\temp");
  
         if (object instanceof Context) {
            Context context = (Context) object;
            context.createSubcontext("jnditest");
         }
 
         ctx.close(); 
      }
      catch(NamingException ne) {
         ne.printStackTrace();
      }
   }
}

Get started with the JNDI file system provider

The JNDI architecture allows you to access various naming and directory services, through a standard interface, mainly through the Context and DirContext interfaces.

Sun has written an implementation of these interfaces to access the filesystem: the filesystem service provider. It can be downloaded from http://java.sun.com/products/jndi/serviceproviders.html.

The following example shows you how to get a File object using the filesystem service provider. Make sure you have added the following JARs to your classpath:

  providerutil.jar
  fscontext.jar

Note: if you specify a directory, you’ll get an instance of a class that implements the Context interface, a JNDI subtree.

Main.java:

import javax.naming.*;
import java.util.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      try {
         Properties properties = new Properties();
         properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
         properties.put(Context.PROVIDER_URL, "file:///");
 
         Context initialCtx = new InitialContext(properties);
 
         Object object = initialCtx.lookup("c:\autoexec.bat");
 
         if (object instanceof File) {
            System.out.println(((File) object).getName());
         }
         else if (object instanceof Context) {
            System.out.println("You have specified a directory");
         }
      }
      catch(NamingException ne) {
         ne.printStackTrace();
      }
   }
}

Logging AWT events

You can do so by subclassing EventQueue and adding logging functionality. Then replace the system event queue with that logging queue.

Main.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      getContentPane().add(new JButton("Test button"));
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.setDefaultCloseOperation(EXIT_ON_CLOSE);
      main.setSize(200, 200);
 
      main.getToolkit().getSystemEventQueue().push(new LoggingEventQueue());
 
      main.setVisible(true);
   }
}

LoggingEventQueue.java:

import java.awt.*;
 
public class LoggingEventQueue extends EventQueue
{
   protected void dispatchEvent(AWTEvent event) {
      super.dispatchEvent(event);
      System.out.println(event);
   }
}

Monitoring specific AWT events

The following example monitors Window events and Key events and prints them out.

Main.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
class Main extends JFrame
{
   public Main() {
      Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
         public void eventDispatched(AWTEvent e) {
            System.out.println(e);
         }
      }, AWTEvent.KEY_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK );
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.setDefaultCloseOperation( EXIT_ON_CLOSE );
      main.setSize(200, 200);
      main.setVisible(true);
   }
}

Dispatching an event to a Component

You can do so directly by calling the method dispatchEvent(AWTEvent event) on the Component. The following example dispatches the events to a button programmatically (as if they would come from the user clicking the mouse).

Main.java:

mport java.awt.event.*;
import java.awt.*;
 
public class Main extends Frame
{
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      Button button1 = new Button("Click me!");
      final Button button2 = new Button("Don't bother me...");
 
      setLayout(new FlowLayout(FlowLayout.LEFT)); 
      add(button1);
      add(button2);
      setSize(200, 200);
 
      button1.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            button2.dispatchEvent(new MouseEvent(button2,
                                                 MouseEvent.MOUSE_PRESSED,
                                                 System.currentTimeMillis(),
                                                 0, 5, 5, 1, false));
 
            try {
               Thread.sleep(100);
            }
            catch(InterruptedException e) { } 
 
            button2.dispatchEvent(new MouseEvent(button2,
                                                 MouseEvent.MOUSE_RELEASED,
                                                 System.currentTimeMillis(),
                                                 0, 5, 5, 1, false));
           
         }
      });
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
   }
}

Catching a specific SIGNAL/Interrupt in Java

You can use the undocumented class sun.misc.Signal. But beware of using the Sun packages.

This program allows you to catch any of the following signals:

   Windows:
      	ABRT	SIGABRT
	FPE 	SIGFPE
    	SEGV	SIGSEGV
	INT	SIGINT
	TERM	SIGTERM
	ILL	SIGILL


   Solaris/Linux:
	HUP	SIGHUP
	INT	SIGINT
	QUIT	SIGQUIT
	ILL	SIGILL
	TRAP	SIGTRAP
	ABRT	SIGABRT
	IOT	SIGIOT (*)
	EMT	SIGEMT (*)
	FPE	SIGFPE
	KILL	SIGKILL
	BUS	SIGBUS
	SEGV	SIGSEGV
	SYS	SIGSYS
	PIPE	SIGPIPE
	ALRM	SIGALRM
	TERM	SIGTERM
	STKFLT	SIGSTKFLT
	USR1	SIGUSR1
	USR2	SIGUSR2
	CHLD	SIGCHLD
	PWR	SIGPWR
	WINCH	SIGWINCH
	URG	SIGURG
	POLL	SIGPOLL
	IO	SIGIO
	STOP	SIGSTOP
	TSTP	SIGTSTP
	CONT	SIGCONT
	TTIN	SIGTTIN
	TTOU	SIGTTOU
	VTALRM	SIGVTALRM
	PROF	SIGPROF
	XCPU	SIGXCPU
	XFSZ	SIGXFSZ
	UNUSED	SIGUNUSED
	SWI	SIGSWI

The example program (Linux/Solaris) demonstrates to catch and perform a System.exit only with a SIGTERM. A SIGHUP will not cause the program to exit.

Main.java:

import sun.misc.Signal;
import sun.misc.SignalHandler;
import java.lang.reflect.*;
 
public class Main
{
   public static void main(String []args) {
      DebugSignalHandler.listenTo("HUP");
      DebugSignalHandler.listenTo("INT");
      DebugSignalHandler.listenTo("KILL");
      DebugSignalHandler.listenTo("TERM");
 
      while (true) {
         try {
            Thread.sleep(1000);
         }
         catch(InterruptedException e) {
         }
      }
   }
}
 
class DebugSignalHandler implements SignalHandler
{
   public static void listenTo(String name) {
      Signal signal = new Signal(name);
      Signal.handle(signal, new DebugSignalHandler());
   }

   public void handle(Signal signal) {
      System.out.println("Signal: " + signal);
      if (signal.toString().trim().equals("SIGTERM")) {
         System.out.println("SIGTERM raised, terminating...");
         System.exit(1);
      }
   }
}

Creating a scale in SWT

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Scale;
import org.eclipse.swt.widgets.Shell;
 
public class Main {
   public static void main (String [] args) {
      Display display = new Display ();
      Shell shell = new Shell (display);
   
      shell.setBounds(200, 200, 250, 250);   
       
      final Scale scale = new Scale (shell, SWT.VERTICAL);
      scale.setMinimum(100);
      scale.setMaximum(200);
      scale.setBounds(10, 10, 30, 200);
      final StyledText styledText = new StyledText(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.WRAP);
      styledText.setBounds(50, 10, 180, 200);
       
      scale.addListener(SWT.Selection, new Listener () {
         public void handleEvent(Event event) {
            styledText.append(scale.getSelection() + "n");
            int offset = styledText.getOffsetAtLine(styledText.getLineCount()-1);
            styledText.setCaretOffset(offset);
            styledText.showSelection();
         }
      });
 
      shell.open ();
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch ()) display.sleep ();
      }
   }
} 

Creating a slider in SWT

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Slider;
 
public class Main {
   public static void main (String [] args) {
      Display display = new Display ();
      Shell shell = new Shell (display);
    
      shell.setBounds(200, 200, 250, 250);   
       
      Slider slider = new Slider (shell, SWT.VERTICAL);
      slider.setBounds (10, 10, 20, 200);
      final StyledText styledText = new StyledText(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.WRAP);
      styledText.setBounds(40, 10, 190, 200);
       
      slider.addListener (SWT.Selection, new Listener () {
         public void handleEvent (Event event) {
            String evt = "SWT.NONE";
            switch (event.detail) {
               case SWT.ARROW_DOWN: 
                  evt = "SWT.ARROW_DOWN";
                  break;
               case SWT.ARROW_UP: 
                  evt = "SWT.ARROW_UP"; 
                  break;
               case SWT.PAGE_DOWN: 
                  evt = "SWT.PAGE_DOWN"; 
                  break;
               case SWT.PAGE_UP: 
                  evt = "SWT.PAGE_UP"; 
                  break;
               case SWT.HOME: 
                  evt = "SWT.HOME"; 
                  break;
               case SWT.END: 
                  evt = "SWT.END"; 
                  break;
               case SWT.DRAG: 
                  evt = "SWT.DRAG"; 
                  break;
            }
            styledText.append(evt + "n");
            int offset = styledText.getOffsetAtLine(styledText.getLineCount()-1);
            styledText.setCaretOffset(offset);
            styledText.showSelection();
         }
      });
 
      shell.open ();
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch ()) display.sleep ();
      }
   }
}