Can I add an animated gif file to JButton? - java

I'm trying to add a .gif file into a JButton, but seems like it doesn't work - the gif file didn't move, it displayed like a normal Image.
Here are my codes:
+The ImageButton Class:
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
/**
* Button which display a png or gif image.
* */
public class ImageButton extends JButton {
private static final long serialVersionUID = 1L;
private ImageIcon defaultIcon;
private ImageIcon hoverIcon;
/**
* Create a normal JButton.
* */
public ImageButton(){
super();
}
/**
* Create a new ImageButton Object.
* #param img1 url of normal image of the button
* #param img2 url hover image of the button
* #param width button width
* #param height button height
* */
public ImageButton(String img1, String img2, int width, int height){
super();
BufferedImage defaultIcon = null;
BufferedImage hoverIcon = null;
try {
defaultIcon = ImageIO.read(getClass().getResource(img1));
hoverIcon = ImageIO.read(getClass().getResource(img2));
} catch (IOException e) {
e.printStackTrace();
}
this.defaultIcon = new ImageIcon(defaultIcon);
this.hoverIcon = new ImageIcon(hoverIcon);
setIcon(this.defaultIcon);
setPreferredSize(new Dimension(width,height));
setBorder(null);
setOpaque(false);
setContentAreaFilled(false);
setBorderPainted(false);
}
/**
* Hover the button.
* */
public void hover(){
setIcon(hoverIcon);
}
/**
* Return the button to normal.
* */
public void down(){
setIcon(defaultIcon);
}
}
+The Test Class:
import java.awt.FlowLayout;
import javax.swing.JFrame;
public class TestGifButton {
public static void main(String[] args) {
ImageButton button = new ImageButton("level3.gif","level3.gif", 150, 150);
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
frame.add(button);
frame.pack();
frame.setVisible(true);
}
}
I used a looping .gif file.
So how can I fix it ? thanks a lot :'(

