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

Prevent the user from closing a JOptionPane with the X button

Embed your JOptionPane in a JDialog. Set the default close operation on that JDialog to DO_NOTHING_ON_CLOSE and add a PropertyChangeListener in which you listen for VALUE_PROPERTY and INPUT_VALUE_PROPERTY and hide the JDialog.

Main.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
  
public class Main
{
   public static void main(String []args) {
      JFrame frame = new JFrame();
 
      final JOptionPane pane = new JOptionPane("Are you sure you want to import this file?n" +
                                               "(try presssing the x button!)", 
                                               JOptionPane.QUESTION_MESSAGE,
                                               JOptionPane.YES_NO_CANCEL_OPTION);
      final JDialog dialog = new JDialog(frame, "Question", true);
      dialog.setContentPane(pane);
 
      dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
 
      pane.addPropertyChangeListener(new PropertyChangeListener() {
         public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();
            if (dialog.isVisible() 
             && (e.getSource() == pane)
             && (prop.equals(JOptionPane.VALUE_PROPERTY) ||
                 prop.equals(JOptionPane.INPUT_VALUE_PROPERTY)))
            {
               System.out.println("Caught, JOptionPane is ready to close!");
               dialog.setVisible(false);
            }
         }
      });
 
      dialog.pack();
      dialog.setVisible(true);
      Object value = pane.getValue();
      System.out.println("Option " + value + " selected!");
      
      System.exit(1);
   }
}

Displaying an image as the background of a JPanel

Override the JPanel’s method paintComponent, draw the image using g.drawImage and call the superclass’ paintComponent. Make sure the JPanel is opaque.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JPanel panel = createPanel();
 
      getContentPane().add(BorderLayout.CENTER, panel);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static JPanel createPanel() {
      JPanel panel = new JPanel() {
         public void paintComponent(Graphics g) {
            ImageIcon img = new ImageIcon("c:\mong.jpg");
            System.out.println(g.drawImage(img.getImage(), 0, 0, null));
            super.paintComponent(g);
         }
      };
      panel.setOpaque(false);
      panel.setLayout(new GridLayout(20, 4, 10, 10));
 
      for (int i=0; i<20; i++) {
         for (int j=0; j<4; j++) {
            JLabel label = new JLabel("label " + i + ", " + j);
            label.setFont(new Font("Helvetica", Font.PLAIN, 30));
            panel.add(label);            
         }
      }
 
      return panel;
   }
 
   public static void main(String [] args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   } 
} 

BTW, here’s the image I used:



Creating a scrollable JTabbedPane

Starting from JDK1.4, you can set the tab layout policy to either WRAP_TAB_LAYOUT or SCROLL_TAB_LAYOUT, for example:

      tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);

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();
      tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
 
      createTab();
 
      getContentPane().add(BorderLayout.CENTER, tabbedPane);
      setJMenuBar(createMenuBar());
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   
      setTitle("JTabbedPane Scrollable 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);
      JMenu menu2 = new JMenu("Change orientation");
      JMenuItem menuItem2 = new JMenuItem("TOP");
      menuItem2.addActionListener(this);
      menu2.add(menuItem2);
      JMenuItem menuItem3 = new JMenuItem("BOTTOM");
      menuItem3.addActionListener(this);
      menu2.add(menuItem3);
      JMenuItem menuItem4 = new JMenuItem("LEFT");
      menuItem4.addActionListener(this);
      menu2.add(menuItem4);
      JMenuItem menuItem5 = new JMenuItem("RIGHT");
      menuItem5.addActionListener(this);
      menu2.add(menuItem5);
      menuBar.add(menu1);
      menuBar.add(menu2);
 
      return menuBar;
   }
  
   public void actionPerformed(ActionEvent e) {
      if (e.getActionCommand().equals("Create new tab")) {
         createTab();
      }
      else if (e.getActionCommand().equals("TOP")) {
         tabbedPane.setTabPlacement(JTabbedPane.TOP);
      }
      else if (e.getActionCommand().equals("BOTTOM")) {
         tabbedPane.setTabPlacement(JTabbedPane.BOTTOM);
      }
      else if (e.getActionCommand().equals("LEFT")) {
         tabbedPane.setTabPlacement(JTabbedPane.LEFT);
      }
      else if (e.getActionCommand().equals("RIGHT")) {
         tabbedPane.setTabPlacement(JTabbedPane.RIGHT);
      }
   }
 
   protected void createTab() {
      ntabs++;
      tabbedPane.addTab("Tab #" + ntabs, new JLabel("Tab #" + ntabs));
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}