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

Handling Hyperlink events on a JEditorPane

Add a HyperlinkListener to your JEditorPane, as shown in the following example. Note that a distinction is made between a normal hyperlink and a hyperlink activated in a frame. In the latter case, a HTMLFrameHyperlinkEvent will be posted.

import javax.swing.text.html.*;
import javax.swing.event.*;
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
{
   // need to be final to allow the inner class to access it!
   final JTextField urlTextField = new JTextField();
   final JEditorPane htmlPane = new JEditorPane();
   JButton urlButton = new JButton("Go!");
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
 
   public Main() { 
      htmlPane.setEditable(false);
      urlTextField.setText("http://www.yahoo.com");
  
      urlButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            loadPage(urlTextField.getText());
         }
      });

      htmlPane.addHyperlinkListener(new HyperlinkListener() {
         public void hyperlinkUpdate (HyperlinkEvent event) {
            if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
               urlTextField.setText(event.getURL().toString());

               if (event instanceof HTMLFrameHyperlinkEvent) {
                  HTMLDocument doc = (HTMLDocument) htmlPane.getDocument();
                  doc.processHTMLFrameHyperlinkEvent ((HTMLFrameHyperlinkEvent) event);
               }
               else {
                  loadPage(urlTextField.getText());
               }
            }
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      JPanel topPanel = new JPanel(new BorderLayout());
      topPanel.add(BorderLayout.CENTER, urlTextField);
      topPanel.add(BorderLayout.EAST, urlButton);
 
      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);
   }

   public void loadPage(String url) {
      try {
         htmlPane.setPage(new URL(urlTextField.getText()));
      }
      catch(Exception e) {
         System.out.println(e);
      }
   }
}

Creating a JFrame that cannot be resized

There is no good way to do this. The closest thing is to create a regular Frame (it doesn’t really matter whether it’s JFrame or Frame for this issue), register a ComponentListener on it and whenever it is resized, resize it back to its original size.

Most times you don’t need to do this though, you can almost always use a Window to achieve what you want.

Adding a menu bar to a JSplitPane

Main.java:

 
import javax.swing.plaf.basic.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.awt.*;
 
public class Main extends JFrame
{
   JSplitPane splitPane;
  
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, 
                                 new JPanel(), new JPanel());
      splitPane.setDividerSize(20);
  
      splitPane.setUI(new MenuDividerUI(getMainMenuBar()));
 
      getContentPane().add(splitPane);
 
      addComponentListener(new ComponentAdapter() {
         public void componentShown(ComponentEvent event) {
            splitPane.setDividerLocation(0.5);  
                
            removeComponentListener(this);
         }
      });
   }
 
   public JMenuBar getMainMenuBar() {
      JMenuBar mainBar = new JMenuBar();
      JMenu menu = new JMenu("JSplitPane");
      JMenuItem item1 = new JMenuItem("HORIZONTAL_SPLIT");
      JMenuItem item2 = new JMenuItem("VERTICAL_SPLIT");
      menu.add(item1);
      menu.add(item2);
      mainBar.add(menu);
  
      item1.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
         }
      });
 
      item2.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
         }
      });
 
      return mainBar;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}
 
class MenuDividerUI extends BasicSplitPaneUI
{
   protected JMenuBar menuBar;
 
   public MenuDividerUI(JMenuBar menuBar) {
      this.menuBar = menuBar;
   }
 
   public BasicSplitPaneDivider createDefaultDivider() {
      BasicSplitPaneDivider divider = new BasicSplitPaneDivider(this) {
         public int getDividerSize() { return menuBar.getPreferredSize().height; }
      };
      divider.setLayout(new BorderLayout());
      divider.add(BorderLayout.NORTH, menuBar);
 
      return divider;
   }
}

Setting the background color of the tabs of a JTabbedPane

You can set the background color using the method setBackgroundAt. However, this will only change the background of the tabs that are not selected. You can’t change the background of the selected tab unless you change the look and feel “TabbedPane.selected” property. This would change all JTabbedPanes that you have instantiated. A bug was filed for this: http://developer.java.sun.com/developer/bugParade/bugs/4230649.html.

import javax.swing.plaf.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JPanel {                     
  public Main() {
    setLayout(new BorderLayout());
    
    UIManager.put("TabbedPane.selected", Color.green);
    
    JTabbedPane tabbedPane = new JTabbedPane();
    for (int i=0;i<10;i++) {
      tabbedPane.addTab("Tab #" + i, new JLabel("Tab #" + i));
      tabbedPane.setBackgroundAt(i, new Color(25*i, 25*i, 25*i));
    }
    add(tabbedPane, BorderLayout.CENTER);
  }
  
  JPanel createPane(String s) {
    JPanel p = new JPanel();
    p.add(new JLabel(s));
    return p;
  }
  
  public static void main(String[] args) {
    JFrame frame = new JFrame("JTabbedPane Selected Color Demonstration");
    frame.addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent e ) {
        System.exit(0);
      }
    });
    frame.getContentPane().add(new Main());
    frame.setSize(200, 100);
    frame.setVisible(true);
  }
}