JButton button = new JButton(new ImageIcon(getClass().getClassLoader().getResource("Images/BBishopB.gif")));
OR
Full Example :
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.swing.*;
public class ImageSwapOnButton {
public static void main( String[] args ) throws Exception {
URL url = new URL("http://1point1c.org/gif/thum/plnttm.gif");
Image image = Toolkit.getDefaultToolkit().createImage(url);
ImageIcon spinIcon = new ImageIcon(image);
JOptionPane.showMessageDialog(null, new JLabel(spinIcon));
// create a static version of this icon
BufferedImage bi = new BufferedImage(150,150,BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.getGraphics();
g.drawImage(image,0,0,null);
g.dispose();
ImageIcon staticIcon = new ImageIcon(bi);
JButton button = new JButton(staticIcon);
button.setRolloverIcon(spinIcon);
JOptionPane.showMessageDialog(null, button);
}
}

well, you might try this for your animation...
File file = new File("img/ani.gif");
URL url = file.toURI().toURL();
Icon icon = new ImageIcon(url);
JButton aniButt = new JButton(icon);
maybe you must also set the mouseover and pressed icons as well..
but read the https://stackoverflow.com/a/18271876/714968 ... (as mKorbel metioned!)

Related

How do I swap icons on buttons arranged in GridLayout using Drag and Drop?

I'm trying to create a jigsaw puzzle of sorts, where I have loaded an image onto a 5x5 grid, cropped the image and assigned each cropped part as an icon to 25 buttons arranged in the same pattern. I want to be able to drag my mouse pointer from a button to another and swap the icons on those 2 buttons.
I've tried using multiple MouseListener methods and MouseMotionListener methods, but nothing has worked so far.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.Component;
import javax.swing.*;
//import java.awt.image.*;
public class ImageMove {
JFrame jf;
JButton[][] grid;
JLabel test;
public static void main(String[] args) {
ImageMove ob = new ImageMove();
ob.start();
}
public void start() {
jf = new JFrame();
JPanel gridPanel = new JPanel();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon img = new ImageIcon("download.jpg");
Image temp1= img.getImage();
img=new ImageIcon(temp1.getScaledInstance(500, 500, Image.SCALE_SMOOTH));
Image img1 = img.getImage();
gridPanel.setLayout(new GridLayout (5,5));
grid = new JButton[5][5];
for(int y=0;y<5;y++) {
for(int x=0; x<5; x++) {
Image image = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(img1.getSource(), new CropImageFilter(x * 500 / 5, y * 500 / 5, 100, 100)));
ImageIcon icon = new ImageIcon(image);
JButton temp = new JButton(icon);
temp.setTransferHandler(new TransferHandler("icon"));
temp.addMouseMotionListener(new DragMouseAdapter());
grid[x][y]=temp;
gridPanel.add(grid[x][y]);
}
}
test= new JLabel();
jf.getContentPane().add(BorderLayout.NORTH, test);
jf.add(gridPanel);
jf.pack();
jf.setSize(500, 500);
jf.setVisible(true);
}
class DragMouseAdapter extends MouseAdapter{
private int x, y;
public void mouseDragged(MouseEvent e) {
final int x0=MouseInfo.getPointerInfo().getLocation().x;
final int y0=MouseInfo.getPointerInfo().getLocation().y;
x=x0;
y=y0;
JButton c = (JButton) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
public void mouseReleased(MouseEvent e) {
JButton c = (JButton) e.getSource();
Icon icon = c.getIcon();
grid[((int)(x/100))][((int)(y/100))].setIcon(icon);
}
}
}
Currently, the program copies the icon from the first button to the second button, i.e. it replaces the second button's icon with the first, but the first button remains the same. I expect to swap those two icons entirely. The MouseDragged method towards the end is performing the described behavior, but the MouseReleased doesn't seem to do anything at all.
Any help is much appreciated.
It's very easy. You simply need to save somewhere the drag source button, and on drop replace its icon with the old icon of drop target button.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Transferable;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.TransferHandler;
//import java.awt.image.*;
public class ImageMove {
JFrame jf;
JButton[][] grid;
JLabel test;
JButton dragSource; // here we save drag source component
public static void main(String[] args) {
ImageMove ob = new ImageMove();
ob.start();
}
public void start() {
jf = new JFrame();
JPanel gridPanel = new JPanel();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon img = new ImageIcon("download.jpg");
Image temp1 = img.getImage();
img = new ImageIcon(temp1.getScaledInstance(500, 500, Image.SCALE_SMOOTH));
Image img1 = img.getImage();
gridPanel.setLayout(new GridLayout(5, 5));
grid = new JButton[5][5];
for (int y = 0; y < 5; y++) {
for (int x = 0; x < 5; x++) {
Image image = Toolkit.getDefaultToolkit()
.createImage(new FilteredImageSource(img1.getSource(), new CropImageFilter(x * 500 / 5, y * 500 / 5, 100, 100)));
ImageIcon icon = new ImageIcon(image);
JButton temp = new JButton(icon);
// use own extension of TransferHandler
temp.setTransferHandler(new MyTransferHandler("icon"));
// start drag on mouse pressed event.
temp.addMouseListener(new DragMouseAdapter());
grid[x][y] = temp;
gridPanel.add(grid[x][y]);
}
}
test = new JLabel();
jf.getContentPane().add(BorderLayout.NORTH, test);
jf.add(gridPanel);
jf.pack();
jf.setSize(500, 500);
jf.setVisible(true);
}
class DragMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
JButton c = (JButton) e.getSource();
dragSource = c;
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
}
private class MyTransferHandler extends TransferHandler {
public MyTransferHandler(String property) {
super(property);
}
#Override
public boolean importData(JComponent comp, Transferable t) {
Icon targetIcon = ((JButton) comp).getIcon();
boolean result = super.importData(comp, t);
if (dragSource != null) {
dragSource.setIcon(targetIcon);
dragSource = null;
}
return result;
}
}
}

Swing JScrollPane gallery implementation

