Java Graphics How to - Shift image to left/right








Question

We would like to know how to shift image to left/right.

Answer

import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.net.URL;
//from   ww  w  .java  2  s  .  c o  m
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Main {

  public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.java2s.com/style/download.png");
    final BufferedImage image = ImageIO.read(url);
    int x = 50;
    final Image crop = image.getSubimage(x, 0, image.getWidth() - x,
        image.getHeight());
    Runnable r = new Runnable() {
      @Override
      public void run() {
        JPanel gui = new JPanel();
        gui.add(new JLabel(new ImageIcon(image)), BorderLayout.LINE_START);
        gui.add(new JLabel("java2s.com"));
        gui.add(new JLabel(new ImageIcon(crop)), BorderLayout.LINE_END);
        JOptionPane.showMessageDialog(null, gui);
      }
    };
    SwingUtilities.invokeLater(r);
  }
}