Using a Look and Feel for one component and another Look and Feel for another component

Main.java:

import javax.swing.plaf.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.io.*; 
  
public class Main extends JFrame
{
   public Main() throws Exception {
      getContentPane().setLayout(new BorderLayout(30, 30)); 
 
      Vector v = new Vector();
      v.addElement("item 1");
      v.addElement("item 2");
      v.addElement("item 3");
 
      JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
      panel1.add(new JButton("Button"));
      panel1.add(new JCheckBox("CheckBox"));
      panel1.add(new JTextField(10));
      panel1.add(new JComboBox(v));
 
      JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
      panel2.add(new JButton("Button"));
      panel2.add(new JCheckBox("CheckBox"));
      panel2.add(new JTextField(10));
      panel2.add(new JComboBox(v));
 
      getContentPane().add(BorderLayout.NORTH, panel1);
      getContentPane().add(BorderLayout.SOUTH, panel2);
 
      UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
      SwingUtilities.updateComponentTreeUI(panel1);
 
      UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
      SwingUtilities.updateComponentTreeUI(panel1);
 
      pack();
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String args[]) throws Exception {
      Main main = new Main();
      //main.setSize(300, 300);
      main.setVisible(true);
   }
}

Right-aligning a JTable column

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   public Main() {
      super("Table example, Wines from Bordeaux");
 
      Object[][] tabledata = {
            { "Chateau Meyney, St. Estephe", 	   new Integer(1994), "$18.75"},
            { "Chateau Montrose, St. Estephe", 	   new Integer(1975), "$54.25" },
            { "Chateau Gloria, St. Julien", 	   new Integer(1993), "$22.99" },
            { "Chateau Beychevelle, St. Julien",   new Integer(1970), "$61.63" },
            { "Chateau La Tour de Mons, Margeaux", new Integer(1975), "$57.03" },
            { "Chateau Brane-Cantenac, Margeaux",  new Integer(1978), "$49.92" },
      };
 
      String columnheaders[] = { "Wine", "Vintage", "Price" };
 
      JTable table = new JTable(tabledata, columnheaders);
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
 
      // right align 2nd column
      TableColumnModel columnModel = table.getColumnModel();
      TableColumn column = columnModel.getColumn(1);  
      DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
      renderer.setHorizontalAlignment(JLabel.RIGHT);
      column.setCellRenderer(renderer);
 
      // right align 2nd column when editing
      JTextField tf = new JTextField();
      tf.setHorizontalAlignment(JTextField.RIGHT);
      column.setCellEditor(new DefaultCellEditor(tf));
 
      JScrollPane scrollPane = new JScrollPane(table);
      getContentPane().add(scrollPane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      pack();
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Changing the traversal keys that control focus

In 1.4, you can use the following method.

Main.java:

import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame
{
   JLabel label = new JLabel("Forward: TAB or alt-f, Backward: SHIFT-TAB or alt-b");
   JButton button = new JButton("Button");
   JTextField textfield1 = new JTextField();
   JTextField textfield2 = new JTextField();
 
   public Main() {
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
      Container contentPane = getContentPane();
      contentPane.setLayout(new BorderLayout());
      JPanel panel = new JPanel(new GridLayout(4, 1, 10, 10));
      panel.add(label);
      panel.add(textfield1);   
      panel.add(textfield2);   
      panel.add(button);
      contentPane.add(BorderLayout.NORTH, panel);
 
      // add "alt f" as an alternative to TAB 
      Set set = contentPane.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
      KeyStroke altf = KeyStroke.getKeyStroke("alt F");
      set = new HashSet(set);
      set.add(altf);
      contentPane.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set);
 
      // add "alt b" as an alternative to SHIFT-TAB 
      set = contentPane.getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
      KeyStroke altb = KeyStroke.getKeyStroke("alt B");
      set = new HashSet(set);
      set.add(altb);
      contentPane.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, set);
   } 
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(350, 200);
      main.setVisible(true);
   }
}

Getting the Component with the current focus in Swing

There is a method in Window named getFocusOwner which returns the currently focused child of the window on which you invoke the method. Given that and the Frame.getFrames() method which returns all the frames created by the application, all you have to do is iterate over all the frames and find the focused component like this:

public static Component findFocusedComponent(){
  Frame [] allFrames = Frame.getFrames();
  for (int i=0;i<allFrames.length;i++){
    Frame frame = allFrames[i];
    Component focusOwner = frame.getFocusOwner();
    if (focusOwner!=null)
      return focusOwner;
  }
  return null; // if no focused component exists
}