I am trying to make a JComponent function as a gallery. It must able to display saved images on it which are going to be showed in a component living in a JScrollPane. I am also going to add the functionality to remove an image. I managed to display the image on the component. How should I approach this?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
public class GalleryPanel extends JPanel
{
private static final long serialVersionUID = 1L;
private int currentImage;
private JLabel[] images;
private final int MAX_IMAGES = 12;
private JScrollPane scrollPane;
private JPanel imageGallery;
public void init()
{
setLayout(new BorderLayout());
images = new JLabel[MAX_IMAGES];
imageGallery = new JPanel();
imageGallery.setLayout(new GridLayout(12,1,10,10));
scrollPane = new JScrollPane();
scrollPane.setBackground(Color.RED);
scrollPane.add(imageGallery);
add(scrollPane, BorderLayout.CENTER);
setBackground(Color.GRAY);
}
public void addImageToGallery(File file)
{
if ( currentImage <= images.length - 1)
{
BufferedImage bufImage = null;
try
{
bufImage = ImageIO.read(file); //tries to load the image
}
catch (Exception e)
{
System.out.println("Unable to load file " + file.toString());
}
Image resizedImage = bufImage.getScaledInstance(bufImage.getWidth()/6, bufImage.getHeight()/6, Image.SCALE_SMOOTH);
ImageIcon icon = new ImageIcon(resizedImage);
images[currentImage] = new JLabel(icon, JLabel.CENTER);
scrollPane.add(images[currentImage]);
images[currentImage].setSize(120, 100);
scrollPane.add(images[currentImage]);
currentImage++;
//scrollPane.revalidate();
//scrollPane.repaint();
}
else
{
throw new ArrayIndexOutOfBoundsException("The gallery is full");
}
}
public final int getMaxImages()
{
return MAX_IMAGES;
}
public Dimension getPreferredSize()
{
return new Dimension(300, 700);
}
}
I created JImagePanel for my CBIR java application using JPanel, JList, JLabel and ListCellRenderer
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javax.swing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.Vector;
import javax.swing.border.LineBorder;
/**
*
* #author NiRRaNjAN RauT
*/
/**
* JImagePanel is used to display JList of BufferedImage
* This class is extended to JPanel
*/
public class JImagePanel extends JPanel {
/**
* JList is used to display display BufferedImage
*/
private JList imageList = null;
/**
* JScrollPane is used to add scroll bar to JList
*/
JScrollPane scroll_pane = null;
/**
* Vector<BufferedImage> is used to store the BufferedImages
*/
Vector<BufferedImage> listData = new Vector<BufferedImage>();
/**
* default constructor used to initialize JPanel
*/
public JImagePanel() {
this(null);
}
/**
* #param data
* This parameterized constructor is used to
* add the vector of BufferedImages to JList
*/
public JImagePanel(Vector<BufferedImage> data) {
setLayout(new BorderLayout());
if(data != null) {
listData = data;
}
imageList = new JList();
imageList.setFixedCellHeight(160);
imageList.setFixedCellWidth(160);
if(!listData.isEmpty()) {
imageList.setListData(listData);
}
imageList.setCellRenderer(new JCellRenderer());
imageList.setAutoscrolls(true);
imageList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
imageList.setVisibleRowCount(-1);
scroll_pane = new JScrollPane(imageList);
this.add(scroll_pane, BorderLayout.CENTER);
this.setBorder(new LineBorder(Color.BLUE));
}
/**
* #param selection
* The parameter selection is used to set multi selection on or off
* When true, it allows to select multiple images in JList using
* Ctrl key.
*/
public void setMultiSelection(boolean selection) {
if(selection) {
imageList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
} else {
imageList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
}
public int[] getSelectedIndices() {
return imageList.getSelectedIndices();
}
public int getImageSize() {
return imageList.getModel().getSize();
}
/**
* #param image
* This is used to add BufferedImage to JList
* User can add new images to JList at runtime.
*/
public void addImageToList(BufferedImage image) {
listData.add(image);
imageList.setListData(listData);
}
/**
* The method is used to clear the old list data.
* It sets the list data to empty list.
*/
public void clear() {
listData.clear();
imageList.setListData(listData);
}
/**
* #param data
* This method is used to set list data to JList
* The data should be Vector of BufferedImage
*/
public void setListData(Vector<BufferedImage> data) {
if(data == null || data.isEmpty()) {
System.err.println("Empty Data");
return;
}
listData = data;
imageList.setListData(listData);
}
}
For this Panel ListCellRenderer component is required which is given below.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javax.swing;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.border.EmptyBorder;
/**
*
* #author NiRRaNjAN RauT
*/
/**
* JCellRenderer is extended to JLabel
* It is used to display the image on JList by implementing ListCellRenderer
*/
public class JCellRenderer extends JLabel implements ListCellRenderer {
/**
* The width and height is used to set size of a JLabel.
* It is default set to 200 * 200
*/
private static final int width = 140, height = 140;
/**
* default constructor used to set size of JLabel and set Border to JLabel.
*/
public JCellRenderer() {
setSize(width, height);
setOpaque(true);
setBorder(new EmptyBorder(10, 10, 10, 10));
}
/**
* #return Component
* it returns JLabel for a cell.
* The image from JList is set as icon on JLabel so that it displays the image as a JList item.
*/
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
try {
if(value instanceof BufferedImage) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.drawImage((BufferedImage) value, 0, 0, width, height, null);
g.dispose();
setIcon(new ImageIcon(image));
}
if(isSelected) {
setBackground(Color.DARK_GRAY);
} else {
setBackground(Color.LIGHT_GRAY);
}
} catch(Exception ex) {
System.err.println("" + ex.getMessage());
}
return this;
}
}
and This is how to use it.
JFrame frame = new JFrame("Image Panel Demo");
frame.setResizable(true);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JImagePanel panel = new JImagePanel();
panel.setMultiSelection(true);
frame.setLayout(new BorderLayout());
frame.add(panel, BorderLayout.CENTER);
frame.setVisible(true);
try {
File files[] = new File("/SOFTWARES/NETBEANS_PROJECTS/BE/S_CBIR/dataset").listFiles();
for(File file : files) {
BufferedImage image = ImageIO.read(file);
panel.addImageToList(image);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
Hope it'll help.
scrollPane.add(images[currentImage]);
images[currentImage].setSize(120, 100);
scrollPane.add(images[currentImage]);
Don't add components directly to a scroll pane.
A JScrollPane uses a JViewport to hold the component to be displayed.
So if you want to use a JList you would use:
JList<Icon> list = new JList<Icon>();
JScrollPane scrollPane = new JScrollPane( list );
frame.add( scrollPane );
Then you add the Icon (not a JLabel) to the JList. A JList already has a custom renderer to display an Icon.
Read the section from the Swing tutorial on How to Use Lists for more information and working examples.
The tutorial also has a section on How to Use Scroll Panes you should read.

paintComponent not called when calling JScrollPane

I'm trying to load a background image with a JFileChooser, but when the operation ends, the paintcomponent() method is not called as expected.
[EDIT] for this reason, instead of having a red ball over the background image, I have the red ball only.
I read in several other topics that the instance of my Mappa Object should be added to the frame:
Why is paint()/paintComponent() never called?
paintComponent not being called at the right time
PaintComponent is not being called
But this does not solve my problem: I created a JScrollPane that gets my component in the constructor and linked the JScrollPane and added it in the main frame with
frmEditor.getContentPane().add(scrollabile, BorderLayout.CENTER);
This is the code of the main Gui
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
public class Gui implements ActionListener {
private JFrame frmEditor;
Mappa content;
private JMenuItem mntmSfondo;
private JScrollPane scrollabile;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Gui window = new Gui();
window.frmEditor.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Gui() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmEditor = new JFrame();
frmEditor.setFont(UIManager.getFont("TextArea.font"));
frmEditor.setBounds(50, 50, 1024, 768);
frmEditor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmEditor.getContentPane().setLayout(new BorderLayout(0, 0));
JPanel panelTile = new JPanel();
panelTile.setLayout(new BorderLayout(0, 0));
JPanel panelStrum = new JPanel();
panelStrum.setLayout(new GridLayout(15, 2));
content = new Mappa(null);
content.setMinimumSize(new Dimension(150, 150));
scrollabile = new JScrollPane(content);
scrollabile
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollabile
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
frmEditor.getContentPane().add(scrollabile, BorderLayout.CENTER);
inizializzaMenu();
}
/**
* Initialize the menu.
*/
private void inizializzaMenu() {
JMenuBar menuBar = new JMenuBar();
frmEditor.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
mnFile.setFont(UIManager.getFont("TextArea.font"));
JMenu mnAltro = new JMenu("Modify");
mnAltro.setFont(UIManager.getFont("TextArea.font"));
menuBar.add(mnAltro);
mntmSfondo = new JMenuItem("Load Background");
mntmSfondo
.setIcon(new ImageIcon(
Gui.class
.getResource("/com/sun/java/swing/plaf/windows/icons/TreeOpen.gif")));
mntmSfondo.setFont(UIManager.getFont("TextArea.font"));
mntmSfondo.addActionListener(this);
mnAltro.add(mntmSfondo);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == mntmSfondo) {
JFileChooser fc = new JFileChooser("tuttiSfondi");
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
content = new Mappa(file);
} catch (Exception ex) {
}
}
if (result == JFileChooser.CANCEL_OPTION) {
}
}
}
}
while this is the code of the class Mappa, that I would like to use to load the background from the JFileChooser.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Mappa extends JPanel {
Image immagine;
public Mappa(File fileImmagine) {
if (fileImmagine != null ) {
BufferedImage img = null;
try {
img = ImageIO.read(new File(fileImmagine.getPath()));
} catch (IOException e) {
e.printStackTrace();
}
this.immagine = img;
}
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.clearRect(0, 0, 4000, 4000);
g.drawImage(immagine, 0, 0, null);
g.setColor(Color.red);
g.fillOval(170, 170, 150, 150);
System.out.println("Called Repaint() on Mappa");
}
}
The problem is not in an incorrect image path, since it loads if I set the path on the Mappa class "manually", by giving the path instead of using new File(fileImmagine.getPath()) in the ImageIO.read, but that paintComponent is called only once, when the constructor of Mappa is called from the Gui class
When you set the background, you only allocate the new Mappa instance, but not actually adding it to any container. Try adding the following:
scrollabile.setViewportView(content);
Or instead, replace an image in the Mappa class. Ie:
public void setImage(File file) throws IOException {
this.immagine = ImageIO.read(file);
repaint();
}
Also, in paintComponent(), you could use panel dimensions to fill the whole area:
g.drawImage(immagine, 0, 0, getWidth(), getHeight(), this);
And don't forget to use a valid ImageObserver as JPanel implements one.
You aren't actually modifying the Mapa instance that you've added to the frame. The line
content = new Mappa(file);
in actionPerformed() doesn't change the panel in the frame, it reassigns the local variable only. You should instead put a method such as updateImage() in Mapa that will update the image that Mapa displays. You will also need to call repaint() after this so that it redraws the new image.

