Hey all I am wondering if I can fix my animation issue.
Currently it does animate just fine but with one issue - it seems to leave training images behind as it animates.
This is my code I am using:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.io.File;
import java.io.FileInputStream;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.io.*;
#SuppressWarnings("serial")
public class Display extends JFrame {
private static JPanel container = new JPanel();
JLabel insidePIV = new JLabel();
public static void main(String[] args) throws IOException {
Display blah = new Display();
}
public void addListeners() {
final Point offset = new Point();
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(final MouseEvent e) {
offset.setLocation(e.getPoint());
}
});
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(final MouseEvent e) {
setLocation(e.getXOnScreen() - offset.x, e.getYOnScreen() - offset.y);
}
});
}
public Display() throws IOException {
JLabel outsidePIV = new JLabel(new ImageIcon(ImageIO.read(new File("c:/temp/pivReaderAlone.png"))));
MyJLabel antialias = new MyJLabel(
"<html><div style='text-align: center;'>Please insert your card into the reader.</div></html>");
antialias.setFont(new Font("Segoe UI", Font.BOLD, 10));
antialias.setBounds(13, 223, 170, 240);
container.setLayout(new BorderLayout());
container.setBackground(new Color(0, 0, 0, 0));
container.add(antialias, BorderLayout.CENTER);
container.add(outsidePIV, BorderLayout.CENTER);
JButton p = new JButton();
p.setText("Animate");
p.setBounds(30, 100, 120, 20);
outsidePIV.add(p, BorderLayout.CENTER);
p.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
File file = new File("c:/temp/pivbatman.gif");
Image image = Toolkit.getDefaultToolkit()
.createImage(org.apache.commons.io.IOUtils.toByteArray(new FileInputStream(file)));
ImageIcon icon = new ImageIcon(image);
outsidePIV.setDoubleBuffered(true);
outsidePIV.setIcon(icon);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
addListeners();
this.setTitle("PIV");
this.setSize(190, 390);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setAlwaysOnTop(true);
this.setUndecorated(true);
this.setBackground(new Color(0, 0, 0, 0));
this.setContentPane(container);
this.setVisible(true);
this.setResizable(false);
}
public class MyJLabel extends JLabel {
public MyJLabel(String str) {
super(str);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
super.paint(g);
}
}
}
If anyone can help me with this error then please do - been trying to fix it for hours now...
UPDATE
public static void main(String[] args) throws IOException {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
Display blah = new Display();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
Render images on Java Swing is trick, java has a main UI Thread called AWT that is not concurrent. It´s a good practice to use the method invokeLater from SwingUtilities class.
SwingUtilities.invokeLater takes a Runnable and invokes it in the UI thread later.
The syntax is:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//some code that render in the UI here.
}
});
Related
Am trying to change color after drawing the object in window, this is what i came up with, am a beginner so this is messy.
import java.awt.*;
import java.awt.event.*;
import java.awt.event.WindowEvent;
import java.util.Arrays;
import java.util.List;
public class TestGraphic extends Figure {
TestGraphic(){
setSize(600,600);
closeFrame();
}
public static void main(String[] args) {
TestGraphic test = new TestGraphic();
test.setVisible(true);
}
public void paint(Graphics gui) {
drawComponent(gui);
}
public void drawComponent(Graphics gui) {
gui.drawOval(108,110,200,200);
gui.drawOval(160,150,20,20);
gui.drawOval(240,150,20,20);
gui.drawRect(160,220,100,40);
Button btn = new Button("Change color");
btn.setBounds(30,100,80,30);
add(btn);
changeColor(gui,btn);
}
#Override
void draw(Graphics gui) {
// TODO Auto-generated method stub
}
#Override
public boolean contains(int x, int y) {
return false;
}
private void closeFrame(){
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
}
void changeColor(Graphics gui,Button btn) {
List<Color> colorList;
colorList = Arrays.asList(Color.black, Color.blue , Color.cyan, Color.red, Color.green, Color.magenta, Color.orange, Color.yellow);
btn.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
for(int i = 0;i < colorList.size(); i++) {
gui.setColor(colorList.get(i));
}
}
});
}
}
The class Figure is an abstract class that is inheriting from java.awt.Frame
Any remarks about how to make this code cleaner will be appreciated, thanks.
Before you begin on something as complex as custom painting, make sure you have a firm understanding of the basics of the language and the APIs
See Creating a GUI With Swing, Performing Custom Painting and Painting in AWT and Swing for more details.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Color desiredColor = Color.BLACK;
private List<Color> avaliableColors = new ArrayList<>(16);
public TestPane() {
setLayout(new BorderLayout());
avaliableColors.add(Color.BLACK);
avaliableColors.add(Color.BLUE);
avaliableColors.add(Color.CYAN);
avaliableColors.add(Color.DARK_GRAY);
avaliableColors.add(Color.GRAY);
avaliableColors.add(Color.GREEN);
avaliableColors.add(Color.LIGHT_GRAY);
avaliableColors.add(Color.MAGENTA);
avaliableColors.add(Color.ORANGE);
avaliableColors.add(Color.PINK);
avaliableColors.add(Color.RED);
avaliableColors.add(Color.WHITE);
avaliableColors.add(Color.YELLOW);
JButton btn = new JButton("Change color");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Randomise the colors
Collections.shuffle(avaliableColors);
desiredColor = avaliableColors.get(0);
repaint();
}
});
add(btn, BorderLayout.SOUTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(desiredColor);
g2d.drawOval(108, 110, 200, 200);
g2d.drawOval(160, 150, 20, 20);
g2d.drawOval(240, 150, 20, 20);
g2d.drawRect(160, 220, 100, 40);
g2d.dispose();
}
}
}
Since you're just starting out, I might suggest getting started with JavaFX instead
AWT
!! Warning !!
No one uses AWT anymore and you're not likely to get much in the way of support for it here. This is a "basic" concept converted from the previous example, beware, AWT isn't double buffered by default
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Frame frame = new Frame();
frame.add(new TestCanvas());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestCanvas extends Container {
private Color desiredColor = Color.BLACK;
private List<Color> avaliableColors = new ArrayList<>(16);
public TestCanvas() {
setLayout(new BorderLayout());
avaliableColors.add(Color.BLACK);
avaliableColors.add(Color.BLUE);
avaliableColors.add(Color.CYAN);
avaliableColors.add(Color.DARK_GRAY);
avaliableColors.add(Color.GRAY);
avaliableColors.add(Color.GREEN);
avaliableColors.add(Color.LIGHT_GRAY);
avaliableColors.add(Color.MAGENTA);
avaliableColors.add(Color.ORANGE);
avaliableColors.add(Color.PINK);
avaliableColors.add(Color.RED);
avaliableColors.add(Color.WHITE);
avaliableColors.add(Color.YELLOW);
JButton btn = new JButton("Change color");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Randomise the colors
Collections.shuffle(avaliableColors);
desiredColor = avaliableColors.get(0);
repaint();
}
});
add(btn, BorderLayout.SOUTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(desiredColor);
g2d.drawOval(108, 110, 200, 200);
g2d.drawOval(160, 150, 20, 20);
g2d.drawOval(240, 150, 20, 20);
g2d.drawRect(160, 220, 100, 40);
g2d.dispose();
}
}
}
This question already has answers here:
Inserting an image under a JTextArea
(2 answers)
Closed 8 years ago.
I want to set background in JTextArea (having transparency), but I don't have any idea. Maybe it's not very important, but I just want have characteristically program. Please help.
This part of code, I create JTextArea.
notatnik_k = new JTextArea();
JScrollPane scrollPane2 = new JScrollPane(notatnik_k);
scrollPane2.setBounds(20,30, 263,200);
notatnik_k.setEditable(false);
add(scrollPane2);
This photo showing my problem:
Is there a simply way, to do it?
You will need to extend your JTextArea class and create a setBackground(Image image) method. This method would set a field to the image you want to use and then invoke the the repaint method (this.repaint()).
You should then override the paintComponent(Graphics) method to paint the component with the image you set using setBackground(Image image).
I found here on the site this sample of code, and I did a little change but I have one error and don't know why it's incorrect? It's shows error: "The method setBackgroundImage(Image) is undefined for the type JTextArea"
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class BackgroundDemo {
public JTextArea notatnik;
private static void createAndShowUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
final JFrame frame = new JFrame("BackgroundDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel buttonsPanel = new JPanel();
final JTextArea notatnik = new JTextArea();
JScrollPane scrollPane1 = new JScrollPane(notatnik);
scrollPane1.setBounds(20,270, 380,110);
JButton loadButton = new JButton("Set background");
buttonsPanel.add(loadButton);
loadButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser(System.getProperty("user.home"));
int returnVal = fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
Image image = ImageIO.read(fc.getSelectedFile());
if (image != null)
notatnik.setBackgroundImage(image);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
JPanel content = new JPanel(new BorderLayout());
content.add(buttonsPanel, BorderLayout.SOUTH);
frame.add(scrollPane1);
frame.add(content);
frame.setSize(new Dimension(800, 500));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
static class MyTextArea extends JTextArea {
private Image backgroundImage;
public MyTextArea() {
super();
setOpaque(false);
}
public void setBackgroundImage(Image image) {
this.backgroundImage = image;
this.repaint();
}
#Override
protected void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
if (backgroundImage != null) {
g.drawImage(backgroundImage, 0, 0, this);
}
super.paintComponent(g);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
I have a problem with the code that I wrote when I run it on Ubuntu. I want to create a transparent JFrame and add an image as a border. When I run the program on Windows is working properly, but when I run it on ubuntu not only the JFrame but also the image is transparent.
I'd like the program to work in both os. I tried with this code setOpacity(0.0f); too. But the outcame is the same.
Help me please T_T
Sorry but I don't have enough reputation to post images so I put them as links...
This is what i see on Ubuntu: http://oi57.tinypic.com/wgymag.jpg
and this is on Windows:http://oi60.tinypic.com/5o5if4.jpg
and this is the link to the frameImage: oi58.tinypic.com/2j2xrwy.jpg
Here are the two classes that I used:
MainClass:
import com.sun.awt.AWTUtilities;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class Window extends JFrame {
private final int width, height;
private ContainerPanel container;
public Window() {
this.width = 1024;
this.height = 688;
this.setSize(width, height);
this.setMaximumSize(new Dimension(width, height));
this.setMinimumSize(new Dimension(width, height));
this.setResizable(false);
this.setUndecorated(true);
this.setBackground(new Color(0, 0, 0, 0));
container = new ContainerPanel(Window.this, 1024, 688);
this.setContentPane(container);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
try {
} catch (Exception e1) {
System.exit(0);
e1.printStackTrace();
}
}
});
this.setVisible(true);
this.pack();
}
public static void main(String[] args) {
System.out.println("TRANSLUCENT supported: " + AWTUtilities.isTranslucencySupported(AWTUtilities.Translucency.TRANSLUCENT));
System.out.println("PERPIXEL_TRANSPARENT supported: " + AWTUtilities.isTranslucencySupported(AWTUtilities.Translucency.PERPIXEL_TRANSPARENT));
System.out.println("PERPIXEL_TRANSLUCENT supported: " + AWTUtilities.isTranslucencySupported(AWTUtilities.Translucency.PERPIXEL_TRANSLUCENT));
new Window();
}
}
and this is the class with the background image:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
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.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ContainerPanel extends JPanel {
private final Window window;
private JLabel label;
private Point mouseDownCompCoords, currentLocationOnScreen;
private final int windowWidth, windowHeight;
private int closeButtonPosX, closeButtonPosY;
private BufferedImage frameImg;
public ContainerPanel(Window window, int windowWidth, int windowHeight) {
this.window = window;
this.windowWidth = windowWidth;
this.windowHeight = windowHeight;
this.closeButtonPosX = 900;
this.closeButtonPosY = 19;
this.setLayout(null);
this.setOpaque(false);
this.setSize(this.windowWidth, this.windowHeight);
this.setMaximumSize(new Dimension(this.windowWidth, this.windowHeight));
this.setMinimumSize(new Dimension(this.windowWidth, this.windowHeight));
crateLabel();
try {
createButton();
frameImg = ImageIO.read(new File("Images/Frame/frame.png"));
} catch (IOException ex) {
Logger.getLogger(ContainerPanel.class.getName()).log(Level.SEVERE, null, ex);
}
this.setVisible(true);
}
private void crateLabel() {
label = new JLabel();
final int labelHeight = 45;
label.setSize(windowWidth, labelHeight);
label.setMaximumSize(new Dimension(windowWidth, labelHeight));
label.setMinimumSize(new Dimension(windowWidth, labelHeight));
label.setLocation(0, 0);
label.setOpaque(false);
label.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mouseDownCompCoords = e.getPoint();
}
});
label.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
currentLocationOnScreen = e.getLocationOnScreen();
ContainerPanel.this.window.setLocation(currentLocationOnScreen.x - mouseDownCompCoords.x, currentLocationOnScreen.y - mouseDownCompCoords.y);
}
#Override
public void mouseMoved(MouseEvent e) {
//do nothing
}
});
label.setVisible(true);
this.add(label);
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g2d);
g2d.drawImage(frameImg, 0, 0, windowWidth, windowHeight, null);
}
private void createButton() {
JButton close = new JButton("close");
close.setLocation(this.closeButtonPosX , this.closeButtonPosY);
close.setSize(100, 30);
close.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
System.exit(0);
}
});
label.add(close);
}
}
you can check this -> https://today.java.net/pub/a/today/2008/03/18/translucent-and-shaped-swing-windows.html by Kirill Grouchnikov.
I have created shaped JDialog by adding transparency effect by
setBackground(new Color(0, 0, 0, 0); but it also adding drag listener to the dialog internally, problem is, when we drag by any other component in the dialog such as JTextfield, JList etc,. still the complete window is able to drag. so need to avoid adding internal drag listener to the jdialog. please anybody help me regarding this, here is my code.
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class MyWindow extends JDialog {
private static final long serialVersionUID = 1L;
public MyWindow() {
JTextField text = new JTextField();
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(new File("background.png"));
} catch (IOException e) {
}
JLabel label = new JLabel(new ImageIcon(myPicture));
setUndecorated(true);
setResizable(false);
setBackground(new Color(0, 0, 0, 0)); // creating issue
setSize(243, 474);
text.setBounds(18, 64, 212, 368);
add(text);
add(label);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyWindow win = new MyWindow();
win.setVisible(true);
}
});
}
}
Thanks in advance,
Regards,
Bharath SR
Not sure if I fully understand your requirements or even your problem, but it sounds like you want a draggable dialog with no frame, just a background image and a component, and you don't want the components to trigger the drag event.
Give this a try. Hopefully it's what you're looking for. Feel free to ask questions.
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class DragDialog extends JDialog {
private int pointX;
private int pointY;
public DragDialog() {
JLabel backgroundLabel = createBackgroundLabel();
JTextField textField = createTextField();
setContentPane(backgroundLabel);
add(textField);
setUndecorated(true);
setBackground(new Color(0, 0, 0, 0));
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private JTextField createTextField() {
final JTextField field = new JTextField(20);
field.setText("Type \"exit\" to terminate.");
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String text = field.getText();
if ("exit".equalsIgnoreCase(text)) {
System.exit(0);
}
}
});
return field;
}
private JLabel createBackgroundLabel() {
Image image = null;
try {
image = ImageIO.read(new URL("http://satyajit.ranjeev.in/images/icons/stackoverflow.png"));
} catch (IOException ex) {
Logger.getLogger(DragDialog.class.getName()).log(Level.SEVERE, null, ex);
}
JLabel label = new JLabel(new ImageIcon(image));
label.setLayout(new GridBagLayout());
label.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
DragDialog.this.setLocation(DragDialog.this.getLocation().x + e.getX() - pointX,
DragDialog.this.getLocation().y + e.getY() - pointY);
}
});
label.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
pointX = e.getX();
pointY = e.getY();
}
});
return label;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DragDialog();
}
});
}
}
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();
}