Playing sound in a Swing application

Try out this small application with evil_laugh.wav:

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
{
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      final JLabel label = new JLabel("Sound file: ");
      final JTextField textfield = new JTextField(30);
      final JButton button = new JButton("Play");
      getContentPane().add(BorderLayout.WEST, label);
      getContentPane().add(BorderLayout.CENTER, textfield);
      getContentPane().add(BorderLayout.EAST, button);
 
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            try {
               URL codebase = new URL("file:" + System.getProperty("user.dir") + "/");
               AudioClip audioClip = Applet.newAudioClip(new URL(codebase, textfield.getText()));
               audioClip.play();
            } catch (MalformedURLException e) {
               System.err.println(e.getMessage());
            }
         }
      });
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });      
 
      pack();
   }
 
   public static void main(String []args) throws Exception {
      Main main = new Main();
      main.show();      
   }
}

Drawing an arc in Swing

Use the method drawArc that accepts the left and right coordinate, the height and width of the circle, the angle of the starting point and the angle of the arc. In this example, an arc is drawn from 90 degrees for 45 degrees.

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.drawArc(10, 50, getSize().width-20, getSize().height-50, 90, 45);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(100, 100);
      main.setVisible(true);
   }
}

Controlling transparancy when two Swing shapes overlap

Use the class AlphaComposite as shown in following example.

Main.java:

import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.text.*;
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.blue);
      g2d.fill(new Ellipse2D.Float(50, 30, 80, 50));
      g2d.setColor(Color.red);
      g2d.fill(new Ellipse2D.Float(100, 30, 80, 50));
 
      g2d.setColor(Color.black);
      g2d.drawLine(0, 90, 250, 90);
      
      DecimalFormat decimalFormat = (DecimalFormat)NumberFormat.getInstance();
      decimalFormat.applyPattern("0.0");
 
      int yd = 80;
      for (float f = 1f; f>=0f; f-=.2f) {
         g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
         g2d.setColor(Color.black);
         g2d.drawString("AlphaComposite = " + decimalFormat.format(f), 50, 50 + yd - 10);
         g2d.setColor(Color.blue);
         g2d.fill(new Ellipse2D.Float(50, 50 + yd, 80, 50));
 
         AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, f);
         g2d.setComposite(ac);
 
         g2d.setColor(Color.red);
         g2d.fill(new Ellipse2D.Float(100, 50 + yd, 80, 50));
 
         yd += 80;
      }
   }
  
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(250, 600);
      main.setVisible(true);
   }
}

Drawing a gradient-filled shape 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;
 
      GradientPaint gp = new GradientPaint(20, 50, Color.red, 100, 130, Color.blue, true);
      g2d.setPaint(gp);
      g2d.fillRect(20, 50, 80, 80);
      g2d.setColor(Color.black);
      g2d.drawLine(20, 50, 100, 130);
 
      gp = new GradientPaint(140, 50, Color.red, 220, 130, Color.blue, false);
      g2d.setPaint(gp);
      g2d.fillRect(140, 50, 80, 80);       
      g2d.setColor(Color.black);
      g2d.drawLine(140, 50, 220, 130);
 
      gp = new GradientPaint(260, 60, Color.red, 270, 60, Color.blue, true);
      g2d.setPaint(gp);
      g2d.fillRect(260, 50, 80, 80);
      g2d.setColor(Color.black);
      g2d.drawLine(260, 60, 270, 60);
 
      gp = new GradientPaint(380, 60, Color.red, 390, 60, Color.blue, false);
      g2d.setPaint(gp);
      g2d.fillRect(380, 50, 80, 80);
      g2d.setColor(Color.black);
      g2d.drawLine(380, 60, 390, 60);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(480, 160);
      main.setVisible(true);
   }
}