Drawing a rectangle in Swing

Use the method drawRect and specify x, y coordinates (top left) and width and height of the rectangle.

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.drawRect(10, 50, 15, 15);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(100, 100);
      main.setVisible(true);
   }
}

Different types of endcap styles 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.drawString("CAP_BUTT", 20, 35); 
      g2d.setStroke(new BasicStroke(10f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,
                                    10f, new float[] { 15f }, 0f));
      g2d.drawRect(20, 50, 80, 80);
 
      g2d.drawString("CAP_ROUND", 140, 35); 
      g2d.setStroke(new BasicStroke(10f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL,
                                    10f, new float[] { 15f }, 0f));
      g2d.drawRect(140, 50, 80, 80);       
 
      g2d.drawString("CAP_SQUARE", 260, 35); 
      g2d.setStroke(new BasicStroke(10f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL,
                                    10f, new float[] { 15f }, 0f));
      g2d.drawRect(260, 50, 80, 80);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(360, 160);
      main.setVisible(true);
   }
}

Drawing a gradient filled circle 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.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                           RenderingHints.VALUE_ANTIALIAS_ON);
 
      GradientPaint gp = new GradientPaint(20, 50, Color.red, 100, 130, Color.blue, true);
      g2d.setPaint(gp);
      g2d.fillOval(20, 50, 80, 80);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(120, 180);
      main.setVisible(true);
   }
}

Waiting for an image to be loaded

Using javax.swing.ImageIcon

Main.java:

import javax.swing.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame {
   public static void main(String []args) throws Exception {
      Main main = new Main();
      main.loadImage(new URL("http://www.esus.com/images/space.jpg"));
      System.exit(0);
   }
 
   public Image loadImage(URL url) throws Exception {
      System.out.print("Loading image... ");   
      Image image = new javax.swing.ImageIcon(url).getImage(); 
      System.out.println("done!");
      return image;
   }
}

Using MediaTracker

Main.java:

import javax.swing.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame {
   public static void main(String []args) throws Exception {
      Main main = new Main();
      main.loadImage(new URL("http://www.esus.com/images/space.jpg"));
      System.exit(0);
   }
 
   public Image loadImage(URL url) throws Exception {
      MediaTracker mt = new MediaTracker(this);
 
      Image image = Toolkit.getDefaultToolkit().getImage(url);
  
      // add image to MediaTracker registry and give it an ID
      mt.addImage(image, 1); 
 
      System.out.print("Loading image... "); 
      // wait for that ID to be completed
      boolean status = false;
      try { 
         mt.waitForID(1); 
         
         status = mt.checkID(1, true); 
      } 
      catch (InterruptedException e) { }
      System.out.println("done! (status = " + status + ")");
 
      return image;
   }
}

Reading a given rectangle from an image with ImageIO

Use the method setSourceRegion, defined in ImageReadParam and pass it to your reader. This example reads a given rectangle, specified by top x,y and width, height and creates a new image.

Main.java:

import javax.imageio.metadata.*; 
import javax.imageio.stream.*;
import javax.imageio.event.*;
import javax.imageio.*;
 
import java.awt.image.*; 
import java.util.*;
import java.awt.*;
import java.io.*;
  
public class Main 
{ 
   public static void main(String []args) throws Exception {
      if (args.length != 5 || !args[0].endsWith(".jpg")) {
         System.out.println("Usage: java Main image.jpg x y w h");
         System.exit(1);
      }
 
      int x = Integer.parseInt(args[1]);
      int y = Integer.parseInt(args[2]);
      int w = Integer.parseInt(args[3]);
      int h = Integer.parseInt(args[4]);
 
      Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
      ImageReader reader = (ImageReader) readers.next();
 
      Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
      ImageWriter writer = (ImageWriter) writers.next();
 
      ImageInputStream iis = ImageIO.createImageInputStream(new File(args[0]));
      reader.setInput(iis, true);
      ImageReadParam param = reader.getDefaultReadParam();
      param.setSourceRegion(new Rectangle(x, y, w, h));
      
      BufferedImage bi = reader.read(0, param);
  
      String jpgFile = args[0].substring(0, args[0].length()-4) + "_new.jpg";
      ImageOutputStream ios = ImageIO.createImageOutputStream(new File(jpgFile));
      writer.setOutput(ios);
      writer.write(bi);
   }
}