Iconifying a AWT Frame

Use setState(Frame.ICONIFIED) and setState(Frame.NORMAL).

Main.java:

import java.awt.event.*;
import java.awt.*;
 
public class Main extends Frame implements ActionListener
{
   public Main()
   {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      Button iconButton = new Button("Iconify this Frame");
      setLayout(new FlowLayout(FlowLayout.LEFT));
      add(iconButton);
      iconButton.addActionListener(this);
   }
 
   public void actionPerformed(ActionEvent ae) {     
      this.setState(Frame.ICONIFIED);  
   }
 
   public static void main(String args[])
   {
      Main main = new Main();
      main.setSize(300, 150);
      main.setVisible(true);
   }
}

Drawing a filled rectangle 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;
  
      g2d.setColor(Color.green);
      g2d.fillRect(10, 50, 130, 50);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(170, 150);
      main.setVisible(true);
   }
}

Drawing a gradient-filled text in Swing

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private BufferedImage image; 
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      image = toBufferedImage(new javax.swing.ImageIcon("djkrush.jpg").getImage());
   }
 
   public void paint(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
       
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                           RenderingHints.VALUE_ANTIALIAS_ON);
 
      Font font = new Font("Serif", Font.PLAIN, 140);
      g2d.setFont(font);
      FontMetrics fm = g2d.getFontMetrics();
 
      GradientPaint gp = new GradientPaint(30, 150-fm.getAscent(), Color.red, 
                                           390, 150, Color.blue, true);
      g2d.setPaint(gp);
      g2d.drawString("Alicia", 30, 150);
   }
 
   public 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.setSize(410, 180);
      main.setVisible(true);
   }
}

Drawing a shape anti-aliased in Swing

     

Main.java:

import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private boolean antiAliasing = false;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      final JCheckBox cb = new JCheckBox("Anti-aliased");
      cb.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            antiAliasing = cb.isSelected();
            repaint();
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.NORTH, cb);
   }
 
   public void paint(Graphics g) {
      super.paint(g);
 
      Graphics2D g2d = (Graphics2D) g;
       
      if (antiAliasing) {
         g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                              RenderingHints.VALUE_ANTIALIAS_ON);
      }
 
      GeneralPath gp = new GeneralPath();
      gp.moveTo(   0,  100);
      gp.quadTo( -75,   25,    0, -100);
      gp.quadTo(  75,   25,    0,  100);
      gp.lineTo( -50,  -50);
      gp.lineTo(  50,  -50);
      gp.closePath();
 
      // set origin to middle of window
      g2d.translate(150f, 150f);
 
      g2d.draw(gp);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}

Inverting the red band of all pixels of a image in Swing

Use the class LookupOp and pass it an array of arrays, each representing the change in band.

