Using an image button 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.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 Image 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);
      button1.setImage(getImage("jpgIcon.gif"));
      button1.addSelectionListener(selectionListener);
      Button button2 = new Button(buttonGroup, SWT.PUSH);
      button2.setImage(getImage("gifIcon.gif"));
      button2.addSelectionListener(selectionListener);
      Button button3 = new Button(buttonGroup, SWT.PUSH);
      button3.setImage(getImage("tiffIcon.gif"));
      button3.addSelectionListener(selectionListener);
       
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      display.dispose();
   }
    
   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;
   }
}

Images used:


Getting the current NT/2000/XP user using JAAS

Note: if you are using a JDK less than 1.4, make sure you have downloaded the JAAS class libraries and the sample authentication module for Windows at http://java.sun.com/products/jaas/index-10.html. Put jaas.jar and jaasmod.jar in your classpath.

Main.java:

import com.sun.security.auth.module.NTSystem;
 
public class Main {
   public static void main(String []args) {
      NTSystem ntSystem = new NTSystem();
      System.out.println(ntSystem.getName());
   }
}

outputs on my machine:

C:myjaastest>java -Djava.library.path=c:javatoolsjaasmod1_0lib Main
esus

To get other NT properties:

import com.sun.security.auth.module.NTSystem;
import java.util.Arrays;

public class Main {
   public static void main(String []args) {
      NTSystem ntSystem = new NTSystem();
      System.out.println(ntSystem.getName());
      System.out.println(ntSystem.getDomain());
      System.out.println(ntSystem.getDomainSID());
      System.out.println(Arrays.asList((Object[])ntSystem.getGroupIDs()));
      System.out.println(ntSystem.getImpersonationToken());
      System.out.println(ntSystem.getPrimaryGroupID());
      System.out.println(ntSystem.getUserSID());
   }
}

outputs:

C:myjaastest>java -Djava.library.path=c:javatoolsjaasmod1_0lib Main
esus
WORKGROUP

[S-1-5-21-3978503659-2915903831-1203752577-513, S-1-1-0, S
-1-5-32-544, S-1-5-32-545, S-1-5-5-0-51662, S-1-2-0, S-1-5
-4, S-1-5-11]
1252
S-1-5-21-3978503659-2915903831-1203752577-513
S-1-5-21-3978503659-2915903831-1203752577-1007

Creating a checked SWT Tree

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
 
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 Checked Tree Demonstration");
      shell.setLayout(new GridLayout());
 
      final Tree tree = new Tree(shell, SWT.BORDER | SWT.CHECK);
        
      TreeItem node1 = new TreeItem (tree, SWT.NULL);
      node1.setText("Java");
       
      TreeItem node2 = new TreeItem(node1, SWT.NULL);
      node2.setText("j2se");
      TreeItem node3 = new TreeItem(node1, SWT.NULL);
      node3.setText("j2ee");
      TreeItem node4 = new TreeItem(node1, SWT.NULL);
      node4.setText("j2me");
       
      TreeItem node5 = new TreeItem(node2, SWT.NULL);
      node5.setText("http://java.sun.com/j2se/");
 
      TreeItem node6 = new TreeItem(node3, SWT.NULL);
      node6.setText("http://java.sun.com/j2se/");
 
      TreeItem node7 = new TreeItem(node4, SWT.NULL);
      node7.setText("http://java.sun.com/j2se/");
       
      tree.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
             
      shell.open();
       
      shell.addShellListener(new ShellAdapter() {
         public void shellClosed(ShellEvent se) {
            TreeItem[] treeItems = tree.getItems();
            for (int i=0; i<treeItems.length; i++) {
               recurseTree(treeItems[i]);
            }
         }
      });      
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      
      display.dispose();
   }
   
   public static void recurseTree(TreeItem item) {
      System.out.println(item.getText() + "tChecked=" + item.getChecked());
      TreeItem[] treeItems = item.getItems(); 
      for (int i=0; i<treeItems.length; i++) {
         TreeItem treeItem = treeItems[i];
         recurseTree(treeItem);
      }   
   }
}

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();
      }
   }
}

Getting a list of referenced types in a .class file

Compile the following Java source file with java -g.

Test.java:

public class Test
{
   private int          privateMember = 10;
   protected float      protectedMember = 20;
   public double        publicMember = 30.0;
 
   public Test() {
   }
   
