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

Hiding a JToolBar that has been made floatable

Here’s an example that will hide a JToolBar, whether or not they have been made floatable.

Main.java:

import javax.swing.border.*;
import javax.swing.plaf.basic.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.awt.*;
  
public class Main extends JFrame {
   public Main() {
      super("JToolBar hide/show example");
 
      final JTextArea textArea = new JTextArea(5, 30);
      final MyJToolBar toolBar = new MyJToolBar();
 
      JButton gifButton = new JButton(new ImageIcon("gifIcon.gif"));
      JButton jpgButton = new JButton(new ImageIcon("jpgIcon.gif"));
      JButton tiffButton = new JButton(new ImageIcon("tiffIcon.gif"));
 
      gifButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("gifButton clicked!n");
         }
      });
  
      jpgButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("jpgButton clicked!n");
         }
      });
        
      tiffButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("tiffButton clicked!n");
         }
      });
 
      toolBar.add(gifButton);
      toolBar.add(new JToolBar.Separator());
      toolBar.add(jpgButton);
      toolBar.add(new JToolBar.Separator());
      toolBar.add(tiffButton);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.NORTH, toolBar);
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(textArea));
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("Toolbar");
      final JMenuItem hideShowMenuItem = new JCheckBoxMenuItem("Hide");
      menu.add(hideShowMenuItem);
      menuBar.add(menu);
      setJMenuBar(menuBar);
   
      hideShowMenuItem.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            toolBar.setVisible(!hideShowMenuItem.isSelected());
         }
      });
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}
 
class MyJToolBar extends JToolBar
{
   public MyJToolBar() {
      super();
   }
 
   public MyJToolBar(int orientation) {
      super(orientation);
   }
 
   public MyJToolBar(String name) {
      super(name);
   }
 
   public MyJToolBar(String name, int orientation) {
      super(name, orientation);
   }
 
   public void setVisible(boolean visible) {
      boolean isFloating = false;
      if (getUI() instanceof BasicToolBarUI) {
         isFloating = ((BasicToolBarUI) ui).isFloating();
      }
 
      if (isFloating) {
         SwingUtilities.getRoot(this).setVisible(visible);
      }
      else {
         super.setVisible(visible);
      }
   }
}

Preventing a JInternalFrame from being closed

Just specify so when you create a JInternalFrame, in the constructor, or call the method setClosable(false).

Main.java:

import java.awt.event.*;
import javax.swing.*;
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;
      JInternalFrame frame = new JInternalFrame(title,
         true,    // resizable
         true,    // closable
         true,    // maximizable
         true);   // iconifiable
      frame.setVisible(true); 
 
      // disable closing the frame
      frame.setClosable(false);
 
      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);
   }
}