In this example, the G(reen) and B(lue) band don’t change while the R(ed) pixels are made brighter.

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;
 
   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);
         setSize(sourceBi.getWidth(), sourceBi.getHeight()*2);
 
         byte[][] intensity = new byte[3][256];
         int newRed;
         for(int i=0; i<256; i++) {
            newRed = (int) (i*1.5);  if (newRed > 255) newRed = 255;
            intensity[0][i] = (byte) newRed;
            intensity[1][i] = (byte) i;
            intensity[2][i] = (byte) i;
         }
  
         ByteLookupTable blt = new ByteLookupTable(0, intensity);
         LookupOp op = new LookupOp(blt, null);
         destBi = op.filter(sourceBi, null);
 
         firstTime = false;
      }
 
      g2d.drawImage(sourceBi, 0, 0, this);
      g2d.drawImage(destBi, 0, sourceBi.getHeight(), 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:

Changing the mouse cursor when moving over a component

Add a mouse listeners to the component and set another cursor when the mouse
enters it. Set it to the default cursor when the mouse moves out of it.

Here’s an example that creates a JFrame with a number of buttons, each with
a different mouse cursor. Our method createCursor will associate a cursor
to a component.

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame
{
   private Vector buttons = new Vector();
     
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
 
   public Main() {
      buttons.addElement(CreateCursor(new JButton("DEFAULT_CURSOR"), Cursor.DEFAULT_CURSOR));
      buttons.addElement(CreateCursor(new JButton("CROSSHAIR_CURSOR"), Cursor.CROSSHAIR_CURSOR));
      buttons.addElement(CreateCursor(new JButton("TEXT_CURSOR"), Cursor.TEXT_CURSOR));
      buttons.addElement(CreateCursor(new JButton("WAIT_CURSOR"), Cursor.WAIT_CURSOR));
      buttons.addElement(CreateCursor(new JButton("SW_RESIZE_CURSOR"), Cursor.SW_RESIZE_CURSOR));
      buttons.addElement(CreateCursor(new JButton("SE_RESIZE_CURSOR"), Cursor.SE_RESIZE_CURSOR));
      buttons.addElement(CreateCursor(new JButton("NW_RESIZE_CURSOR"), Cursor.NW_RESIZE_CURSOR));
      buttons.addElement(CreateCursor(new JButton("NE_RESIZE_CURSOR"), Cursor.NE_RESIZE_CURSOR));
      buttons.addElement(CreateCursor(new JButton("N_RESIZE_CURSOR"), Cursor.N_RESIZE_CURSOR));
      buttons.addElement(CreateCursor(new JButton("S_RESIZE_CURSOR"), Cursor.S_RESIZE_CURSOR));
      buttons.addElement(CreateCursor(new JButton("W_RESIZE_CURSOR"), Cursor.W_RESIZE_CURSOR));
      buttons.addElement(CreateCursor(new JButton("E_RESIZE_CURSOR"), Cursor.E_RESIZE_CURSOR));
      buttons.addElement(CreateCursor(new JButton("HAND_CURSOR"), Cursor.HAND_CURSOR));
      buttons.addElement(CreateCursor(new JButton("MOVE_CURSOR"), Cursor.MOVE_CURSOR));
 
	getContentPane().setLayout(new GridLayout(buttons.size(), 1));
 
      for (int i=0; i<buttons.size(); i++) {
         getContentPane().add((JButton) buttons.elementAt(i));
      }
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      pack();
   }
 
   private JComponent CreateCursor(final JComponent component, final int cursor) {
	component.addMouseListener(new MouseAdapter() {
	   public void mouseEntered(MouseEvent e) {
		component.setCursor(Cursor.getPredefinedCursor(cursor));
	   }
	   public void mouseExited(MouseEvent e) {
		component.setCursor(Cursor.getDefaultCursor());
	   }
 	});
 
      return component;
   }  
}

Rendering HTML documents in Java

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

Creating a Menu for a JFrame

This example creates a JFrame, and puts a raised menubar on it, and menu items on the menubar. It also applies acclerators and mnemonics to the menu items and assigns listeners.

MyFrame.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.border.*;
import javax.swing.KeyStroke;
import javax.swing.JOptionPane;
import java.awt.Component;
 
public class MyFrame extends JFrame {
 
   public static void main(String args[]) {
 
      MyFrame main = new MyFrame();
 
      // center frame on screen
      Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
      main.setBounds(d.width/2-100, d.height/2-75, 200, 150);
 
      main.pack();
      main.setSize(200, 150); //set frame size
           
      main.setVisible(true);     
   } 
 
   public MyFrame() {
      super("Menu Example");
 
      this.addWindowListener(new WindowEventHandler()); 
         
      Container container = this.getContentPane();
 
      JMenu filemenu = new JMenu("Document");
      filemenu.setMnemonic(KeyEvent.VK_D);
 
      JMenuBar bar = new JMenuBar();
      bar.setBorder(new BevelBorder(BevelBorder.RAISED));
      container.add(bar);
      setJMenuBar(bar);
 
      JMenuItem connect = new JMenuItem("Open");
      connect.addActionListener(new openListener());
      connect.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, 
                                         Event.CTRL_MASK, false));
      connect.setMnemonic('O');
 
      JMenuItem exit = new JMenuItem("Exit");
      exit.addActionListener(new exitListener());
      exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, 
                                         Event.CTRL_MASK, false));
      exit.setMnemonic('X');
 
      filemenu.add(connect);
      filemenu.add(exit);
      bar.add(filemenu);
   }
 
   class WindowEventHandler extends WindowAdapter {
      public void windowClosing(WindowEvent evt) {          
         System.exit(0);
      }
   }
 
   class exitListener implements ActionListener {
      public void actionPerformed(ActionEvent l){
         System.exit(0);
      } 
   } 
 
   class openListener implements ActionListener {
      JFrame f = new JFrame();
 
      public void actionPerformed(ActionEvent l){
         JOptionPane.showMessageDialog(f, "OPEN");
      }
   }
}

Scrolling a JScrollPane to the top programmatically

Call the method scrollRectToVisible of the component that is added to the JScrollPane container as shown in following example:

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() throws Exception {
      getContentPane().setLayout(new BorderLayout());
 
      final JPanel panel = createPanel(); 
      final JScrollPane scrollpane = new JScrollPane(panel);
 
      JButton button = new JButton("Scroll to top!");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            panel.scrollRectToVisible(
              new Rectangle(0, 0, 1, 1));
         }
      });
 
      getContentPane().add(BorderLayout.NORTH, button);
      getContentPane().add(BorderLayout.CENTER, scrollpane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static JPanel createPanel() throws Exception {
      JPanel panel = new JPanel();
      panel.setLayout(new GridLayout(50, 20, 10, 10));
 
      for (int i=0; i<50; i++) {
         for (int j=0; j<20; j++) {
            JLabel label = new JLabel("label " + i + ", " + j);
            panel.add(label);    
         }
      }
 
      return panel;
   }
 
   public static void main(String [] args) throws Exception  {
      Main main = new Main();
      main.setSize(600, 600);
      main.setVisible(true);
   } 
} 

Make the tab-text of a JTabbedPane appear bold

You can HTML tags when naming your tabs, as shown in following example.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame implements ActionListener {
   JTabbedPane tabbedPane;
   int ntabs = 0;
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      tabbedPane = new JTabbedPane();
      createTab();
 
      getContentPane().add(BorderLayout.CENTER, tabbedPane);
      setJMenuBar(createMenuBar());
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   
      setTitle("JTabbedPane Bold Demonstration");
      setSize(new Dimension(400, 400));
   }
 
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();
 
      JMenu menu1 = new JMenu("JTabbedPane");
      JMenuItem menuItem1 = new JMenuItem("Create new tab");
      menuItem1.addActionListener(this);
      menu1.add(menuItem1);
      menuBar.add(menu1);
 
      return menuBar;
   }
  
   public void actionPerformed(ActionEvent e) {
      if (e.getActionCommand().equals("Create new tab")) {
         createTab();
      }
   }
 
   protected void createTab() {
      ntabs++;
      if (ntabs % 2 == 0) {
         tabbedPane.addTab("<html><i>Tab #" + ntabs + "</i></html>", 
                             new JLabel("Tab #" + ntabs));
      }
      else {
         tabbedPane.addTab("<html><b>Tab #" + ntabs + "</b></html>", 
                             new JLabel("Tab #" + ntabs));
      }
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}