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

Setting a background image for a JDesktop

A JDesktopPane extends is a JLayeredPane. This container adds the notion of depth, allowing components to overlap each other. You specify the depth with an integer value, where higher-valued components sit on top of lower-valued components. To create a background image, just place it at the lowest layer: eg. the MIN_VALUE of an integer object. All other components must be layed out on top of this one.
Here’s an example, look at the method setBackgroundImage().

import java.awt.image.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;

public class Main extends JFrame
{
   JDesktopPane desktop;
 
   public Main() {
      desktop = new JDesktopPane(); 
      setContentPane(desktop);
      setBackgroundImage();
      createInternalFrame();
      setSize(new Dimension(500, 300));
      setLocation(100, 100);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0); 
         }
      });
   }
 
   protected void setBackgroundImage() {
      try {
         ImageIcon icon = new ImageIcon(new URL("http://www.esus.com/images/mong.jpg"));
         JLabel label = new JLabel(icon);
         label.setBounds(0, 0, icon.getIconWidth(), icon.getIconHeight());
  
         desktop.add(label, new Integer(Integer.MIN_VALUE));
      } catch(MalformedURLException e) {
         System.out.println(e);
      }
   }
  
   protected void createInternalFrame() {
      JInternalFrame frame = new JInternalFrame("InternalFrame", 
         true,    // resizable
         true,    // closable
         true,    // maximizable
         true);   // iconifiable
      frame.setVisible(true); 
      desktop.add(frame);
      frame.setSize(200, 200);
      try {
         frame.setSelected(true);
      } catch (java.beans.PropertyVetoException e) {}
   }
 
   public static void main(String []args) throws Exception {
      Main main = new Main();
      main.show();      
   }
}

Externalizing a JInternalFrame in a JFrame

You can get the contentpane of a JInternalFrame and put it inside a JFrame. Check out the following example, specifically the classes MyJInternalFrame and MyJFrame.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.util.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame {
   JDesktopPane desktop;
   int nframes = 0;
  
   public Main() {
      desktop = new JDesktopPane(); 
      setContentPane(desktop);
      setJMenuBar(createMenuBar());
      createInternalFrame(); 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();
 
      JMenu createMenu = new JMenu("Create");
      createMenu.setMnemonic(KeyEvent.VK_C);
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            createInternalFrame();
         }
      }); 
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      createMenu.add(newMenuItem);
      menuBar.add(createMenu);
 
      return menuBar;
   }
 
   protected void createInternalFrame() {
      nframes++;
      String title = "JInternalFrame #" + nframes;
      MyJInternalFrame frame = new MyJInternalFrame(title,
         true,    // resizable
         true,    // closable
         true,    // maximizable
         true);   // iconifiable
      frame.setVisible(true); 
 
      desktop.add(frame);
      frame.setSize(200, 200);
      frame.setLocation(30*nframes, 30*nframes);
      try {
         frame.setSelected(true);
      } catch (java.beans.PropertyVetoException e) {}
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(500, 300);
      main.setVisible(true);
   }
} 
 
class MyJInternalFrame extends JInternalFrame 
                       implements VetoableChangeListener { 
   MyJFrame externalFrame = null;
 
   public MyJInternalFrame(String title, boolean resizable, 
                           boolean closable, boolean maximizable, 
                           boolean iconifiable) { 
      super(title, resizable, closable, maximizable, iconifiable); 
      addVetoableChangeListener(this); 
 
      getContentPane().setLayout(new GridLayout(3, 1));
      getContentPane().add(new JLabel("JLabel"));
      getContentPane().add(new JButton("JButton"));
      getContentPane().add(new JCheckBox("JCheckBox"));
   } 
 
   public void vetoableChange(PropertyChangeEvent pce) 
                                 throws PropertyVetoException { 
      if (pce.getPropertyName().equals(IS_CLOSED_PROPERTY)) { 
         boolean changed = ((Boolean) pce.getNewValue()).booleanValue(); 
         if (changed) { 
            setVisible(false);
            boolean packFrame = false;
            if (externalFrame == null) {
               externalFrame = new MyJFrame(this.getTitle(), this);
               packFrame = true;
            }
            Container cp = this.getContentPane();
            this.getRootPane().setContentPane(new JPanel());
            externalFrame.getRootPane().setContentPane(cp);
            externalFrame.setVisible(true);
 
            // remember frame size if frame was already shown before
            if (packFrame) externalFrame.pack();
             
            throw new PropertyVetoException("Intercepted Closing",null); 
         } 
      } 
   }
} 
 
class MyJFrame extends JFrame
{
   MyJInternalFrame internalFrame;
 
   public MyJFrame(String title, MyJInternalFrame internalFrame) {
      super(title);
      this.internalFrame = internalFrame;
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) { 
            MyJFrame frame = MyJFrame.this;
            frame.setVisible(false);
            Container cp = frame.getContentPane();
            frame.getRootPane().setContentPane(new JPanel());
            frame.internalFrame.getRootPane().setContentPane(cp);
            frame.internalFrame.setVisible(true);
         } 
      });
   }
}

Setting the margin of a JButton

Use the method setMargin and specify an Insets object with (bottom, left, right, top) margins.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame {
   JList list; 
 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      final JButton button = new JButton("OK!");
      button.setMargin(new Insets(100, 100, 100, 100));
      
      getContentPane().add(button);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Getting an event when a JComboBox is about to appear/disappear

Since JDK1.4, you can add PopupMenuListeners to your JComboBox. This allows you to get the events popupMenuWillBecomeVisible and popupMenuWillBecomeInvisible. Another event is supposed to be thrown, for a popupMenuCanceled, but is not, due to a bug.

Now that you have the possibility to get an event when the JComboBox popup is about to appear, you can lazily populate it. So only when the user wants to change the value of a JComboBox, you fill it up.

Here’s a short example. Due to a bug related to the order in which getPreferredSize and popupMenuWillBecomeVisible are called, the size of the component is not the desired size. Click twice on the JComboBox to see the desired size.

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
 
      final JComboBox combobox = new JComboBox(new Object[] {"Default Item"});
      getContentPane().add(combobox);
 
      combobox.addPopupMenuListener(new PopupMenuListener() {
         public void popupMenuCanceled(PopupMenuEvent e) {
            System.out.println("popupMenu canceled");
         }
         public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            System.out.println("popupMenu will become invisible");
         }
         public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            if (combobox.getModel().getSize() <= 1) {
               // lazily populate combobox
               for (int i=0; i<100; i++) {
                  combobox.insertItemAt("Item #" + i, 0);
               }
               combobox.validate();
            }
            System.out.println("popupMenu will become visible");
         }
      });  
 
      setSize(300, 300);
   }
 
   public static void main(String[] args) {
      (new Main()).setVisible(true);
   }
}