Drawing text on top of a BufferedImage

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   BufferedImage image;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      createImage();
   }
 
   public void createImage() {
      Image backImage = new javax.swing.ImageIcon("mong.jpg").getImage(); 
      int width = backImage.getWidth(this); 
      int height = backImage.getHeight(this); 
      image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
      Graphics2D g2d = image.createGraphics(); 
      g2d.drawImage(backImage, 0, 0, this); 

      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                           RenderingHints.VALUE_ANTIALIAS_ON);
      Font f = new Font("Mistral", Font.BOLD, 56);
      g2d.setFont(f);
      String text = "Philip Elliott";
      FontMetrics fm = getFontMetrics(f);       
      int swidth = fm.stringWidth(text);
      int sheight = fm.getAscent();
 
      GradientPaint gp = new GradientPaint(20, 50, Color.red, 
                                           100, 130, Color.yellow, true); 
      g2d.setPaint(gp);
      g2d.drawString(text, width/2 - swidth/2, height/2 + sheight/2);   
 
      setSize(width, height);
   }
  
   public void paint(Graphics g) { 
      Graphics2D g2d = (Graphics2D) g; 
 
      g2d.drawImage(image, null, 0, 0); 
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
   }
}

Image used:

Use double-buffering for animation in Swing

Look at the performance between these two examples. The first one (Main1.java) will directly write to the graphics context and results in lots of flickering. The second one (Main2.java) uses instead to an intermediate buffer.

Main1.java:

import java.awt.image.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main1 extends JFrame implements Runnable {
   int pos = 0;
   int WIDTH = 300;
   int HEIGHT = 150;
  
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      setSize(WIDTH, HEIGHT);
   } 
 
   public void update(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
 
      g.setColor(Color.white);
      g.fillRect(0, 0, WIDTH, HEIGHT);
 
      g.setColor(Color.black);
      g.fillRect(10 + pos, 50, 50, 50);
   }
 
   public void run() {
      setResizable(false); 
 
      while (true) {
         pos++;
         if (pos > 220) pos = 0;
         repaint();
 
         try {
            Thread.sleep(10);
         }
         catch(InterruptedException e) {
         }
      }
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
 
      Thread t = new Thread(main);
      t.start();
   }
}

Main2.java:

import java.awt.image.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main2 extends JFrame implements Runnable {
   BufferedImage buffer;
   Graphics bufferGraphics;
   int pos = 0;
   int WIDTH = 300;
   int HEIGHT = 150;
  
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      setSize(WIDTH, HEIGHT);
   } 
 
   public void update(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
 
      bufferGraphics.setColor(Color.white);
      bufferGraphics.fillRect(0, 0, WIDTH, HEIGHT);
 
      bufferGraphics.setColor(Color.black);
      bufferGraphics.fillRect(10 + pos, 50, 50, 50);
 
      g2d.drawImage(buffer, 0, 0, this);
   }
 
   public void run() {
      buffer = (BufferedImage) createImage(WIDTH, HEIGHT);
      bufferGraphics = buffer.createGraphics();
      setResizable(false); 
 
      while (true) {
         pos++;
         if (pos > 220) pos = 0;
         repaint();
 
         try {
            Thread.sleep(10);
         }
         catch(InterruptedException e) {
         }
      }
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
 
      Thread t = new Thread(main);
      t.start();
   }
}

Catching events while an image is being written out using ImageIO

Register an IIOWriteProgressListener with your ImageWriter.

   IIOWriteProgressListener listener = new MyWriteProgressListener();
   writer.addIIOWriteProgressListener(listener);

This example reads a JPG and creates a new one, vertically subsampled.

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.io.*;
  
public class Main 
{ 
   public static void main(String []args) throws Exception {
      if (args.length != 1 || !args[0].endsWith(".jpg")) {
         System.out.println("Usage: java Main image.jpg");
         System.exit(1);
      }
 
      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);
      BufferedImage bi = reader.read(0);
 
      IIOWriteProgressListener listener = new MyWriteProgressListener();
      writer.addIIOWriteProgressListener(listener);
 
      String jpgFile = args[0].substring(0, args[0].length()-4) + "_new.jpg";
      ImageOutputStream ios = ImageIO.createImageOutputStream(new File(jpgFile));
      ImageWriteParam param = writer.getDefaultWriteParam();
 
