Rendering RTF documents with RTFEditorKit

JEditorPane is able to display and edit different kinds of content. By default,
text/plain, text/html and text/rtf are recognized and passed on to the
EditorKit that is designed to handle it: DefaultEditorKit, HTMLEditorKit and
RTFEditorKit
. In the following example, a URL can be given in a JTextField.
Clicking GO will invoke the setPage method on the JEditorPane that will load
the page into a default document and set the content type. Using the
mime type of the page, the pane will automatically detect the correct EditorPane to
use.
Try: http://www.yahoo.com and http://www.esus.com/richtext.rtf

import javax.swing.text.html.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.awt.*;
import java.io.*;
 
public class Main extends JFrame
{
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
 
   public Main() {
 
      JButton uriButton = new JButton("Go!");
      // needs to be final to allow the inner class to access it!
      final JTextField uriTextField = new JTextField();
      final JEditorPane htmlPane = new JEditorPane();
      uriTextField.setText("http://www.yahoo.com");
      htmlPane.setEditable(false);
 
      uriButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            try {
               htmlPane.setPage(new URL(uriTextField.getText()));
            }
            catch(Exception e) {
               System.out.println(e);
            }
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      JPanel topPanel = new JPanel(new BorderLayout());
      topPanel.add(BorderLayout.CENTER, uriTextField);
      topPanel.add(BorderLayout.EAST, uriButton);
 
      getContentPane().add(BorderLayout.NORTH, topPanel);
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(htmlPane));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      setSize(400, 400);
   }
}

Allowing for multiple selections in a JTree

Use TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION!

Main.java:

import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
 
public class Main extends JFrame
{
   public Main() {
      DefaultMutableTreeNode root = createNodes();
      final JTree tree = new JTree(root);
 
      TreeSelectionModel model = new DefaultTreeSelectionModel();
      model.setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
      tree.setSelectionModel(model);
 
      JButton button = new JButton("Display selected values on stdout");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            TreePath[] treePaths = tree.getSelectionPaths();    
            for (int i=0; i<treePaths.length; i++) {
               System.out.println(treePaths[i].getLastPathComponent());    
            }
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(tree));
      getContentPane().add(BorderLayout.SOUTH, button);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static DefaultMutableTreeNode createNodes() {
      DefaultMutableTreeNode root = new DefaultMutableTreeNode("Java");
      
      DefaultMutableTreeNode j2se = new DefaultMutableTreeNode("J2SE");
      DefaultMutableTreeNode j2ee = new DefaultMutableTreeNode("J2EE");
      DefaultMutableTreeNode j2me = new DefaultMutableTreeNode("J2ME");
 
      j2se.add(new DefaultMutableTreeNode("http://java.sun.com/j2se/"));
      j2ee.add(new DefaultMutableTreeNode("http://java.sun.com/j2ee/"));
      j2me.add(new DefaultMutableTreeNode("http://java.sun.com/j2me/"));
 
      root.add(j2se);
      root.add(j2ee);
      root.add(j2me);
 
      return root;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Creating an SWT Text(Area)

Main.java:

import org.eclipse.swt.SWT;
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.Text;
 
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));
 
      Text text = new Text(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.WRAP);
      text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
       
      text.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.");
       
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
       
      display.dispose();
   }
}

Creating a JFormattedTextField that only accepts dates

Main.java and JFormattedDateTextField:

import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
import java.util.*;
 
public class Main extends JFrame 
{
   public Main() throws Exception
   {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
  
 
      final JFormattedDateTextField formattedTf =
                   new JFormattedDateTextField();
      formattedTf.setValue(new Date()); 
 
      final JTextField normalTf = new JTextField(25);
      JButton button = new JButton("Get value");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) { 
            normalTf.setText(""+formattedTf.getValue());
         }
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      getContentPane().add(formattedTf);
      getContentPane().add(button);
      getContentPane().add(normalTf);
 