   private void privateMethod(String argument) {
      int localMember = 40;
   }
  
   protected String protectedMethod() {
      String localMember = "Hello, World!";
 
      return localMember;
   }
  
   public void publicMethod() {
   }
}

Make sure Test.class in on your classpath and run Main:
Main.java:

import org.apache.bcel.classfile.*;
import org.apache.bcel.generic.*;
import org.apache.bcel.*;
 
public class Main
{
   public static void main(String []args) {
      JavaClass clazz = Repository.lookupClass("Test");
      ConstantPoolGen cp = new ConstantPoolGen(clazz.getConstantPool());
 
      Field[] fields = clazz.getFields();
      for (int i=0; i<fields.length; i++) {
         System.out.println(fields[i].getSignature());
      }
 
      Method[] methods = clazz.getMethods();
      for (int i=0; i<methods.length; i++) {
         Code code = methods[i].getCode();
         LocalVariableTable localVariableTable = code.getLocalVariableTable();
         if (localVariableTable != null) {            
            LocalVariable[] localVars = localVariableTable.getLocalVariableTable();
            for (int j=0; j<localVars.length; j++) {
               System.out.println(localVars[j].getSignature());
            }
         }
      }
   }
}

output:

I
F
D
LTest;
Ljava/lang/String;
Ljava/lang/String;
LTest;
LTest;
LTest;

Creating a JList with icons and text

Main.java:

import java.awt.image.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
  
public class Main 
{
   public static void main(String args[]) {
      JFrame frame = new JFrame("JList ImageIcon Demonstration");
 
      DefaultListModel dlm = new DefaultListModel();
      dlm.addElement(new ListEntry("Audio", new ImageIcon("audio.gif")));
      dlm.addElement(new ListEntry("Control Panel", new ImageIcon("controlpanel.gif")));
      dlm.addElement(new ListEntry("Folder", new ImageIcon("folder.gif")));
      dlm.addElement(new ListEntry("Local Disk (C:)", new ImageIcon("mycomp.gif")));
      dlm.addElement(new ListEntry("doc on '192.168.0.1' (Z:)", new ImageIcon("network.gif")));
 
      JList list = new JList(dlm);
      list.setCellRenderer(new ListEntryCellRenderer());
         
      frame.getContentPane().add(BorderLayout.CENTER, new JScrollPane(list)); 
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setVisible(true);
   }
}
 
class ListEntry 
{
   private String value;
   private ImageIcon icon;
 
   public ListEntry(String value, ImageIcon icon) {
      this.value = value;
      this.icon = icon;
   }
 
   public String getValue() {
      return value;
   }
 
   public ImageIcon getIcon() {
      return icon;
   }
 
   public String toString() {
      return value;
   }
}
 
class ListEntryCellRenderer
 extends JLabel implements ListCellRenderer
{
   private JLabel label;
 
   public Component getListCellRendererComponent(JList list, Object value,
                                                 int index, boolean isSelected,
                                                 boolean cellHasFocus) {
      ListEntry entry = (ListEntry) value;
 
      setText(value.toString());
      setIcon(entry.getIcon());
  
      if (isSelected) {
         setBackground(list.getSelectionBackground());
         setForeground(list.getSelectionForeground());
      }
      else {
         setBackground(list.getBackground());
         setForeground(list.getForeground());
      } 
 
      setEnabled(list.isEnabled());
      setFont(list.getFont());
      setOpaque(true);
 
      return this;
   }
}

Putting a JCheckbox in a JComboBox

Here’s a working example:

Main.java:

import javax.swing.*;
import java.awt.*;
import java.util.*;
 
public class Main extends JFrame
{
   public Main() {
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
      getContentPane().setLayout(new FlowLayout());
       
      Vector v = new Vector();
      v.add("Europe");
      v.add(new JCheckBox("Brussels", false));
      v.add(new JCheckBox("Paris", false));
      v.add(new JCheckBox("London", false));
      v.add("United States");
      v.add(new JCheckBox("New York", false));
      v.add(new JCheckBox("Detroit", false));
      v.add(new JCheckBox("San Francisco", false));
 
      getContentPane().add(new JComboCheckBox(v));
   }
    
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}

JComboCheckBox.java:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
 
public class JComboCheckBox extends JComboBox 
{
   public JComboCheckBox() { 
      init(); 
   }
   
   public JComboCheckBox(JCheckBox[] items) { 
      super(items); 
      init(); 
   }
   