      IIOImage iioImage = new IIOImage(bi, null, null);
      param.setSourceSubsampling(1, 4, 0, 0);
      writer.setOutput(ios);
      writer.write(null, iioImage, param);
   }
 
   static class MyWriteProgressListener implements IIOWriteProgressListener {
        float last = 0;
 
	public MyWriteProgressListener() {}

        public void imageStarted(ImageWriter dest, int imageIndex)  { 
           System.out.println("0% -----------------------------------> 100%n");
        }
 
        public void imageProgress(ImageWriter dest, final float percentageDone) {
           int n = (int) (percentageDone-last);
           for (int i=0; i<n/2; i++) {
              System.out.print("*");
           }
           last = percentageDone;
        }
 
        public void imageComplete(ImageWriter dest) { 
           System.out.println();
        }
 
        public void writeAborted(ImageWriter dest)                  { }
        public void sequenceComplete(ImageWriter dest)              { }
        public void sequenceStarted(ImageWriter dest, int minIndex) { }
        public void thumbnailComplete(ImageWriter dest)             { }
        public void thumbnailProgress(ImageWriter dest, float percentageDone) { }
        public void thumbnailStarted(ImageWriter dest, int imageIndex, int thumbnailIndex) { }
   }
}

Examples of JOptionPane?

   JOptionPane.showMessageDialog(frame, "File successfully imported!");

   JOptionPane.showMessageDialog(frame, "Deprecated version", "Warning", 
                                 JOptionPane.WARNING_MESSAGE);

   JOptionPane.showMessageDialog(frame, "Error importing file!", "Error", 
                                 JOptionPane.ERROR_MESSAGE);

   JOptionPane.showMessageDialog(frame, "File successfully imported!", "Message", 
                                 JOptionPane.PLAIN_MESSAGE);

   JOptionPane.showMessageDialog(frame, "File successfully imported?", "Question",
                                 JOptionPane.QUESTION_MESSAGE);

   ImageIcon icon = new ImageIcon("thumbsup.gif");
   JOptionPane.showMessageDialog(frame, "File successfully imported!", "Hey", 
                                 JOptionPane.INFORMATION_MESSAGE, icon);

   int status = JOptionPane.showOptionDialog(frame, "Are you sure you want to import this file?", 
                                             "Question", JOptionPane.YES_NO_CANCEL_OPTION, 
                                             JOptionPane.QUESTION_MESSAGE, null, null, null);
   System.out.println("Option " + status + " selected!");

   Object[] options = { "Ja", "Nee", "Annuleren", "Test" };
   status = JOptionPane.showOptionDialog(frame, "Ben je zeker dat je dit bestand wilt importeren?",
                                         "vraag", -1, JOptionPane.QUESTION_MESSAGE, null,
                                         options, options[2]);
   System.out.println("Option " + status + " selected!");

   options = new Object[] { "Yes, please", "No, thanks" };
   status = JOptionPane.showOptionDialog(frame, "Error importing, try again?", "Question",
                                         -1, JOptionPane.ERROR_MESSAGE, null,
                                         options, options[0]);
   System.out.println("Option " + status + " selected!");

   String value = JOptionPane.showInputDialog("Please enter your name"); 
   System.out.println("You entered: " + value);

   options = new Object[] { "male", "female" };
   value = (String) JOptionPane.showInputDialog(frame, "Select your sex", "Input", 
                                                JOptionPane.QUESTION_MESSAGE, icon, options, 
                                                options[1]); 
   System.out.println("You entered: " + value);

   JDesktopPane desktop = new JDesktopPane(); 
   frame.setContentPane(desktop);
   frame.setSize(new Dimension(400, 200));
   frame.setLocation(100, 100);
   frame.setVisible(true);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
   status = JOptionPane.showInternalOptionDialog(desktop, "Are you sure you want to import this file?", 
                                                 "Question", JOptionPane.YES_NO_CANCEL_OPTION, 
                                                 JOptionPane.QUESTION_MESSAGE, null, null, null);
   System.out.println("Option " + status + " selected!");

The complete working example: Main.java:

import javax.swing.*;
import java.awt.*;
 
