Fill JPanel with BufferedImage and print it on printer - java

I want to fill a panel with a BufferedImage (striped, see link below) and print it on a printer. The thing is that the pattern doesn't print, but it is visible as wanted on the panel. If I use a color instead of the striped image this gets printed.
You see two comments in the paintComponent-method below. Any ideas why I don't see the BufferedImage when I print?
Thanks!
You can find the image used here: http://imgur.com/sSlVUzK
package printbufferedimagepanel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.TexturePaint;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import static java.awt.print.Printable.NO_SUCH_PAGE;
import static java.awt.print.Printable.PAGE_EXISTS;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.imageio.ImageIO;
public class PrintBufferedImagePanel {
JFrame mainFrame;
JPanel mainPanel;
Buff printMe;
JButton printButton;
BufferedImage bf;
public PrintBufferedImagePanel() {
prepareGUI();
}
public static void main(String[] args) {
PrintBufferedImagePanel bip = new PrintBufferedImagePanel();
}
private void prepareGUI() {
mainFrame = new JFrame();
mainFrame.setLayout(new FlowLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
printMe = new Buff();
printButton = new JButton("Print");
mainPanel.setSize(400, 150);
mainPanel.add(printMe);
mainFrame.add(mainPanel);
mainFrame.add(printButton);
mainFrame.setSize(400, 250);
mainFrame.setVisible(true);
printButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(printMe);
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException de) {
System.err.println("Oops!");
}
}
}
});
}
class Buff extends JPanel implements Printable {
#Override
public Dimension getPreferredSize() {
return new Dimension(400,150);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage bImage = null;
TexturePaint tp = null;
try {
bImage = ImageIO.read(new File("src/printbufferedimagepanel/blueStripes.jpg"));
tp = new TexturePaint(bImage, new Rectangle(0,0,bImage.getWidth(),bImage.getHeight()));
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(tp); //<-- doesn't show at print, Why?
//g2.setColor(Color.CYAN); //<-- does show at print
g2.fillRect(0, 0, 400, 150);
} catch (Exception e) {
System.out.println("oops");
}
}
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
if (pageIndex > 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D)graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
this.printAll(graphics);
return PAGE_EXISTS;
}
}
}

Related

How can I use Graphics and Affinetransform draw a perspective picture

I want draw a picture with Java.
And I want rotate this picture along the X-axis or Y-axis to make the picture perspective.
It can make the image three-dimensional.
Do you know the function '3D rotation' in the PowerPoint? I just want to achieve this effect.
Can I use java to make it?
I am sorry that I have not describe my question carefully before.
This is the original image:
original image
I added a shear operation when I drew it
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.clearRect(0, 0, this.getWidth(), this.getHeight());
if (sourceImage != null) {
g2d.shear(0.5, 0);
g2d.drawImage(sourceImage, 0, 0, sourceImage.getWidth(), sourceImage.getHeight(), null);
}
}
And then it looks like this
The transformed image
But this is a linear transformation, I want perspective image, just like this
What I need to achieve
The AffineTransform in JAVA can only do linear transformations.
How can I use PerspectiveTransform, Do I need to use OpenGL or OpenCV to achieve it?
This is my complete code
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class ImagePanel extends JPanel{
private static final long serialVersionUID = 1L;
private BufferedImage sourceImage;
public ImagePanel() {
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.clearRect(0, 0, this.getWidth(), this.getHeight());
if (sourceImage != null) {
g2d.shear(0.5, 0);
g2d.drawImage(sourceImage, 0, 0, sourceImage.getWidth(), sourceImage.getHeight(), null);
}
}
public BufferedImage getSourceImage() {
return sourceImage;
}
public void setSourceImage(BufferedImage sourceImage) {
this.sourceImage = sourceImage;
}
}
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;
public class MainUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
public static final String IMAGE_CMD = "choose image ... ";
private JButton imgBtn;
private ImagePanel imagePanel;
private BufferedImage srcImage;
public MainUI() {
setTitle("image demo");
imgBtn = new JButton(IMAGE_CMD);
JPanel btnPanel = new JPanel();
btnPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
btnPanel.add(imgBtn);
imagePanel = new ImagePanel();
getContentPane().setLayout(new BorderLayout());
getContentPane().add(imagePanel, BorderLayout.CENTER);
getContentPane().add(btnPanel, BorderLayout.SOUTH);
imgBtn.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if(IMAGE_CMD.equals(e.getActionCommand())){
try {
JFileChooser chooser = new JFileChooser();
setFileTypeFilter(chooser);
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
if (f != null) {
srcImage = ImageIO.read(f);
imagePanel.setSourceImage(srcImage);
imagePanel.repaint();
}
} catch (IOException e1) {
e1.printStackTrace();
}
imagePanel.repaint();
}
}
public void setFileTypeFilter(JFileChooser chooser){
FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & PNG Images", "jpg", "png");
chooser.setFileFilter(filter);
}
public void openView(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(1280, 960));
pack();
setVisible(true);
}
public static void main(String[] args) {
MainUI ui = new MainUI();
ui.openView();
}
}