      formattedTf.setPreferredSize(normalTf.getPreferredSize());
   }
  
   public static void main(String args[]) throws Exception 
   {
      Main main = new Main();
      main.setSize(300, 150);
      main.setVisible(true);
   }
}
 
class JFormattedDateTextField extends JFormattedTextField {
   Format format = new SimpleDateFormat("MM/dd/yyyy"); 
 
   public JFormattedDateTextField() {
      super();
      MaskFormatter maskFormatter = null;
      try {
         maskFormatter = new MaskFormatter("##/##/####");
      } catch (ParseException e) {
         e.printStackTrace();
      }
 
      maskFormatter.setPlaceholderCharacter('_');
      setFormatterFactory(new DefaultFormatterFactory(maskFormatter));
      this.addFocusListener(new FocusAdapter() {
         public void focusGained(FocusEvent e) {
            if (getFocusLostBehavior() == JFormattedTextField.PERSIST)
               setFocusLostBehavior(JFormattedTextField.COMMIT_OR_REVERT);
            }
  
            public void focusLost(FocusEvent e) {
               try {
                  Date date = (Date) format.parseObject(getText());
                  setValue(format.format(date));
               } catch (ParseException pe) {
                  setFocusLostBehavior(JFormattedTextField.PERSIST);
                  setText("");
                  setValue(null);
               }
            }
      });
   }
 
   public void setValue(Date date) {
      super.setValue(toString(date));
   }
 
   private Date toDate(String sDate) {
      Date date = null;
      if (sDate == null) return null;
      try {
         date = (Date) format.parseObject(sDate);
      }
      catch (ParseException pe) {
         // ignore
      }
 
      return date;
   } 
 
   private String toString(Date date) {
      try {
         return format.format(date);
      } catch (Exception e) {
         return "";
      }
   }
}

Creating a Menu for a Frame

Main.java:

import java.awt.*;
import java.awt.event.*;

class MenuTest extends Frame implements ActionListener
{
   MenuBar menu=new MenuBar();
   Menu menuFile=new Menu("File");
   MenuItem menuFileQuit=new MenuItem("Quit");
 
   public static void main(String args[]) {
      MenuTest window=new MenuTest();
      window.show();
   }
 
   public MenuTest() {
      setMenuBar(menu);
      menu.add(menuFile);
      menuFile.add(menuFileQuit);
      menuFileQuit.addActionListener(this);
   }
  
   public void actionPerformed(ActionEvent e)
   {
      if (e.getSource()==menuFileQuit)
      {
         System.exit(0);
      }
   }
}

Drawing a filled polygon in Swing

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(90, 140);
      p.addPoint(110, 130);
      p.addPoint(130, 130);
      p.addPoint(150, 140);
      p.addPoint(150, 150);
      p.addPoint(130, 160);
      p.addPoint(110, 160);
      p.addPoint(90, 150);
      p.addPoint(90, 140);
 
      g2d.setColor(Color.green);
      g2d.fillPolygon(p);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}

Rotating text in Swing

You could apply AffineTransform on the graphics context directly or you can use the TextLayout class as shown here.

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.font.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private int degrees = 0;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      JButton button = new JButton("Rotate 10 degrees");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            degrees += 10;
            repaint();
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.SOUTH, button);
   }
 
   public void paint(Graphics g) {
      super.paint(g);
 
      Graphics2D g2d = (Graphics2D) g;
 
      g2d.drawString("Java and...", 80, 50);
     
      double radians = degrees * (Math.PI / 180);
      AffineTransform at = new AffineTransform();
      at.setToRotation(radians);
 
      FontRenderContext frc = g2d.getFontRenderContext();
      Font font = new Font("Times", Font.PLAIN, 20);
      Font derivedFont = font.deriveFont(at);
      TextLayout textLayout = new TextLayout("Alicia", derivedFont, frc);
      textLayout.draw(g2d, getSize().width/2, getSize().height/2);
 
      g2d.drawString("all I need ;)", 330, 180);
   }
  
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(480, 240);
      main.setVisible(true);
   }
}

