Disabling selection in my JTable

Look at the three lines of code in this working program to find out how to disallow any selection.

Main.java:

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));
      JScrollPane scrollPane = new JScrollPane(table);
 
      getContentPane().add(scrollPane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      // disable selection
      table.setRowSelectionAllowed(false);
      table.setColumnSelectionAllowed(false);
      table.setCellSelectionEnabled(false);
 
      pack();
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Catching an event when a form SUBMIT button has been clicked on a JTextPane

Set a custom HTMLEditorKit on your JTextPane. In the example below, this is MyHTMLEditorKit. It contains a factory that is responsible for returning a custom FormView. In MyFormView, you can override the method submitData that is called when the submit button is pressed. The form data is passed to this method in a escaped form.

Main.java:

import javax.swing.text.html.*;
import javax.swing.event.*;
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
{
   final JTextField urlTextField = new JTextField();
   final JEditorPane htmlPane = new JEditorPane();
   JButton urlButton = new JButton("Go!");
 
   public Main() {
      htmlPane.setEditable(false);
      urlTextField.setText("file:c:\test.html");
 
      urlButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            loadPage(urlTextField.getText());
         }
      });
 
      htmlPane.setEditorKit(new MyHTMLEditorKit());
 
      getContentPane().setLayout(new BorderLayout());
      JPanel topPanel = new JPanel(new BorderLayout());
      topPanel.add(BorderLayout.CENTER, urlTextField);
      topPanel.add(BorderLayout.EAST, urlButton);
 
      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);
   }
 
   public void loadPage(String url) {
      try {
         htmlPane.setPage(new URL(urlTextField.getText()));
      }
      catch(Exception e) {
         System.out.println(e);
      }
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
   }
}

MyHTMLEditorKit.java:

import javax.swing.text.html.*;
import javax.swing.text.*;
 
public class MyHTMLEditorKit extends HTMLEditorKit {
   private static final ViewFactory customFactory = new MyHTMLFactory();
 
   public ViewFactory getViewFactory() {
      return customFactory;
   }
 
   public static class MyHTMLFactory extends HTMLEditorKit.HTMLFactory
   {
      public View create(Element elem) {
         Object o = elem.getAttributes().getAttribute(StyleConstants.NameAttribute);
 
         if (o instanceof HTML.Tag) {
            HTML.Tag kind = (HTML.Tag) o;
            if (kind == HTML.Tag.INPUT || kind == HTML.Tag.SELECT || kind == HTML.Tag.TEXTAREA) {
               return new MyFormView(elem);
            }
            else return super.create(elem);
         }
 
         return super.create(elem);
      }
   }
}

MyFormView.java:

import javax.swing.text.html.*;
import javax.swing.text.*;
import java.awt.event.*;
import java.util.*;
 
public class MyFormView extends FormView
{
   public MyFormView(Element elem) {
      super(elem);
   }
 
   public void actionPerformed(ActionEvent event) {
      super.actionPerformed(event);
   }
 
   public void submitData(String data) {
      System.out.println("Escaped data: " + data);
   }
}

A simple HTML file to test it with: test.html:

<html>
<body>
 
<form METHOD=POST ACTION="performyourownaction">
 
   <i>Subcategory:</i><br>
   <SELECT NAME="subcat">
      <OPTION> J2SE </OPTION>
      <OPTION> J2EE </OPTION>
      <OPTION> J2ME </OPTION>
      <OPTION> Other </OPTION>
   </SELECT>
   <p>
   <i>Subject:</i><br>
      <input type=text size=80 maxsize=200 name="subject"><p>
   <i>Question:</i><br>
      <textarea name="question" cols=60 rows=4></textarea><p>
 
   <br><br>
 
   <input TYPE=SUBMIT VALUE=" Submit Question! ">
</form>
 
</body>
</html>

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