Swing JScrollPane gallery implementation - java

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.

Related

java swing - painting multiple jpanels on the same jframe

Just to preface, I've looked for several hours trying to find a solution to this on here and several other sites. If you find a question I may have missed, please let me know.
Anywho, I'm trying to create a thumbnail viewer that displays 4 thumbnails (in jpanels) and 4 captions. I can draw out all 4 thumbnails, but they're all the same image (duplicates of the last one painted). I think it's part of how I'm trying to repaint them, but I can't figure out what to change. The imageAlbum is an ArrayList of jpg paths.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
//import MainFrame.ImageComponent;
import javax.swing.JLabel;
public class Thumbnails extends JFrame {
final int IMG_WIDTH = 80;
final int IMG_HEIGHT = 60;
private BufferedImage image;
private ImageAlbum imageAlbum;
private JPanel contentPane;
private JPanel thmbnl_1;
private JPanel thmbnl_2;
private JPanel thmbnl_3;
private JPanel thmbnl_4;
private JLabel thmbnl_1Label;
private JLabel thmbnl_2Label;
private JLabel thmbnl_3Label;
private JLabel thmbnl_4Label;
/**
* Create the frame.
*/
public Thumbnails(ImageAlbum album) {
imageAlbum = album;
String captionUnavailable = "Caption is not available";
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(new GridLayout(4, 2, 0, 0));
thmbnl_1 = new JPanel();
thmbnl_1.setPreferredSize(new Dimension(80, 60));
panel.add(thmbnl_1);
thmbnl_2 = new JPanel();
thmbnl_2.setPreferredSize(new Dimension(80, 60));
panel.add(thmbnl_2);
thmbnl_1Label = new JLabel(captionUnavailable);
panel.add(thmbnl_1Label);
thmbnl_2Label = new JLabel(captionUnavailable);
panel.add(thmbnl_2Label);
thmbnl_3 = new JPanel();
thmbnl_3.setPreferredSize(new Dimension(IMG_WIDTH, IMG_HEIGHT));
panel.add(thmbnl_3);
thmbnl_4 = new JPanel();
thmbnl_4.setPreferredSize(new Dimension(IMG_WIDTH, IMG_HEIGHT));
panel.add(thmbnl_4);
thmbnl_3Label = new JLabel(captionUnavailable);
panel.add(thmbnl_3Label);
thmbnl_4Label = new JLabel(captionUnavailable);
panel.add(thmbnl_4Label);
setupThumbnails();
}// end Thumbnails(ImageAlbum album)
//
private void setupThumbnails() {
int albumSize = imageAlbum.getSize();
for(int i = 0; i < albumSize; i++) {
try {
image = resizeToThumbnail(ImageIO.read(new File(imageAlbum.getAlbum(i))));
switch(i) {
case 0:
thmbnl_1.setLayout(new BorderLayout());
thmbnl_1.add(new ImageComponent(image), BorderLayout.CENTER);
thmbnl_1Label.setText(imageAlbum.getCaption(i));
break;
case 1:
thmbnl_2.setLayout(new BorderLayout());
thmbnl_2.add(new ImageComponent(image), BorderLayout.CENTER);
thmbnl_2Label.setText(imageAlbum.getCaption(i));
break;
case 2:
thmbnl_3.setLayout(new BorderLayout());
thmbnl_3.add(new ImageComponent(image), BorderLayout.CENTER);
thmbnl_3Label.setText(imageAlbum.getCaption(i));
break;
case 3:
thmbnl_4.setLayout(new BorderLayout());
thmbnl_4.add(new ImageComponent(image), BorderLayout.CENTER);
thmbnl_4Label.setText(imageAlbum.getCaption(i));
break;
default:
break;
}// end switch-case
revalidate();
repaint();
}// end try-block
catch(IOException e) {
e.printStackTrace();
}// end catch-block
}// end for-loop
}// end setupCaptions()
//
public BufferedImage resizeToThumbnail(BufferedImage original) {
int type;
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, original.getType());
Graphics2D g = resizedImage.createGraphics();
g.drawImage(original, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
return resizedImage;
}// end resizeToThumbnail(...)
class ImageComponent extends JComponent {
/**
* Desc: constructor for ImageComponent
* #param: BufferedImage img
* #return: nothing
*/
public ImageComponent(BufferedImage img) {
image = img;
}// end ImageComponent()
/**
* Desc: draws out the image to the panel
* #param: Graphics g
* #return: void
*/
#Override
public void paintComponent(Graphics g) {
if(image == null)
return;
Graphics2D g2d = (Graphics2D) g;
// draw the image
g.drawImage(image, 0, 0, this);
g.dispose();
}// end paintComponents(Graphics g)
}// end class ImageComponent
}// end class class Thumbnails
EDIT
ImageAlbum class:
import java.util.*;
public class ImageAlbum {
private ArrayList imageAlbum;
private ArrayList imageCaptions;
private int size;
/**
* Desc: getter for album size
* #param: none
* #return: int
*/
public int getSize() {
return size;
}// end getSize()
/**
* Desc: getter for the image
* #param: int index
* #return: String
*/
public String getAlbum(int index) {
return imageAlbum.get(index).toString();
}// end getAlbum(int index)
/**
* Desc: getter for the image caption
* #param: int index
* #return: String
*/
public String getCaption(int index) {
return imageCaptions.get(index).toString();
}// end getCaption(int index)
/**
* Desc: default constructor for ImageAlbum
* #param: none
* #return: nothing
*/
public ImageAlbum() {
imageAlbum = new ArrayList();
imageCaptions = new ArrayList();
size = 0;
}// end ImageAlbum()
/**
* Desc: parameterized constructor for ImageAlbum
* #param: none
* #return: nothing
*/
public ImageAlbum(ArrayList tempImageAlbum, ArrayList tempImageCaptions) {
imageAlbum = tempImageAlbum;
imageCaptions = tempImageCaptions;
}// end ImageAlbum(...)
/**
* Desc: adds the image directory and caption to both array lists
* #param: String imageDirectory, String imageCaption
* #return: void
*/
public void add(String imageDirectory, String imageCaption) {
imageAlbum.add(imageDirectory);
imageCaptions.add(imageCaption);
size++;
}// end add(...)
/**
* Desc: clears imageAlbum and imageCaptions array lists
* #param: nothing
* #return: void
*/
public void clear() {
imageAlbum.clear();
imageCaptions.clear();
size = 0;
}// end clear()
}// end class ImageAlbum
FINAL EDIT
I'm obviously not understanding very well, so I've decided to take a different approach - I'm using JLabels and doing icons instead. Works great, thanks everyone for your help
Your panel is set for a BorderLayout, and you call panel.add() for each of your thumbnails. That method sets the given component into the middle of the BorderLayout, replacing whatever is there, so that's why you're just seeing the last one added. BorderLayout does not do what you want for the thumbnails.
I would expect you want GridLayout; it lays out components added to it in rows and columns. Set your panel to GridLayout (or whatever else you want to layout the thumbnails), and add the thumbnails to it. Then put panel wherever you want; by default, a JFrame has a Borderlayout on it, you probably want to put panel in the middle of that.

Can I add an animated gif file to JButton?

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!)

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