Image position is not updated

I am trying to make a button change its position once clicked. I have read that in order to set my components' positions manually. Thus I declared the default layout manager of my Frame as null. However my button's remains the same although the debugger tell me I am getting new (x, y) each time the button is clicked. Here is my source code :
Class GameUI.java :
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import de.tk1.g4.ta1.model.Player;
public class GameUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private String header[] = new String[]{"Player", "Score"};
private JTable table = new JTable();
private DefaultTableModel model = (DefaultTableModel) table.getModel();
private JPanel sidePanel = new JPanel();
private ImagePanel bodyPanel = new ImagePanel();
public GameUI() {
model.setColumnIdentifiers(header);
table.setEnabled(false);
getContentPane().setLayout(null);
getContentPane().add(sidePanel);
getContentPane().add(bodyPanel);
sidePanel.setLayout(new BoxLayout(sidePanel, BoxLayout.Y_AXIS));
sidePanel.add(table);
sidePanel.add(Box.createHorizontalStrut(10));
sidePanel.setBounds(0, 0, 300, 500);
bodyPanel.setBounds(300, 0, 700, 500);
setMaximumSize(new Dimension(700 + 300, 500));
setPreferredSize(new Dimension(700 + 300, 500));
setResizable(false);
super.paintComponents(getGraphics());
this.pack();
}
public void addPlayerToList (Player thePlayer) {
model.addRow(new Object[]{thePlayer.getName(), thePlayer.getScore()});
super.paintComponents(getGraphics());
}
public void clearPlayersTable() {
while(model.getRowCount() > 0)
{
model.removeRow(0);
}
}
public void setPokemonLocation (int x, int y) {
bodyPanel.getBtnPokemon().setLocation(x, y);
//repaint();
}
public JButton getPokButton () {
return bodyPanel.getBtnPokemon();
}
public ImagePanel getBodyPanel() {
return bodyPanel;
}
public void setBodyPanel(ImagePanel bodyPanel) {
this.bodyPanel = bodyPanel;
}
public void setImage(String path) throws IOException {
try {
FileInputStream fis = new FileInputStream(new File(path));
Image img = ImageIO.read(fis);
bodyPanel.getBtnPokemon().setIcon(new ImageIcon(img));
}catch(IOException e){
e.printStackTrace();
System.out.println(path);
}
}
public void setPokButton(int x,int y,String path) {
bodyPanel.setImage(path);
bodyPanel.getBtnPokemon().setLocation(x, y);
}
public void addPokemonListener(ActionListener listenForPokemon) {
bodyPanel.getBtnPokemon().addActionListener(listenForPokemon);
}
#Override
public void actionPerformed(ActionEvent e) {
super.paintComponents(getGraphics());
}
}
Class ImagePanel.java :
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
public class ImagePanel extends JPanel implements ActionListener{
private static final long serialVersionUID = 1L;
private JButton btnPokemon = new JButton("");
private BufferedImage image;
public ImagePanel() {
super();
this.setBorder(BorderFactory.createTitledBorder(""));
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setMaximumSize(new Dimension(700, 450));
this.setMinimumSize(new Dimension(700, 450));
this.add(btnPokemon);
}
#Override
public void paintComponent(Graphics g) {
if (g != null && image != null) {
super.paintComponent(g);
g.drawImage(image, btnPokemon.getX(), btnPokemon.getY(), null);
}
}
#Override
public void actionPerformed(ActionEvent e) {
super.paintComponents(getGraphics());
}
public void setImage(String path) {
try {
this.image = ImageIO.read(new File(path));
btnPokemon.setIcon(new ImageIcon(image));
} catch (IOException e) {
e.printStackTrace();
}
}
public JButton getBtnPokemon() {
return btnPokemon;
}
public void setBtnPokemon(JButton btnPokemon) {
this.btnPokemon = btnPokemon;
}
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
}
Although my controller calls this.gameUI.revalidate(); and this.gameUI.repaint();.
Any hints what I did miss in my source code please.

