I try and search I cannot find the answer from anywhere.heres the code I just want to include TextField in a pop-up menu to access String from that text field.
package systemtray;
import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
public class Main {
public static void main(String[] args) throws AWTException {
PopupMenu popMenu= new PopupMenu();
MenuItem item1 = new MenuItem("Exit");
popMenu.add(item1);
Image img = Toolkit.getDefaultToolkit().getImage("C:/java/cup.jpg");
TrayIcon trayIcon = new TrayIcon(img, "Application Name", popMenu);
SystemTray.getSystemTray().add(trayIcon);
}
}
Menu containers generally aren't great for displaying display input components like text fields, beside, PopupMenu is an AWT based component, which just complicates the issue.
A better solution is to simply "fake it", but then question becomes "how".
One approach might be to attach a MouseListener to the TrayIcon and on the mouseClicked event, show an undecorated frame.
The trick here is trying to figure out "where" to show the popup, as you can't (easily) get the screen coordinates of the TrayIcon
import java.awt.AWTException;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class TestTaskIcon {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Image img = null;
try {
img = ImageIO.read(TestTaskIcon.class.getResource("TaskIcon.png"));
} catch (IOException e) {
e.printStackTrace();
}
TrayIcon ti = new TrayIcon(img, "Tooltip");
ti.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
Rectangle bounds = getSafeScreenBounds(e.getPoint());
JFrame popup = new JFrame();
popup.setUndecorated(true);
popup.setAlwaysOnTop(true);
popup.setLayout(new FlowLayout());
popup.add(new JLabel("Password: "));
popup.add(new JTextField(20));
popup.pack();
popup.addWindowFocusListener(new WindowFocusListener() {
#Override
public void windowGainedFocus(WindowEvent e) {
}
#Override
public void windowLostFocus(WindowEvent e) {
popup.dispose();
}
});
Point point = e.getPoint();
int x = point.x;
int y = point.y;
if (y < bounds.y) {
y = bounds.y;
} else if (y > bounds.y + bounds.height) {
y = bounds.y + bounds.height;
}
if (x < bounds.x) {
x = bounds.x;
} else if (x > bounds.x + bounds.width) {
x = bounds.x + bounds.width;
}
if (x + popup.getPreferredSize().width > bounds.x + bounds.width) {
x = (bounds.x + bounds.width) - popup.getPreferredSize().width;
}
if (y + popup.getPreferredSize().height > bounds.y + bounds.height) {
y = (bounds.y + bounds.height) - popup.getPreferredSize().height;
}
popup.setLocation(x, y);
popup.setVisible(true);
}
});
try {
SystemTray.getSystemTray().add(ti);
} catch (AWTException ex) {
Logger.getLogger(TestTaskIcon.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public static Rectangle getSafeScreenBounds(Point pos) {
Rectangle bounds = getScreenBoundsAt(pos);
Insets insets = getScreenInsetsAt(pos);
bounds.x += insets.left;
bounds.y += insets.top;
bounds.width -= (insets.left + insets.right);
bounds.height -= (insets.top + insets.bottom);
return bounds;
}
public static Insets getScreenInsetsAt(Point pos) {
GraphicsDevice gd = getGraphicsDeviceAt(pos);
Insets insets = null;
if (gd != null) {
insets = Toolkit.getDefaultToolkit().getScreenInsets(gd.getDefaultConfiguration());
}
return insets;
}
public static Rectangle getScreenBoundsAt(Point pos) {
GraphicsDevice gd = getGraphicsDeviceAt(pos);
Rectangle bounds = null;
if (gd != null) {
bounds = gd.getDefaultConfiguration().getBounds();
}
return bounds;
}
public static GraphicsDevice getGraphicsDeviceAt(Point pos) {
GraphicsDevice device = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice lstGDs[] = ge.getScreenDevices();
ArrayList<GraphicsDevice> lstDevices = new ArrayList<GraphicsDevice>(lstGDs.length);
for (GraphicsDevice gd : lstGDs) {
GraphicsConfiguration gc = gd.getDefaultConfiguration();
Rectangle screenBounds = gc.getBounds();
if (screenBounds.contains(pos)) {
lstDevices.add(gd);
}
}
if (lstDevices.size() > 0) {
device = lstDevices.get(0);
} else {
device = ge.getDefaultScreenDevice();
}
return device;
}
}
Related
Below is a minimal reproducible code example where you can use mouse wheel to zoom in and out relative to the position of the mouse. The JScrollPane also auto-adjusts its size as you zoom in and out.
package testpane;
import java.awt.event.MouseAdapter;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;
public class TestPane
{
public static Drawing d;
public static double zoomFactor = 1;
public static void main(String[] args)
{
JFrame f = new JFrame("Tree Diagram");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new TestPane().makeDiagram());
f.setSize(1600, 800);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public JComponent makeDiagram()
{
d = new Drawing();
MouseAdapter mouseAdapter = new TestPaneMouseListener();
d.addMouseListener(mouseAdapter);
d.addMouseMotionListener(mouseAdapter);
d.addMouseWheelListener(mouseAdapter);
return new JScrollPane(d);
}
}
package testpane;
import java.awt.Component;
import java.awt.Container;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import javax.swing.JComponent;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import static testpane.TestPane.d;
import static testpane.TestPane.zoomFactor;
public class TestPaneMouseListener extends MouseAdapter
{
private final Point origin = new Point();
#Override
public void mouseDragged(MouseEvent e)
{
Component c = e.getComponent();
Container p = SwingUtilities.getUnwrappedParent(c);
if (p instanceof JViewport)
{
JViewport viewport = (JViewport) p;
Point cp = SwingUtilities.convertPoint(c, e.getPoint(), viewport);
Point vp = viewport.getViewPosition();
vp.translate(origin.x - cp.x, origin.y - cp.y);
((JComponent) c).scrollRectToVisible(new Rectangle(vp, viewport.getSize()));
origin.setLocation(cp);
}
}
#Override
public void mousePressed(MouseEvent e)
{
Component c = e.getComponent();
Container p = SwingUtilities.getUnwrappedParent(c);
if(p instanceof JViewport)
{
JViewport viewport = (JViewport) p;
Point cp = SwingUtilities.convertPoint(c, e.getPoint(), viewport);
origin.setLocation(cp);
}
}
#Override
public void mouseWheelMoved(MouseWheelEvent e)
{
if(e.getWheelRotation()<0)
{
zoomFactor*=1.05;
d.setZoomFactor(1.05);
}
if(e.getWheelRotation()>0)
{
zoomFactor/=1.05;
d.setZoomFactor(1/1.05);
}
}
}
package testpane;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.MouseInfo;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import javax.swing.JPanel;
public class Drawing extends JPanel
{
private final AffineTransform zoomTransform = new AffineTransform();
private final Rectangle rect = new Rectangle(1600, 800);
private double xOffset = 0;
private double yOffset = 0;
private double prevZoomFactor = 1;
public Drawing()
{
Font currentFont = getFont();
Font newFont = currentFont.deriveFont(currentFont.getSize() * 15F);
setFont(newFont);
setBackground(Color.WHITE);
}
public void setZoomFactor(double zoomFactor)
{
zoomTransform.scale(zoomFactor, zoomFactor);
revalidate();
repaint();
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
AffineTransform scrollTransform = g2d.getTransform();
double xRel = MouseInfo.getPointerInfo().getLocation().getX() - getLocationOnScreen().getX();
double yRel = MouseInfo.getPointerInfo().getLocation().getY() - getLocationOnScreen().getY();
double zoomDiv = TestPane.zoomFactor / prevZoomFactor;
xOffset = (zoomDiv) * (xOffset) + (1 - zoomDiv) * xRel;
yOffset = (zoomDiv) * (yOffset) + (1 - zoomDiv) * yRel;
prevZoomFactor = TestPane.zoomFactor;
scrollTransform.translate(xOffset, yOffset);
scrollTransform.concatenate(zoomTransform);
g2d.setTransform(scrollTransform);
g2d.drawString("Example", 400, 400);
g2d.dispose();
}
#Override
public Dimension getPreferredSize()
{
Rectangle r = zoomTransform.createTransformedShape(rect).getBounds();
return new Dimension(r.width, r.height);
}
}
Here is my problem: the zooming works just fine, but when I zoom too close, part of the "Example" written on the JScrollPane goes out of bounds. I believe that the problem comes from the translation I've made inside of the "Drawing" java class in the "paintComponent" method. While this translation does help me zoom in properly, it also causes my text to go out of bounds if I zoom too close. Is there any way for me to fix this?
Could get a similar effect to this
https://www.youtube.com/watch?v=ubFq-wV3Eic
in Java? The goal is to have it as fast as possible - my mission is to find out if it's possible to burn pixels in my lcd this way. It may sound ridiculous, but I still need to find out.
The links Spektre shared say that 16 levels of gray are enough, so you can generate a random value in the [0, 15] range, and multiply that to get a pixel value.
Since you’re concerned about speed, you can directly manipulate the DataBuffer of a BufferedImage to update the pixels. TYPE_USHORT_GRAY guarantees an image with a ComponentColorModel and ComponentSampleModel:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.GraphicsDevice;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferUShort;
import java.awt.image.ComponentSampleModel;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.util.Random;
public class NoiseGenerator
extends JPanel {
private static final long serialVersionUID = 1;
private static final int FPS = Math.max(1, Integer.getInteger("fps", 30));
private final int width;
private final int height;
private final BufferedImage image;
private final Random random = new Random();
public NoiseGenerator(GraphicsDevice screen) {
this(screen.getDefaultConfiguration().getBounds().getSize());
}
public NoiseGenerator(Dimension size) {
this(size.width, size.height);
}
public NoiseGenerator(int width,
int height) {
this.width = width;
this.height = height;
this.image = new BufferedImage(width, height,
BufferedImage.TYPE_USHORT_GRAY);
setFocusable(true);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
private void generateFrame() {
DataBufferUShort buffer = (DataBufferUShort)
image.getRaster().getDataBuffer();
short[] data = buffer.getData();
ComponentSampleModel sampleModel = (ComponentSampleModel)
image.getSampleModel();
int stride = sampleModel.getScanlineStride();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
data[y * stride + x] = (short) (random.nextInt(16) * 4096);
}
}
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
public void start() {
Timer timer = new Timer(1000 / FPS, e -> generateFrame());
timer.start();
}
public static void main(String[] args) {
int screenNumber = args.length > 0 ? Integer.parseInt(args[0]) : -1;
EventQueue.invokeLater(() -> {
GraphicsEnvironment env =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice screen = env.getDefaultScreenDevice();
if (screenNumber >= 0) {
GraphicsDevice[] screens = env.getScreenDevices();
if (screenNumber >= screens.length) {
System.err.println("Cannot detect screen " + screenNumber);
System.exit(2);
}
screen = screens[screenNumber];
}
NoiseGenerator generator = new NoiseGenerator(screen);
generator.start();
JFrame window = new JFrame("Noise Generator",
screen.getDefaultConfiguration());
window.setUndecorated(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
generator.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent event) {
System.exit(0);
}
});
generator.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent event) {
System.exit(0);
}
#Override
public void keyPressed(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.VK_ESCAPE) {
System.exit(0);
}
}
});
window.getContentPane().add(generator);
screen.setFullScreenWindow(window);
});
}
}
I'm trying to add scrollbar to image in java swing, there is also function to read RGB from image. There are 2 problems:
Scrollbar doesn't work - i want to put image to container...some kind of ''frame'' with constant size and zoom image. After zoom - picture is larger - there are also scrollbars...but it's not working .
There is function to read RGB color pixel in from mouse position , but when i add scrollbar program think that image is in (0,0) position , and there colors are reading , not from real image in frame.
Code:
Window.class:
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
public class Window extends JFrame implements ActionListener{
JButton Bzoom ;
ButtonGroup BGzoom, BGMzoom;
JRadioButton RB1,RB2,RB4,RB8,RB16;
JRadioButton RBM1, RBM2, RBM4, RBM8, RBM16;
MyImage myImage;
public Window()
{
super("Image_Processing");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800 , 600);
setLayout(new FlowLayout());
setVisible(true);
setLocation(50,50);
setResizable(true);
// RadioButtons for X 1,2,4,8,16
BGzoom = new ButtonGroup();
RB1 = new JRadioButton("1x",true);
RB2 = new JRadioButton("2X",false);
RB4 = new JRadioButton("4X",false);
RB8 = new JRadioButton("8X",false);
RB16 = new JRadioButton("16X",false);
BGzoom.add(RB1);
BGzoom.add(RB2);
BGzoom.add(RB4);
BGzoom.add(RB8);
BGzoom.add(RB16);
add(RB1);
add(RB2);
add(RB4);
add(RB8);
add(RB16);
RB1.addActionListener(this);
RB2.addActionListener(this);
RB4.addActionListener(this);
RB8.addActionListener(this);
RB16.addActionListener(this);
// RadioButtons for MINUS X 1,2,4,8,16
BGMzoom = new ButtonGroup();
RBM1 = new JRadioButton("-1x",true);
RBM2 = new JRadioButton("-2X",false);
RBM4 = new JRadioButton("-4X",false);
RBM8 = new JRadioButton("-8X",false);
RBM16 = new JRadioButton("-16X",false);
BGzoom.add(RBM1);
BGzoom.add(RBM2);
BGzoom.add(RBM4);
BGzoom.add(RBM8);
BGzoom.add(RBM16);
add(RBM1);
add(RBM2);
add(RBM4);
add(RBM8);
add(RBM16);
RBM1.addActionListener(this);
RBM2.addActionListener(this);
RBM4.addActionListener(this);
RBM8.addActionListener(this);
RBM16.addActionListener(this);
Bzoom = new JButton("WYKONAJ");
add(Bzoom);
Bzoom.addActionListener(this);
// RGB for mouse click
getContentPane().addMouseMotionListener(new MouseMotionListener()
{
public void mouseMoved(MouseEvent e)
{
int x = (int) ((getContentPane().getMousePosition().x - (myImage.getBounds().x + 1))/myImage.getZoom());
int y = (int) ((getContentPane().getMousePosition().y - (myImage.getBounds().y + 1))/myImage.getZoom());
int color = myImage.getColorAt(x, y);
Color thisColor = new Color(color);
System.out.println("R: " + thisColor.getRed() + " G: " + thisColor.getGreen() + " B: " + thisColor.getBlue());
}
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
});
}
public void LoadImage(String filename)
{
myImage = new MyImage(filename);
JScrollPane scroll = new JScrollPane(myImage,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
add(scroll);
pack();
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == Bzoom)
{
if(RB1.isSelected())
{
myImage.zoomIn(1);
repaint();
}
else if(RB2.isSelected())
{
myImage.zoomIn(2);
repaint();
}
else if(RB4.isSelected())
{
myImage.zoomIn(4);
repaint();
}
else if(RB8.isSelected())
{
myImage.zoomIn(8);
repaint();
}
else if(RB16.isSelected())
{
myImage.zoomIn(16);
repaint();
}
else if(RBM1.isSelected())
{
myImage.zoomOut(1);
repaint();
}
else if(RBM2.isSelected())
{
myImage.zoomOut(2);
repaint();
}
else if(RBM4.isSelected())
{
myImage.zoomOut(4);
repaint();
}
else if(RBM8.isSelected())
{
myImage.zoomOut(8);
repaint();
}
else if(RBM16.isSelected())
{
myImage.zoomOut(16);
repaint();
}
}
}
}
MyImage.class:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class MyImage extends JPanel{
protected BufferedImage image;
private float zoom = (float) 1.0;
public MyImage() {}
public MyImage(String filename)
{
super();
File imageFile = new File(filename);
try
{
image = ImageIO.read(imageFile);
}
catch (IOException e)
{
System.err.println("Blad odczytu obrazka");
e.printStackTrace();
}
Dimension dimension = new Dimension(image.getWidth(), image.getHeight()); //wymiar
setPreferredSize(dimension);
}
public Dimension getPreferredSize()
{
int w = (int)(zoom * (image.getWidth()+20));
int h = (int)(zoom * (image.getHeight()+20));
return new Dimension(w, h);
}
#Override
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.scale(zoom, zoom);
g2d.drawImage(image, 0 , 0, this);
}
public float getZoom()
{
return zoom;
}
public int getColorAt(int x, int y)
{
return image.getRGB(x, y);
}
public void zoomIn(int scale)
{
zoom = zoom*scale;
}
public void zoomOut(int scale)
{
zoom = zoom/scale;
}
}
Main.class:
import java.awt.BorderLayout;
import java.awt.Container;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
//import org.opencv.core.Core;
//import org.opencv.core.CvType;
//import org.opencv.core.Mat;
public class Main {
public static void main( String[] args ) throws IOException
{
Window m = new Window();
m.LoadImage("file.jpg");
}
}
Thanks for all help , and sorry for my English ;)
Scrollbar doesn't work - i want to put image to container...some kind of ''frame'' with constant size and zoom image. After zoom - picture is larger - there are also scrollbars...but it's not working .
You need to inform the container that there has been change to the state of the component which might affect it's size...
public void zoomIn(int scale) {
zoom = zoom * scale;
revalidate();
repaint();
}
public void zoomOut(int scale) {
zoom = zoom / scale;
revalidate();
repaint();
}
The revalidate call will cause the container hierarchy to revalidate the layout information and update the layout
There is function to read RGB color pixel in from mouse position , but when i add scrollbar program think that image is in (0,0) position , and there colors are reading , not from real image in frame.
Add the MouseListener to the MyImage pane. MouseEvents are contextual to the component to which they are generated from
You will need a way to scale the mouse coordinates back to the "unscaled" version of the image so you can get the pixel represented by the unscaled image
I'm trying to draw Images with Graphics2D on JFrame.
But this code only displays blank background.
How to do that?
Java Version: SE-1.6
IDE: Eclipse
My code looks like this:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import java.awt.geom.Line2D;
import java.util.TimerTask;
import javax.swing.JFrame;
public class GraphicTest extends JFrame{
public static void main(String[] args) {
GraphicTest gt = new GraphicTest();
gt.start();
}
JFrame frame;
BufferStrategy strategy;
GraphicTest(){
int width = 320;
int height = 240;
this.frame = new JFrame("test");
this.frame.setSize(width, height);
this.frame.setLocationRelativeTo(null);
this.frame.setLocation(576, 336);
this.frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
this.frame.setUndecorated(true);
this.frame.setBackground(new Color(0, 0, 0, 50));
this.frame.setVisible(true);
this.frame.setIgnoreRepaint(true);
this.frame.createBufferStrategy(2);
this.strategy = this.frame.getBufferStrategy();
}
public void onExit(){
System.exit(0);
}
void start(){
java.util.Timer timer = new java.util.Timer();
timer.schedule(new RenderTask(), 0, 16);
}
class RenderTask extends TimerTask{
int count = 0;
#Override
public void run() {
GraphicTest.this.render();
}
}
void render() {
// Some moving images
Graphics2D g2 = (Graphics2D)this.strategy.getDrawGraphics();
g2.setStroke(new BasicStroke(5.0f));
Line2D line = new Line2D.Double(20, 40, 120, 140);
g2.draw(line);
this.strategy.show();
}
}
Thank you for any help you can provide.
BufferStrategy is normally associated with heavy weight components, which don't have any concept of transparency.
Transparent and translucent (per alpha pixeling) is not "officially" supported under Java 6
Making a window translucent effects anything else painted to it...this very annoying, regardless if you are using Java 6 or 7
The secret is to make the Window transparent to begin with, then overlay a transparent component that has a special "translucent" paint effect.
Under Java 6 (update 10 I think), there became available a private API called AWTUtilities which provide the ability to make a window transparent or translucent, the following example is based on that API.
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.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TransparentWindowAnimation {
public static void main(String[] args) {
new TransparentWindowAnimation();
}
public TransparentWindowAnimation() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
if (supportsPerAlphaPixel()) {
try {
JFrame frame = new JFrame("Testing");
frame.setUndecorated(true);
setOpaque(frame, false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new PaintPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (Exception exp) {
exp.printStackTrace();
}
} else {
System.err.println("Per pixel alphering is not supported");
}
}
});
}
public static boolean supportsPerAlphaPixel() {
boolean support = false;
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
support = true;
} catch (Exception exp) {
}
return support;
}
public static void setOpaque(Window window, boolean opaque) throws Exception {
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
if (awtUtilsClass != null) {
Method method = awtUtilsClass.getMethod("setWindowOpaque", Window.class, boolean.class);
method.invoke(null, window, opaque);
}
} catch (Exception exp) {
throw new Exception("Window opacity not supported");
}
}
public class PaintPane extends JPanel {
private BufferedImage img;
private int xPos, yPos = 100;
private int xDelta = 0;
private int yDelta = 0;
public PaintPane() {
while (xDelta == 0) {
xDelta = (int)((Math.random() * 8)) - 4;
}
while (yDelta == 0) {
yDelta = (int)((Math.random() * 8)) - 4;
}
setOpaque(false);
try {
img = ImageIO.read(new File("AngryBird.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
xPos += xDelta;
yPos += yDelta;
if (xPos - (img.getWidth() / 2) <= 0) {
xPos = img.getWidth() / 2;
xDelta *= -1;
}
if (xPos + (img.getWidth() / 2) >= getWidth()) {
xPos = getWidth() - (img.getWidth() / 2);
xDelta *= -1;
}
if (yPos - (img.getHeight() / 2) <= 0) {
yPos = img.getHeight() / 2;
yDelta *= -1;
}
if (yPos + (img.getHeight() / 2) >= getHeight()) {
yPos = getHeight() - (img.getHeight() / 2);
yDelta *= -1;
}
repaint();
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(new Color(128, 128, 128, 128));
g2d.fillRect(0, 0, getWidth(), getHeight());
int x = xPos - (img.getWidth() / 2);
int y = yPos - (img.getHeight()/ 2);
g2d.drawImage(img, x, y, this);
g2d.dispose();
}
}
}
Another way can be seen here. It can be accomplished by
frame.setBackground(new Color(0, 0, 0, 0));
....
setOpaque(false); //for the JPanel being painted on.
I have an image inside the JOptionPane and I want it to disappear whenever I point the mouse cursor and click into it.
Is there something to do about the position?
Thanks...
Here's the code :
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
class ImageBlinking extends JComponent
{
BufferedImage image;
boolean showImage;
int x = -1;
int y = -1;
Random r;
ImageBlinking()
{
try
{
File sourceimage = new File("ball.gif");
image = ImageIO.read(sourceimage);
}
catch (IOException e)
{
e.printStackTrace();
}
r = new Random();
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (image != null)
{
if (!showImage)
{
int w = image.getWidth();
int h = image.getHeight();
int rx = getWidth() - w;
int ry = getHeight() - h;
if (rx > -1 && ry > -1)
{
x = r.nextInt(rx);
y = r.nextInt(ry);
}
}
showImage = !showImage;
repaint();
}
}
};
Timer timer = new Timer(200, listener);
timer.start();
setPreferredSize(new Dimension(1000, 1000));
JOptionPane.showMessageDialog(null, this);
timer.stop();
}
public void paintComponent(Graphics g)
{
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
if (image != null)
{
g.drawImage(image, x, y,80,80, this);
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ImageBlinking();
}
});
}
}
(Edited:)
I put a Keylistener on your JComponent, then I look if the MouseEvent is on your Image and if its the case, I stop the timer and put the color of the image to Black
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
class BlockBlinking extends JComponent {
BufferedImage image;
boolean showImage;
int x = -1;
int y = -1;
int imageW = 20;
int imageH = 20;
Random r;
private Timer timer;
Color imageColor=null;
BlockBlinking() {
{
try
{
File sourceimage = new File("ball.gif");
image = ImageIO.read(sourceimage);
}
catch (IOException e)
{
e.printStackTrace();
}
this.addMouseListener(new MyMouseListener());
r = new Random();
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (image != null) {
if (!showImage) {
int w = image.getWidth();
int h = image.getHeight();
int rx = getWidth() - w;
int ry = getHeight() - h;
if (rx > -1 && ry > -1) {
x = r.nextInt(rx);
y = r.nextInt(ry);
}
}
showImage = !showImage;
repaint();
}
}
};
timer = new Timer(500, listener);
timer.start();
setPreferredSize(new Dimension(500, 400));
JOptionPane.showMessageDialog(null, this);
timer.stop();
}
}
public void paintComponent(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
if (image != null) {
if(imageColor != null){
Graphics imageGraphic =image.createGraphics();
imageGraphic.setColor(imageColor);
imageGraphic.fillRect(0, 0, image.getWidth(), image.getHeight());
}
g.drawImage(image, x, y,imageW,imageH, this);
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new BlockBlinking();
}
});
}
class MyMouseListener extends MouseAdapter {
#Override
public void mouseReleased(MouseEvent e) {
if (e.getX() >= x && e.getX() <= x + imageW && e.getY() >= y && e.getY() <= y + imageH) {
imageColor = Color.BLACK;
repaint();
timer.stop();
}
}
}
}
Edit: look at the fields imageW and imageH
One approach is to use a JToggleButton.
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
class ImageVanish extends JComponent {
ImageVanish() {
// put your image reading code here..
BufferedImage imageSelected = new BufferedImage(
32,32,BufferedImage.TYPE_INT_ARGB);
BufferedImage image = new BufferedImage(
32,32,BufferedImage.TYPE_INT_ARGB);
Graphics g = image.createGraphics();
g.setColor(Color.ORANGE);
g.fillOval(0,0,32,32);
g.dispose();
// END - image read
JToggleButton b = new JToggleButton();
b.setIcon(new ImageIcon(image));
b.setSelectedIcon(new ImageIcon(imageSelected));
b.setBorderPainted(false);
b.setContentAreaFilled(false);
JOptionPane.showMessageDialog(null, b);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ImageVanish();
}
});
}
}
For the positioning, see #Hovercraft FOE's advice on their answer to your earlier question.