   public JComboCheckBox(Vector items) { 
      super(items); 
      init(); 
   }
   
   public JComboCheckBox(ComboBoxModel aModel) { 
      super(aModel); 
      init(); 
   }
   
   private void init() {
      setRenderer(new ComboBoxRenderer());
      addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) { 
            itemSelected(); 
         }
      });
   }
 
   private void itemSelected() {
      if (getSelectedItem() instanceof JCheckBox) {
         JCheckBox jcb = (JCheckBox)getSelectedItem();
         jcb.setSelected(!jcb.isSelected());
      }
   }
 
   class ComboBoxRenderer implements ListCellRenderer {
      private JLabel label;
      
      public ComboBoxRenderer() { 
         setOpaque(true); 
      }
      
      public Component getListCellRendererComponent(JList list, Object value, int index, 
                                                    boolean isSelected, boolean cellHasFocus) {
         if (value instanceof Component) {
            Component c = (Component)value;
            if (isSelected) {
               c.setBackground(list.getSelectionBackground());
               c.setForeground(list.getSelectionForeground());
            } else {
               c.setBackground(list.getBackground());
               c.setForeground(list.getForeground());
            }
             
            return c;
         } else {
            if (label ==null) {
               label = new JLabel(value.toString());
            }
            else {
               label.setText(value.toString());
            }
               
            return label;
         }
      }
   }
}

Using a ConcurrentLinkedQueue

A ConcurrentLinkedQueue is an unbounded non-blocking FIFO queue. Although there is already a thread-safe implementation of a linked list:

   List list = Collections.synchronizedList(new LinkedList(...));

the ConcurrentLinkedQueue offers better concurrent performance and scalability.

Main.java:

import java.util.concurrent.*;
import java.util.*;
 
public class Main
{
   public static void main(String []args) {
      Queue<Message> queue = new ConcurrentLinkedQueue<Message>();
 
      Producer p = new Producer(queue);
      new Thread(p).start();
 
      // wait a bit before consuming to allow the queue to fill up
      // and force a blocking wait
      try { Thread.sleep(1000); } catch(InterruptedException e) { }
      Consumer c = new Consumer(queue);
      new Thread(c).start();
   }
}
 
class Producer implements Runnable
{
   private Queue<Message> queue;
 
   public Producer(Queue<Message> queue) {
      this.queue = queue;
   }
 
   public void run() {
      for (int i=0; i<1000; i++) {
         Message<String> m = new Message<String>("message contents #" + i);
         System.out.println("Producing '" + m + "'");
         queue.offer(m);
      }
   }
}
 
class Consumer implements Runnable
{
   private Queue<Message> queue;
    
   public Consumer(Queue<Message> queue) {
      this.queue= queue;
   }
    
   public void run() {
      while (true) {
         Message m = queue.poll();
         if (m != null) {
            System.out.println("tConsuming '" + m + "'");
         }
         else {
            System.out.println("All elements consumed.");
            break;
         }
      }
   }
}
 
class Message<T> {
   private T contents;
    
   public Message(T contents) {
      this.contents = contents;
   }
    
   public T getContents() {
      return contents;
   }
    
   public String toString() {
      return ""+contents;
   }
}

Drawing a polygon in Swing

Create a Polygon object that contains all corners of the polygon and use the method drawPolygon to render it.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
   }
 
   public void paint(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
 
      Polygon p = new Polygon();
      p.addPoint(110, 120);
      p.addPoint(120, 110);
      p.addPoint(130, 110);
      p.addPoint(140, 120);
      p.addPoint(140, 130);
      p.addPoint(130, 140);
      p.addPoint(120, 140);
      p.addPoint(110, 130);
      p.addPoint(110, 120);
 
      g2d.drawPolygon(p);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}

Make the speaker beep in Java

The first example simply beeps the speaker through an ASCII code:

public class Main {
   public static void main(String args[]) {
      System.out.print("7");
      System.out.flush();
   }
}

The second example makes use of the AWT Toolkit’s method beep. Note that even though we only use the AWT to make a beep, it automatically creates a non-daemon thread that keeps the program alive when it reaches the end of the main method. This is why there is a call to System.exit.

import java.awt.*;
 
public class beep {
   public static void main(String args[]) {
      Toolkit.getDefaultToolkit().beep();     
      System.exit(1);
   }
}