Robot.createScreenCapture() doesn't seem to match painting operations

I am trying to make a portion of my screen appear blurry. I grab pixel colors out of a BufferedImage where I saved a capture of the screen and draw the pixels again as bigger squares. But this only works when the paint method is called the first time, after that the affected pixels always stay the same even when the content of the screen updates. So it seems that even though the canvas is refreshed at the beginning of the paint method, the robot still sees the screen as it was previously...
#Override public void paintComponent(Graphics g) {
super.paintComponent(g);
screen = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
int gap = 10; int width = 1920;
for (int r = 120; r <= 420; r += gap) {
for (int c = 500; c <= width - 500; c += gap) {
g.setColor(new Color(screen.getRGB(c, r)));
g.fillRect(c, r, gap, gap);
}
}
}
I tried clearing the painted area using clearRect() and sleeping the Thread at different positions, but it didn't work. Where do I need to put the createScreenCapture() so the painting actually updates?
This is the whole class:
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Transparent extends JPanel implements Runnable {
private JFrame frame;
private Robot robot;
private BufferedImage screen;
public static void main(String[] args) {
new Transparent();
}
public Transparent() {
try {
robot = new Robot();
} catch (AWTException ex) {
ex.printStackTrace();
}
frame = new JFrame();
init();
frame.add(this);
frame.setUndecorated(true);
frame.setBackground(new Color(0, true));
frame.setAlwaysOnTop(true);
frame.setSize(1920, 1080);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
new Thread(this).start();
}
public void init() {
setBackground(new Color(0, true));
setOpaque(false);
}
#Override public void paintComponent(Graphics g) {
super.paintComponent(g);
screen = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
int gap = 5; int width = 1920;
for (int r = 120; r <= 420; r += gap) {
for (int c = 500; c <= width - 500; c += gap) {
g.setColor(new Color(screen.getRGB(c, r)));
g.fillRect(c, r, gap, gap);
}
}
}
#Override public void run() {
while (true) {
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
A number of things pop out at me...
You seem to be capturing the who screen, but are't taking into account were the window may actually be positioned and what area it might be covering
When you capture the screen, you component is going to be on it...
Now, this is a very simple example. I demonstrates how to convert the area of your panel to the screen coordinates and capture only that area. It does this by first hiding the window and then taking a snap shot of it before re-showing the window and painting the resulting snap-shot...
import com.jhlabs.image.GaussianFilter;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Transparency;
import java.awt.Window;
import java.awt.event.HierarchyBoundsAdapter;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
try {
JPanel outter = new JPanel(new BorderLayout());
outter.setBorder(new EmptyBorder(20, 20, 20, 20));
outter.add(new TestPane());
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(outter);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (AWTException | HeadlessException exp) {
exp.printStackTrace();
}
}
});
}
public class TestPane extends JPanel {
private Robot bot;
private BufferedImage snapShot;
private Point lastSnapShot;
public TestPane() throws AWTException {
bot = new Robot();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public void updateSnapshot() {
Rectangle bounds = getBounds();
Point p = new Point(0, 0);
SwingUtilities.convertPointToScreen(p, this);
bounds.setLocation(p);
if (lastSnapShot == null || !lastSnapShot.equals(p)) {
lastSnapShot = p;
Window window = SwingUtilities.getWindowAncestor(this);
window.addHierarchyListener(new HierarchyListener() {
#Override
public void hierarchyChanged(HierarchyEvent e) {
if (!window.isVisible()) {
e.getComponent().removeHierarchyListener(this);
snapShot = bot.createScreenCapture(bounds);
snapShot = generateBlur(snapShot, 10);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
window.setVisible(true);
}
});
}
}
});
window.setVisible(false);
}
}
public BufferedImage generateBlur(BufferedImage imgSource, int size) {
GaussianFilter filter = new GaussianFilter(size);
int imgWidth = imgSource.getWidth();
int imgHeight = imgSource.getHeight();
BufferedImage imgBlur = createCompatibleImage(imgWidth, imgHeight, Transparency.OPAQUE);
Graphics2D g2 = imgBlur.createGraphics();
g2.drawImage(imgSource, 0, 0, null);
g2.dispose();
imgBlur = filter.filter(imgBlur, null);
return imgBlur;
}
public BufferedImage createCompatibleImage(int width, int height, int transparency) {
GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(width, height, transparency);
image.coerceData(true);
return image;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (snapShot == null) {
updateSnapshot();
}
int x = 0;
int y = 0;
g2d.drawImage(snapShot, 0, 0, this);
g2d.dispose();
}
}
}
This example takes advantage of JH Lab's Filters, cause I'm to lazy to create my own...