Zoom in and zoom out function in Jpanel

I have to add Zoom In and Zoom Out functionality to JPanel, which contains components like JLabel with ImageIcon.
I want to Zoom JPanel with their components appropriately
I tried with following code snippet but it did not work properly.
The JPanel which is having null layout and is itself placed inside an Applet.
I am unsure of the reason as to why it is not working either because of Applet or something else !!
cPanel is my JPanel which contains JLabel
Following code snippet on Zoom Button click,
it shows blink screen on button click after that as original
Graphics g = cPanel.getGraphics();
Graphics2D g2d = (Graphics2D) g;
AffineTransform savedXForm = g2d.getTransform();
g2d.scale(1.0, 1.0);
g2d.setColor(Color.red);
super.paint(g);
g2d.setTransform(savedXForm);
cPanel.validate();
cPanel.repaint();
You can have a look into this link:
http://blog.sodhanalibrary.com/2015/04/zoom-in-and-zoom-out-image-using-mouse_9.html#.Vz6iG-QXV0w
Source Code to Refer(Here it has been accomplished using MouseWheelListener):
import java.awt.EventQueue;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import com.mortennobel.imagescaling.ResampleOp;
import java.awt.event.MouseWheelListener;
import java.awt.event.MouseWheelEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ImageZoom {
private JFrame frmImageZoomIn;
private static final String inputImage = "C:\\my-pfl-pic.jpg"; // give image path here
private JLabel label = null;
private double zoom = 1.0; // zoom factor
private BufferedImage image = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ImageZoom window = new ImageZoom();
window.frmImageZoomIn.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #throws IOException
*/
public ImageZoom() throws IOException {
initialize();
}
/**
* Initialize the contents of the frame.
* #throws IOException
*/
private void initialize() throws IOException {
frmImageZoomIn = new JFrame();
frmImageZoomIn.setTitle("Image Zoom In and Zoom Out");
frmImageZoomIn.setBounds(100, 100, 450, 300);
frmImageZoomIn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane();
frmImageZoomIn.getContentPane().add(scrollPane, BorderLayout.CENTER);
image = ImageIO.read(new File(inputImage));
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
// display image as icon
Icon imageIcon = new ImageIcon(inputImage);
label = new JLabel( imageIcon );
panel.add(label, BorderLayout.CENTER);
panel.addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
int notches = e.getWheelRotation();
double temp = zoom - (notches * 0.2);
// minimum zoom factor is 1.0
temp = Math.max(temp, 1.0);
if (temp != zoom) {
zoom = temp;
resizeImage();
}
}
});
scrollPane.setViewportView(panel);
}
public void resizeImage() {
System.out.println(zoom);
ResampleOp resampleOp = new ResampleOp((int)(image.getWidth()*zoom), (int)(image.getHeight()*zoom));
BufferedImage resizedIcon = resampleOp.filter(image, null);
Icon imageIcon = new ImageIcon(resizedIcon);
label.setIcon(imageIcon);
}
}

