shaped jdialog for transparency effect causing dragging issue - java

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();
}
});
}
}

Related

Java Swing applicaion gif animation leaving a trail

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.
}
});

JAVA: Screenshot after JFrame change just black

I've written a program which makes a screenshot of JFrame by clicking on JMenuItem. If I only run the .java file in Eclipse, everything works and the screenshot shows the JFrame perfectly. But if I open the JFrame as a link from another JFrame, the screenshot is black instead of showing the JFrame. Here's my code:
JFrame1.java:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class JFrame1 extends JFrame {
static JFrame1 frame1 = new JFrame1();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame1.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void CloseFrame(){
super.dispose();
}
public JFrame1() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(50, 50, 800, 740);
JButton ok = new JButton("OK");
getContentPane().add(ok);
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CloseFrame();
JFrame2 frame2 = new JFrame2();
frame2.setVisible(true);
}
});
}
}
With a button (ok) I can go to JFrame2.java.
JFrame2.java:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class JFrame2 extends JFrame {
static JFrame2 frame2 = new JFrame2();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame2.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem screen = new JMenuItem("Screenshot");
screen.addActionListener(new AbstractAction() {
#Override
public void actionPerformed (ActionEvent e)
{
Dimension size = frame2.getSize ();
BufferedImage img = new BufferedImage (size.width, size.height, BufferedImage.TYPE_3BYTE_BGR);
Graphics g = img.getGraphics ();
frame2.printAll (g);
g.dispose ();
try
{
ImageIO.write (img, "png", new File ("screenshot.png"));
}
catch (IOException ex)
{
ex.printStackTrace ();
}
}
});
file.add(screen);
menubar.add(file);
setJMenuBar(menubar);
}
public JFrame2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(50, 50, 800, 740);
createMenuBar();
}
}
If I click now on "Screenshot", it is just black.
And if I run only JFrame2.java without running JFrame1.java before, the real image is saved.
Why does the screenshot is black after going from one JFrame1 to JFrame2?
You're painting from the wrong frame...
In your first frame, you are doing this...
JFrame2 frame2 = new JFrame2();
frame2.setVisible(true);
Looks pretty harmless, but, in JFrame2 you are doing this...
public class JFrame2 extends JFrame {
static JFrame2 frame2 = new JFrame2();
And...
public void actionPerformed (ActionEvent e)
{
Dimension size = frame2.getSize ();
BufferedImage img = new BufferedImage (size.width, size.height, BufferedImage.TYPE_3BYTE_BGR);
Graphics g = img.getGraphics ();
frame2.printAll (g);
g.dispose ();
try
{
ImageIO.write (img, "png", new File ("screenshot.png"));
}
catch (IOException ex)
{
ex.printStackTrace ();
}
}
But, frame2 (inside JFrame2) is not visible on the screen.
This is why static is evil and should be avoid. This is also why you should not extend directly from something like JFrame. You can to easily get yourself into a knot of not knowing what is actually on the screen and what you are referencing...
For example...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
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.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class JavaApplication254 {
public static void main(String[] args) {
new JavaApplication254();
}
public JavaApplication254() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JButton btn = new JButton("Click me away...");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TestPane testPane = new TestPane();
SnapshotAction snapshotAction = new SnapshotAction(testPane);
JMenuBar mb = new JMenuBar();
JMenu mnuFile = new JMenu("File");
mnuFile.add(snapshotAction);
mb.add(mnuFile);
JFrame frame = new JFrame("More Testing");
frame.setJMenuBar(mb);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(testPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(btn);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new EmptyBorder(20, 20, 20, 20));
JLabel label = new JLabel("I be a bananan");
label.setOpaque(true);
label.setBackground(Color.YELLOW);
label.setForeground(Color.RED);
label.setBorder(
new CompoundBorder(
new LineBorder(Color.RED),
new EmptyBorder(20, 20, 20, 20)));
setLayout(new GridBagLayout());
add(label);
}
}
public class SnapshotAction extends AbstractAction {
private JComponent parent;
public SnapshotAction(JComponent parent) {
this.parent = parent;
putValue(NAME, "Take Snapshot...");
}
#Override
public void actionPerformed(ActionEvent e) {
if (parent.isDisplayable()) {
BufferedImage img = new BufferedImage(parent.getWidth(), parent.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
parent.printAll(g2d);
g2d.dispose();
try {
ImageIO.write(img, "png", new File("Snapshot.png"));
Toolkit.getDefaultToolkit().beep();
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(parent, "Failed to generate snapshot: " + ex.getMessage());
}
}
}
}
}
Which will output...

Is it possible to set a background image inside JTextArea (including JScrollPane) not all the frame window? [duplicate]

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();
}
});
}
}

java jframe transparent background on ubuntu

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.

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