Java - can't draw an image from file

I use NetBeans and I wanted to show an image on a jPanel (basically to make it scroll).
I wrote this code
Graphics g=jPanelScrolling.getGraphics();
File fileBackground = new File("background.jpg");
Image background;
try{
background=ImageIO.read(fileBackground);
final int WIDTH=background.getWidth(rootPane);
final int HEIGHT=background.getHeight(rootPane);
g.drawImage(background, WIDTH, HEIGHT, rootPane);
}
catch(IOException e){
background=null;
jPanelScrolling.setBackground(Color.red); //to test if the image has been succesfully uploaded
}
but when I execute it, it shows me only the void jPanel
How can I make it work?
Try,
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageInFrame {
public static void main(String[] args) throws IOException {
String path = "Image1.jpg";
File file = new File(path);
BufferedImage image = ImageIO.read(file);
JLabel label = new JLabel(new ImageIcon(image));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(label);
f.pack();
f.setLocation(200,200);
f.setVisible(true);
}
}
Want to display Image, try something like this:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImagePanel extends JPanel{
private BufferedImage bi;
public ImagePanel() {
try {
bi = ImageIO.read(new File("Your Image Path"));
} catch (IOException ex) {
Logger.getLogger(ImagePanel.class.getName()).log(Level.SEVERE, null, ex);
}
final JPanel panel = new JPanel(){
#Override
protected void paintComponent(Graphics g){
Graphics g2 = g.create();
g2.drawImage(bi, 0, 0, getWidth(), getHeight(), null);
g2.dispose();
}
#Override
public Dimension getPreferredSize(){
return new Dimension(bi.getWidth()/2, bi.getHeight()/2);
//return new Dimension(200, 200);
}
};
add(panel);
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ImagePanel imgPanel=new ImagePanel();
JOptionPane.showMessageDialog(
null, imgPanel, "Image Panel", JOptionPane.PLAIN_MESSAGE);
}
});
}
}
Output

Display Images in JFrame from JComboBox event