Background image in java

i'm trying to put an image as a background of my interface in java , i tried to write a class that does that and using it , but is there a simpler way to do that .
here 's the code i used:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class BackgroundImagePanelExample {
// Set up contraints so that the user supplied component and the
// background image label overlap and resize identically
private static final GridBagConstraints gbc;
static {
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
}
/**
* Wraps a Swing JComponent in a background image. Simply invokes the overloded
* variant with Top/Leading alignment for background image.
*
* #param component - to wrap in the a background image
* #param backgroundIcon - the background image (Icon)
* #return the wrapping JPanel
*/
public static JPanel wrapInBackgroundImage(JComponent component,
Icon backgroundIcon) {
return wrapInBackgroundImage(
component,
backgroundIcon,
JLabel.TOP,
JLabel.LEADING);
}
/**
* Wraps a Swing JComponent in a background image. The vertical and horizontal
* alignment of background image can be specified using the alignment
* contants from JLabel.
*
* #param component - to wrap in the a background image
* #param backgroundIcon - the background image (Icon)
* #param verticalAlignment - vertical alignment. See contants in JLabel.
* #param horizontalAlignment - horizontal alignment. See contants in JLabel.
* #return the wrapping JPanel
*/
public static JPanel wrapInBackgroundImage(JComponent component,
Icon backgroundIcon,
int verticalAlignment,
int horizontalAlignment) {
// make the passed in swing component transparent
component.setOpaque(false);
// create wrapper JPanel
JPanel backgroundPanel = new JPanel(new GridBagLayout());
// add the passed in swing component first to ensure that it is in front
backgroundPanel.add(component, gbc);
// create a label to paint the background image
JLabel backgroundImage = new JLabel(backgroundIcon);
// set minimum and preferred sizes so that the size of the image
// does not affect the layout size
backgroundImage.setPreferredSize(new Dimension(1, 1));
backgroundImage.setMinimumSize(new Dimension(1, 1));
// align the image as specified.
backgroundImage.setVerticalAlignment(verticalAlignment);
backgroundImage.setHorizontalAlignment(horizontalAlignment);
// add the background label
backgroundPanel.add(backgroundImage, gbc);
// return the wrapper
return backgroundPanel;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Background Image Panel Example");
// Create some GUI
JPanel foregroundPanel = new JPanel(new BorderLayout(10, 10));
foregroundPanel.setBorder(
BorderFactory.createEmptyBorder(10, 10, 10, 10));
foregroundPanel.setOpaque(false);
foregroundPanel.add(new JLabel("Comment:"), BorderLayout.NORTH);
foregroundPanel.add(new JScrollPane(new JTextArea(3, 10)),
BorderLayout.CENTER);
foregroundPanel.add(
new JLabel(
"Please enter your comments in text box above."
+ " HTML syntax is allowed."), BorderLayout.SOUTH);
frame.setContentPane(wrapInBackgroundImage(foregroundPanel,
new ImageIcon(
BackgroundImagePanelExample.class.getResource("backgd.jpg"))));
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
thanks
I'm guessing you're getting java.lang.NullPointerException because backgd.jpg can't be found by getResource(). You might be able to put the image file alongside the source file and rebuild the project. Alternatively, you can load it from the file system as a temporary measure while you sort things out.
frame.setContentPane(wrapInBackgroundImage(
foregroundPanel, new ImageIcon("image.jpg")));
I dont actually see what are you asking. If you are asking, whether there is simpler way to build swing apps - than answer is YES. Use NetBeans IDE with Swing builder which produces very reasonable generated code and lets you edit whole bunch of componenets. Hand written Swing is more often "broken" than generated code from NetBeans, and much much more time consuming ...
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ImageTest {
public static void main(String[] args) {
ImagePanel panel = new ImagePanel(new ImageIcon("images/background.png").getImage());
JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
class ImagePanel extends JPanel {
private Image img;
public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}
public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
public class BackgroundPanel extends JPanel {
private static final long serialVersionUID = 1L;
Image image;
public BackgroundPanel() {
super();
initialize();
}
/**
* This method initializes this
*
* #return void
*/
private void initialize() {
try {
image = new ImageIcon(getClass().getResource("background.jpg")).getImage();
} catch (Exception e) {
/*handled in paintComponent()*/
}
this.setSize(800, 470);
this.setLayout(null);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(image != null) {
g.drawImage(image, 0,0,this.getWidth(),this.getHeight(),this);
}
}
}

Categories