Drawing an image in Swing

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private Image image;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      image = Toolkit.getDefaultToolkit().getImage("c:\djkrush.jpg");
   }
 
   public void paint(Graphics g) {
      g.drawImage(image, 0, 20, this);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(150, 150);
      main.setVisible(true);
   }
}

Image used:

Brightening an image in Swing

To brighten an image, you can use the class LookupOp. This class works with one or more tables that will be applied to the color values of the pixels. To brighten an RGB image, the RGB values have to be increased (higher values means brighter). The lookup table reflects these changes.

The following example shows the original image, an image that has been brightened by adding 30 to every pixel color (every R,G and B, and all values that are higher than 255 are reset to 255) and an image where brightening is based on the rule that says that midrange colors are adjusted more than dark or bright colors.

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private boolean firstTime = true;
   private BufferedImage sourceBi;
   private BufferedImage destBi;
   private BufferedImage destBi2;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      }); 
   } 
 
   public void paint(Graphics graphics) {
      Graphics2D g2d = (Graphics2D) graphics;
  
      if (firstTime) {
         Image img = new javax.swing.ImageIcon("djkrush.jpg").getImage(); 
         sourceBi = toBufferedImage(img);
         destBi = new BufferedImage(sourceBi.getWidth(), sourceBi.getHeight(), 
                                    BufferedImage.TYPE_INT_RGB);
         destBi2 = new BufferedImage(sourceBi.getWidth(), sourceBi.getHeight(), 
                                    BufferedImage.TYPE_INT_RGB);
         setSize(sourceBi.getWidth(), sourceBi.getHeight()*3);
 
         short[] intensity1 = new short[256];
         for(int i=0; i<256; i++) {
            short newVal = (short) (i + 30);
            if (newVal > 255) newVal = 255;
            intensity1[i] = newVal;
         }
  
         byte[] intensity2 = new byte[256];
         for(int i=0; i<256; i++) {
            intensity2[i] = (byte) (Math.sqrt((float)i/255.0) * 255);
         }
 
         ShortLookupTable slt = new ShortLookupTable(0, intensity1);
         LookupOp op = new LookupOp(slt, null);
         destBi = op.filter(sourceBi, null);
 
         ByteLookupTable blt = new ByteLookupTable(0, intensity2);
         LookupOp op2 = new LookupOp(blt, null);
         destBi2 = op2.filter(sourceBi, null);
 
         firstTime = false;
      }
 
      g2d.drawImage(sourceBi, 0, 0, this);
      g2d.drawImage(destBi, 0, sourceBi.getHeight(), this);
      g2d.drawImage(destBi2, 0, sourceBi.getHeight()*2, this);
   }
 
   public static BufferedImage toBufferedImage(Image image) {
      BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), 
                                           BufferedImage.TYPE_INT_RGB); 
 
      // copy the original image
      Graphics g = bi.createGraphics();
    
      g.drawImage(image, 0, 0, null);
      g.dispose();
 
      return bi;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
      main.setSize(300, 150);
   }
}

Image used:

To learn more about image processing,
check out this expensive but excellent book:

Generating a mouse event programatically in Swing

In JDK 1.3, you can use the Robot class, very useful for testing purposes. The following example creates a JFrame with a button and left clicks in the center.

Main.java:

import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.awt.*;
  
public class Main extends JFrame
{
   public Main() throws Exception {
      JButton button = new JButton("This button will be clicked");
      getContentPane().add(button);
      pack();
 
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
            System.out.println("Button was clicked!");
         }
      });
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public void generateClickEvent() throws Exception {
      Robot robot = new Robot();
      robot.mouseMove((int) (getSize().getWidth() / 2), (int) (getSize().getHeight() / 2));
      robot.mousePress(InputEvent.BUTTON1_MASK);
      robot.mouseRelease(InputEvent.BUTTON1_MASK);
   }
  
   public static void main(String args[]) throws Exception {
      Main main = new Main();
      main.show();
      try { Thread.sleep(1000); } catch(InterruptedException e) { } 
      main.generateClickEvent();
   }
}