I want to achieve following functionality :
Eg :
When user selects "Profile Pic"item from JComboBox releted images from "Profile Pic" folder should be loaded on same frame.
Again when user selects "Product Img" item related images from "Product Img" folder should be loaded replacing previous images.
Following is code snippet , please suggest any changes
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
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.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class NewClass1 {
public static void main(String[] args) {
createAndShowJFrame();
}
public static void createAndShowJFrame() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = createJFrame();
frame.setVisible(true);
}
});
}
private static JFrame createJFrame() {
JFrame frame = new JFrame();
//frame.setResizable(false);//make it un-resizeable
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Test");
ArrayList<BufferedImage> images = null;
try {
images = getImagesArrayList();
} catch (Exception ex) {
ex.printStackTrace();
}
final ImageViewPanel imageViewPanel = new ImageViewPanel(images);
JScrollPane jsp = new JScrollPane(imageViewPanel);
jsp.setPreferredSize(new Dimension(400, 400));
frame.add(jsp);
final javax.swing.JComboBox filter = new javax.swing.JComboBox<>();
filter.addItem("All");
filter.addItem("Profile Pic");
filter.addItem("Company Logo");
filter.addItem("Product Img");
JPanel controlPanel = new JPanel();
JButton addLabelButton = new JButton("Delete Selected Image");
addLabelButton.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
imageViewPanel.removeFocusedImageLabel();
}
});
JLabel label =new JLabel("Filter By :");
filter.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
String cat=(String) filter.getSelectedItem();
createJFrame(cat);
}
});
controlPanel.add(addLabelButton);
controlPanel.add(label);
controlPanel.add(filter);
frame.add(controlPanel, BorderLayout.NORTH);
frame.pack();
return frame;
}
private static ArrayList<BufferedImage> getImagesArrayList(String cat) throws Exception {
System.out.println(cat);
ArrayList<BufferedImage> images = new ArrayList<>();
if(cat.equals("Profile Pic"))
images.add(resize(ImageIO.read(new URL("http://192.168.1.25:8080/pic/ProfilePic/1.jpg")), 100, 100));
else if(cat.equals("Product Img"))
{
images.add(resize(ImageIO.read(new URL("http://192.168.1.25:8080/pic/ProductImg/2.jpg")), 100, 100));
}
return images;
}
private static ArrayList<BufferedImage> getImagesArrayList() throws Exception {
ArrayList<BufferedImage> images = new ArrayList<>();
images.add(resize(ImageIO.read(new URL("http://localhost:8080/pic/All/a.jpg")), 100, 100));
images.add(resize(ImageIO.read(new URL("http://localhost:8080/pic/All/b.jpg")), 100, 100));
return images;
}
public static BufferedImage resize(BufferedImage image, int width, int height) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
return bi;
}
}
I would urge you to have another look at the code I posted (which you seem to be using) Deleting images from JFrame.
However:
In your code I see:
filter.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
String cat=(String) filter.getSelectedItem();
createJFrame(cat);
}
});
I cannot even find the method createJFrame(String cat);?
As far as I see you should be doing this:
filter.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
String cat=(String) filter.getSelectedItem();
ArrayList<BufferedImage> images=getImagesArrayList(cat);//get the new images for the selected item in combo
//refresh the layout by removing old pics and itertating the new array and adding pics to the panel as you iterate
layoutLabels(images);
}
});
....
private JLabel NO_IMAGES=new JLabel("No Images");
private void layoutLabels(ArrayList<BufferedImage> images) {
removeAll();//remove all components from our panel (the panel should only have the images on if not use setActionCommand("Image") on your images/JLabels and than use getComponents of JPanel and iterate through them looking for getActionCommand.equals("Image")
if (images.isEmpty()) {//if the list is empty
add(NO_IMAGES);//add Jlabel to show message of no images
} else {
remove(NO_IMAGES);
for (BufferedImage i : images) {//iterate through ArrayList of images
add(new JLabel(new ImageIcon(i)));//add each to the panel using JLabel as container for image
}
}
revalidate();
repaint();
}

Categories

Resources