public class Main
{
   public static void main(String []args) {
      JFrame frame = new JFrame();
 
      // #1 
      JOptionPane.showMessageDialog(frame, "File successfully imported!");
 
      // #2
      JOptionPane.showMessageDialog(frame, "Deprecated version", "Warning", 
                                    JOptionPane.WARNING_MESSAGE);
 
      // #3
      JOptionPane.showMessageDialog(frame, "Error importing file!", "Error", 
                                    JOptionPane.ERROR_MESSAGE);
      
      // #4
      JOptionPane.showMessageDialog(frame, "File successfully imported!", "Message", 
                                    JOptionPane.PLAIN_MESSAGE);
 
      // #5
      JOptionPane.showMessageDialog(frame, "File successfully imported?", "Question",
                                    JOptionPane.QUESTION_MESSAGE);
 
      // #6
      ImageIcon icon = new ImageIcon("thumbsup.gif");
      JOptionPane.showMessageDialog(frame, "File successfully imported!", "Hey", 
                                    JOptionPane.INFORMATION_MESSAGE, icon);
 
      // #7
      int status = JOptionPane.showOptionDialog(frame, "Are you sure you want to import this file?", 
                                                "Question", JOptionPane.YES_NO_CANCEL_OPTION, 
                                                JOptionPane.QUESTION_MESSAGE, null, null, null);
      System.out.println("Option " + status + " selected!");
 
      // #8
      Object[] options = { "Ja", "Nee", "Annuleren", "Test" };
      status = JOptionPane.showOptionDialog(frame, "Ben je zeker dat je dit bestand wilt importeren?",
                                            "vraag", -1, JOptionPane.QUESTION_MESSAGE, null,
                                            options, options[2]);
      System.out.println("Option " + status + " selected!");
 
      // #9
      options = new Object[] { "Yes, please", "No, thanks" };
      status = JOptionPane.showOptionDialog(frame, "Error importing, try again?", "Question",
                                            -1, JOptionPane.ERROR_MESSAGE, null,
                                            options, options[0]);
      System.out.println("Option " + status + " selected!");
 
      // #10
      String value = JOptionPane.showInputDialog("Please enter your name"); 
      System.out.println("You entered: " + value);
      
      // #11
      options = new Object[] { "male", "female" };
      value = (String) JOptionPane.showInputDialog(frame, "Select your sex", "Input", 
                                                   JOptionPane.QUESTION_MESSAGE, icon, options, 
                                                   options[1]); 
      System.out.println("You entered: " + value);
 
      // #12
      JDesktopPane desktop = new JDesktopPane(); 
      frame.setContentPane(desktop);
      frame.setSize(new Dimension(400, 200));
      frame.setLocation(100, 100);
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
      status = JOptionPane.showInternalOptionDialog(desktop, "Are you sure you want to import this file?", 
                                                    "Question", JOptionPane.YES_NO_CANCEL_OPTION, 
                                                    JOptionPane.QUESTION_MESSAGE, null, null, null);
      System.out.println("Option " + status + " selected!");
 
      System.exit(1);
   }
}

Creating a scrollable JPanel

Create a JScrollPane and pass your panel to its constructor. Then add the scrollpane to the container. Make sure your panel has a size in case you use the null layout manager (with setSize and setPreferredSize). Here’s an example that uses a BorderLayout.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new BorderLayout());
 
      JPanel panel = createPanel();
 
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(panel));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static JPanel createPanel() {
      JPanel panel = new JPanel();
      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);
   } 
} 

Find out what JTabbedPane tab is selected

Note:
1.Each Tab in a Tabbed Pane is a JPanel i.e it has a name
2.The first Tab index is ’0′, 2′nd tab ’1′ and so on.
3.’StateChanged’ event is fired on selection of a tab.

....
....
....
tabbedPane.addChangeListener(changeListener)
....
....
public void stateChanged(changeEvent)
{
   if(e.getSource() == tabbedPane)
   {
      int i = tabbedPane.getSelectedIndex();
      Component c = tabbedPane.getSelectedComponent();
   }
}
....
....